Thursday, September 13, 2012

Consistent Look Razor in MVC


@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
<title>Main Page</title>
<link href="@Href("../../Content/styles/Style.css")" rel="stylesheet" type="text/css" />
</head><body>
<div class="header">This is header text.</div>
<h1>Index Page Content</h1>
@Html.ActionLink("Content", "Content1", "Helper")
@Html.ActionLink("MultiSection Content", "Content2", "Helper")
@Html.ActionLink("Passing Data", "Content3", "Helper")
<p>This is the content of the main page.</p>
<div class="footer">&copy; 2010 Contoso Pharmaceuticals. All rights reserved.</div>
</body></html>


h1 
{
    border-bottom: 3px solid #cc9900;
    font: 2.75em/1.75em Georgia, serif;
    color: #996600;
}
ul 
{
    list-style-type: none;
}
body 
{
    margin: 0;
    padding: 1em;
    background-color: #ffffff;
    font: 75%/1.75em "Trebuchet MS", Verdana, sans-serif;
    color: #006600;
}
#list 
{
    margin: 1em 0 7em -3em;
    padding: 1em 0 0 0;
    background-color: #ffffff;
    color: #996600;
    width: 25%;
    float: left;
}
#header, #footer
{
    margin: 0;
    padding: 0;
    color: #996600;
}



Handling Errors In MVC


 @{var dataFilePath = "~/dataFile.txt";
 
 var fileContents = "";
 var physicalPath = Server.MapPath(dataFilePath);
 var userMessage = "Hello world, the time is " + DateTime.Now;
 var userErrMsg = "";
 var errMsg = "";
 if(IsPost)
 {
 // When the user clicks the "Open File" button and posts
 // the page, try to open the created file for reading.
 try {
    // This code fails because of faulty path to the file.
    fileContents = File.ReadAllText(@"K:\batafile.txt");
    // This code works. To eliminate error on page,
    // comment the above line of code and uncomment this one.
    fileContents = File.ReadAllText(physicalPath);
 }
 catch (FileNotFoundException ex)
  {
     // You can use the exception object for debugging, logging, etc.errMsg = ex.Message;
    // Create a friendly error message for users.
    userErrMsg = "A file could not be opened, please contact "+ "your system administrator.";
    }
    catch (DirectoryNotFoundException ex)
    {
    // Similar to previous exception.
    errMsg = ex.Message;
    userErrMsg = "A directory was not found, please contact "+ "your system administrator.";
    }
 }
 else
 {
     // The first time the page is requested, create the text file.
     File.WriteAllText(physicalPath, userMessage);
 }
 }

 <!DOCTYPE html>
 <html lang="en">
 <head><meta charset="utf-8" />
 <title>Try-Catch Statements</title>
 </head><body>
 <form method="post" action="" >
 <input type="submit" name="Submit" value="Open File"/>
 </form>
 <p>@fileContents</p>
 <p>@userErrMsg</p>
 </body>
 </html>

Objects and Collections


Objects and Collections

Page Objects

The most basic object in ASP.NET is the page. You can access properties of the page object directlywithout any qualifying object. The following code gets the page's file path, using the Request object of the page:

        @{var path = Request.FilePath;}
        @path
        @{
        var pageUrl = this.Request.Url;
        }
        <br />
        <a href="@pageUrl">My page</a>
 
/Helper/Objects
My page

Collection Objects (Arrays and Dictionaries)

        @{

        <h3>Team Members</h3>

            string[] teamMembers = {"Matt", "Joanne", "Robert", "Nancy"};

            foreach (var person in teamMembers)

            {

                <p>@person</p>

            }

          }

@{ 
             <p>The number of names in the teamMembers array: @teamMembers.Length </p>
             <p>Robert is now in position: @Array.IndexOf(teamMembers, "Robert")</p>
             <p>The array item at position 2 (zero-based) is @teamMembers[2]</p>
             <h3>Current order of team members in the list</h3>
              foreach (var name in teamMembers){<p>@name</p>}
            <h3>Reversed order of team members in the list</h3>
              Array.Reverse(teamMembers);
              foreach (var reversedItem in teamMembers){<p>@reversedItem</p>}
            }

Team Members

Matt
Joanne
Robert
Nancy
The number of names in the teamMembers array: 4
Robert is now in position: 2
The array item at position 2 (zero-based) is Robert

Current order of team members in the list

Matt
Joanne
Robert
Nancy

Reversed order of team members in the list

Nancy
Robert
Joanne
Matt

Dictionary


            @{var myScores = new Dictionary<string, int>();
              myScores.Add("test1", 71);
              myScores.Add("test2", 82);
              myScores.Add("test3", 100);
              myScores.Add("test4", 59);}
              <p>My score on test 3 is: @myScores["test3"]%</p>
              @(myScores["test4"] = 79)
              <p>My corrected score on test 4 is: @myScores["test4"]%</p>          


My score on test 3 is: 100%
79 My corrected score on test 4 is: 79%

Conditional Logic and Loops in MVC


Conditional Logic and Loops

ASP.NET server code lets you perform tasks based on conditions and write code that repeats statementsa specific number of times (loops).

Testing Conditions

To test a simple condition you use the if statement, which returns true or false based on a test youspecify:


 @{var showToday = true;if(showToday){@DateTime.Today;}}

        @{
            showToday = false;
            if(showToday)
            {
                @DateTime.Today;
            }
            else
            {
                <br />
                <text>Sorry!</text>
            }}



9/13/2012 12:00:00 AM
Sorry!

If else Code

You can add multiple conditions using an else if block:


@{
            var theBalance = 4.99;
           if(theBalance == 0)
           {  
                      <p>You have a zero balance.</p>          
           }
            else if (theBalance > 0 && theBalance <= 5)
            {
            <p>Your balance of $@theBalance is very low.</p>
            }
            else
            {
            <p>Your balance is: $@theBalance</p>
            }
            }



Your balance of $4.99 is very low.

Switch case Code

To test a large number of conditions, use a switch block:


 @{
                var weekday = "Wednesday";
                var greeting = "";
                switch (weekday)
                {
                    case "Monday":
                        greeting = "Ok, it's a marvelous Monday";
                        break;
                    case "Tuesday":
                        greeting = "It's a tremendous Tuesday";
                        break;
                    case "Wednesday":
                        greeting = "Wild Wednesday is here!";
                        break;
                    default:
                        greeting = "It's some other day, oh well.";
                        break;
                }
                <p>Since it is @weekday, the message for today is: @greeting</p>
                }



Since it is Wednesday, the message for today is: Wild Wednesday is here!

For Looping Code

 @for(var i = 10; i < 21; i++){<p style="font-size: @(i + "pt")">My font size is now: @i</p>}

My font size is now: 10
My font size is now: 11
My font size is now: 12
My font size is now: 13
My font size is now: 14
My font size is now: 15
My font size is now: 16
My font size is now: 17
My font size is now: 18
My font size is now: 19
My font size is now: 20

For each Looping Code

<ul>@foreach (var myItem in Request.ServerVariables){<li>@myItem</li>}</ul>
  • ALL_HTTP
  • ALL_RAW
  • APPL_MD_PATH
  • APPL_PHYSICAL_PATH
  • AUTH_TYPE
  • AUTH_USER
  • AUTH_PASSWORD
  • LOGON_USER
  • REMOTE_USER
  • CERT_COOKIE
  • CERT_FLAGS
  • CERT_ISSUER
  • CERT_KEYSIZE
  • CERT_SECRETKEYSIZE
  • CERT_SERIALNUMBER
  • CERT_SERVER_ISSUER
  • CERT_SERVER_SUBJECT
  • CERT_SUBJECT
  • CONTENT_LENGTH
  • CONTENT_TYPE
  • GATEWAY_INTERFACE
  • HTTPS
  • HTTPS_KEYSIZE
  • HTTPS_SECRETKEYSIZE
  • HTTPS_SERVER_ISSUER
  • HTTPS_SERVER_SUBJECT
  • INSTANCE_ID
  • INSTANCE_META_PATH
  • LOCAL_ADDR
  • PATH_INFO
  • PATH_TRANSLATED
  • QUERY_STRING
  • REMOTE_ADDR
  • REMOTE_HOST
  • REMOTE_PORT
  • REQUEST_METHOD
  • SCRIPT_NAME
  • SERVER_NAME
  • SERVER_PORT
  • SERVER_PORT_SECURE
  • SERVER_PROTOCOL
  • SERVER_SOFTWARE
  • URL
  • HTTP_CONNECTION
  • HTTP_ACCEPT
  • HTTP_ACCEPT_ENCODING
  • HTTP_ACCEPT_LANGUAGE
  • HTTP_COOKIE
  • HTTP_HOST
  • HTTP_REFERER
  • HTTP_USER_AGENT
  • HTTP_DNT

While Looping Code

@{var countNum = 0;while (countNum < 50){countNum += 1;<p>Line #@countNum: </p>}}

Line #1:
Line #2:
Line #3:
Line #4:
Line #5:
Line #6:
Line #7:
Line #8:
Line #9:
Line #10:
Line #11:
Line #12:
Line #13:
Line #14:
Line #15:
Line #16:
Line #17:
Line #18:
Line #19:
Line #20:
Line #21:
Line #22:
Line #23:
Line #24:
Line #25:
Line #26:
Line #27:
Line #28:
Line #29:
Line #30:
Line #31:
Line #32:
Line #33:
Line #34:
Line #35:
Line #36:
Line #37:
Line #38:
Line #39:
Line #40:
Line #41:
Line #42:
Line #43:
Line #44:
Line #45:
Line #46:
Line #47:
Line #48:
Line #49:
Line #50:

Working with File and Folder Paths in Code in MVC


@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Files</title>
</head>
<body>
    <div>
        <h1>The ~ operator: Getting the virtual root</h1>
        @{
            var myImagesFolder = "../../Content/images";
            var myStyleSheet = "../../Content/Site.css";
            }

            <h1>The Server.MapPath method: Converting virtual to physical paths</h1>
            @{var dataFilePath = "~/dataFile.txt";}
            <!-- Displays a physical path C:\Websites\MyWebSite\datafile.txt -->
            <p>@Server.MapPath(dataFilePath)</p>


            <h1>The Href method: Creating paths to site resources</h1>
            <!--This code creates the path "../images/Logo.jpg" in the src attribute. -->
           
            <img src="@Href(myImagesFolder)/Chrysanthemum.jpg" alt="Image" width="100px" height="100px" />
            <br /><br />
            <!-- This produces the same result, using a path with ~ -->
            <img src="@Href("../../Content/images")/Chrysanthemum.jpg" alt="Image" width="100px" height="100px" />
            <!-- This creates a link to the CSS file. -->
            <link rel="stylesheet" type="text/css" href="@Href(myStyleSheet)" />

    </div>
</body>
</html>

Output:

D:\MyProjects\Registrationmvc3PArt2\CabAutomationSystem\CabAutomationSystem\dataFile.txt


Add Numbers in MVC



@{
    Layout = null;
}

 <!DOCTYPE html>
 <html lang="en">
 <head>
 <title>My Title</title>
 <meta charset="utf-8" />
 <style type="text/css">
     body
     {
         background-color: beige; font-family: Verdana, Arial;margin: 50px;
          }
          form
          {padding: 10px; border-style: solid; width: 250px;}
          </style>
          </head>
          <body>
          <p>
          Enter two whole numbers and then click
          <strong>Add</strong>.</p>
          <form action="" method="post">
          @{
            var total = 0;
            var totalMessage = "";
            if(IsPost)
             {
             @*Retrieve the numbers that the user entered.*@
             var num1 = Request["text1"];
             var num2 = Request["text2"];
             @*Convert the entered strings into integers numbers and add.*@
             total = num1.AsInt() + num2.AsInt();
             totalMessage = "Total = " + total;
             }
             }
          <p>
          <label for="text1">First Number:</label>
          <input type="text" name="text1" />
          </p><p>
          <label for="text2">Second Number:</label>
          <input type="text" name="text2" />
          </p><p>
          <input type="submit" value="Add" />
          </p>
          </form>
          <p>@totalMessage</p>
          </body>
          </html>



The Top 8 Programming Tips in MVC

1.You add code to a page using @ Character

The @ character starts inline expressions, single statement blocks, and multi-statement blocks:


<!-- Single statement blocks -->
       @{ var total = 7; }
       @{ var myMessage = "Hello World"; }
       <!-- Inline expressions --><p>
       The value of your account is: @total </p>
       <p>The value of myMessage is: @myMessage</p>
       <!-- Multi-statement block -->
       @{
         var greeting = "Welcome to our site!";
         var weekDay = DateTime.Now.DayOfWeek;
         var greetingMessage = greeting + " Today is: " + weekDay;

        }
        <p>The greeting is: @greetingMessage</p>


The value of your account is: 7
The value of myMessage is: Hello World
The greeting is: Welcome to our site! Today is: Thursday

2. You enclose code blocks in braces

A code block includes one or more code statements and is enclosed in braces.:


<!-- Single statement block. -->
        @{ var theMonth = DateTime.Now.Month; }
        <p>The numeric value of the current month: @theMonth</p>
        <!-- Multi-statement block. -->
        @{
            var outsideTemp = 79;
             var weatherMessage = "Hello, it is " + outsideTemp + " degrees.";
          }
                                                                                                                                                                       
        <p>Today's weather: @weatherMessage</p>

The numeric value of the current month: 9
Today's weather: Hello, it is 79 degrees.

3. Inside a block, you end each code statement with a semicolon

Inside a code block, each complete code statement must end with a semicolon. Inline expressions donot end with a semicolon.:

4. You use variables to store values

You can store values in a variable , including strings, numbers, and dates, etc. You create a new variableusing the var keyword. You can insert variable values directly in a page using @ :


<!-- Storing a string -->
         @{ var welcomeMessage = "Welcome, new members!"; }
         <p>@welcomeMessage</p>
         <!-- Storing a date -->
         @{ var year = DateTime.Now.Year; }
         <!-- Displaying a variable -->
         <p>Welcome to our new members who joined in @year!</p>


Welcome, new members!
Welcome to our new members who joined in 2012!

5. You enclose literal string values in double quotation marks

A string is a sequence of characters that are treated as text. To specify a string, you enclose it in doublequotation marks:


@{ var myString = "This is a string literal"; }
          <p>Literal : @myString</p>
          <!-- Embedding a backslash in a string -->
          @{ var myFilePath = @"C:\MyFolder\"; }
          <p>The path is: @myFilePath</p>


          <!-- Embedding double quotation marks in a string -->
          @{ var myQuote = @"The person said: ""Hello, today is Monday."""; }
          <p>@myQuote</p>


Literal : This is a string literal
The path is: C:\MyFolder\
The person said: "Hello, today is Monday."

6. Code is case sensitive

In C#, keywords ( var, true, if ) and variable names are case sensitive.
The following lines of codecreate two different variables, lastName and LastName.
@{var lastName = 'Smith';var LastName = 'Jones';}
If you declare a variable as var lastName = "Smith"; and if you try to reference that variable in yourpage as @LastName , an error results because LastName won't be recognized.

7. Much of your coding involves objects

An object represents a thing that you can program with — a page, a text box, a file, an image, a webrequest, an email message, a customer record (database row), etc.


<table border="1" style="width:400px">
            <tr>
            <td>Requested URL</td>
            <td>Relative Path</td>
            <td>Full Path</td>
            <td>HTTP Request Type</td>
            </tr>
            <tr>
            <td>@Request.Url</td>
            <td>@Request.FilePath</td>
            <td>@Request.MapPath(Request.FilePath)</td>
            <td>@Request.RequestType</td>
            </tr>
            </table>



8. You can write code that makes decisions

A key feature of dynamic web pages is that you can determine what to do based on conditions. Themost common way to do this is with the if statement (and optional else statement).


@{var result = "";
              if(IsPost)
              {
                  result = "This page was posted using the Submit button.";
              }
              else
              {
                  result = "This was the first request for this page.";
              }
              }
              <input type="submit" name="Submit" value="Submit"/>
              <p>@result</p>


This was the first request for this page.

Current System Time Display in MVC


@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Time</title>
</head>
<body>
    <div>
        <h1>Hello World Page</h1>
        <p>Hello World !</p>
        <p>The Time is @DateTime.Now</p>
    </div>
</body>
</html>



Operators inMVC


Operator

Description

Example

.

Dot. Used to distinguish objects and theirproperties and methods.

var myUrl = Request.Url;var count =Request["Count"].AsInt();

()

Parentheses. Used to group expressions and topass parameters to methods.

@(3 + 7)@Request.MapPath(Request.FilePath);

[]

Brackets. Used for accessing values in arrays orcollections.

var income =Request["AnnualIncome"];

=

Assignment. Assigns the value on the right side of a statement to the object on the left side. (Noticethe distinction between the = operator and the == operator.)

var age = 17;

!

Not. Reverses a true value to false and viceversa. Typically used as a shorthand way to testfor false (that is, for not true ).

bool taskCompleted = false;// Processing.if(!taskCompleted) {// Continue processing}

==

Equality. Returns true if the values are equal.

var myNum = 15;if (myNum == 15) {// Do something.}

!=

Inequality. Returns true if the values are notequal.

var theNum = 13;if (theNum != 15) {// Do something.}

<

>


<=

>=

Less-than,greater-than,less-than-or-equal, andgreater-than-or-equal.

if (2 < 3) {// Do something.} var currentCount = 12; if(currentCount >= 12) {// Do something.}

+

Math operators used in numerical expressions.

@(5 + 13)@{ var netWorth = 150000; }@{ var newTotal = netWorth * 2; }

Classes in MVC


Method

Description

Example

AsInt(),IsInt()

Converts a string that representsa whole number (like "93") to aninteger.

var myIntNumber = 0;var myStringNum = "539";if(myStringNum.IsInt()==true){myIntNumber = myStringNum.AsInt();}

AsBool(),IsBool()

Converts a string like "true" or"false" to a Boolean type.

var myStringBool = "True";var myVar = myStringBool.AsBool();

AsFloat(),IsFloat()

Converts a string that has adecimal value like "1.3" or "7.439"to a floating-point number.

var myStringFloat = "41.432895";var myFloatNum = myStringFloat.AsFloat();

AsDecimal(),IsDecimal()

Converts a string that has adecimal value like "1.3" or "7.439"to a decimal number.

(A decimalnumber is more precise than afloating-point number.)
var myStringDec = "10317.425";var myDecNum = myStringDec.AsDecimal();

AsDateTime(),IsDateTime()

Converts a string that representsa date and time value to theASP.NET DateTime type.

var myDateString = "12/27/2010";var newDate = myDateString.AsDateTime();

ToString()

Converts any other data type to astring.

int num1 = 17;int num2 = 76;// myString is set to 1776string myString = num1.ToString() +num2.ToString();

Using Authorization with Swagger in ASP.NET Core

 Create Solution like below LoginModel.cs using System.ComponentModel.DataAnnotations; namespace UsingAuthorizationWithSwagger.Models {     ...