Tuesday, 17 September 2013

WCF Walkthrough

WCF EndPoint

WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.
All the WCF communications are take place through end point. End point consists of three components.

Address

Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service. e.g
http://localhost:8090/MyService/SimpleCalculator.svc

Binding

Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements.
A binding has several characteristics, including the following:
  • Transport -Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.
  • Encoding (Optional) - Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).
  • Protocol(Optional) - Defines information to be used in the binding such as Security, transaction or reliable messaging capability
The following table gives some list of protocols supported by WCF binding.
BindingDescription
BasicHttpBindingBasic Web service communication. No security by default
WSHttpBindingWeb services with WS-* support. Supports transactions
WSDualHttpBindingWeb services with duplex contract and transaction support
WSFederationHttpBindingWeb services with federated security. Supports transactions
MsmqIntegrationBindingCommunication directly with MSMQ applications. Supports transactions
NetMsmqBindingCommunication between WCF applications by using queuing. Supports transactions
NetNamedPipeBindingCommunication between WCF applications on same computer. Supports duplex contracts and transactions
NetPeerTcpBindingCommunication between computers across peer-to-peer services. Supports duplex contracts
NetTcpBindingCommunication between WCF applications across computers. Supports duplex contracts and transactions

Contract

Collection of operation that specifies what the endpoint will communicate with outside world. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client. Each operation is a simple exchange pattern such as one-way, duplex and request/reply.
Below figure illustrate the functions of Endpoint

Example:

Endpoints will be mentioned in the web.config file on the created service.
<system.serviceModel>
<services>
      <service name="MathService"
        behaviorConfiguration="MathServiceBehavior">
       <endpoint
         address="http://localhost:8090/MyService/MathService.svc" contract="IMathService"
          binding="wsHttpBinding"/> 
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MathServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

Binding and Behavior

Binding

Simple definition for Binding describes how the client will communicate with service. We can understand with an example.
Consider a scenario say, I am creating a service that has to be used by two type of client. One of the client will access SOAP using http and other client will access Binary using TCP. How it can be done? With Web service it is very difficult to achieve, but in WCF its just we need to add extra endpoint in the configuration file.
<system.serviceModel>
    <services>
      <service name="MathService"
        behaviorConfiguration="MathServiceBehavior">
      <endpoint address="http://localhost:8090/MyService/MathService.svc" 
        contract="IMathService"
          binding="wsHttpBinding"/>
<endpoint address="net.tcp://localhost:8080/MyService/MathService.svc" 
contract="IMathService"
          binding="netTcpBinding"/> 
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MathServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

  
See how simple it is in WCF. Microsoft is making everything simple.cording to its scope: common behaviors affect all endpoints globally, service behaviors affect only service-related aspects, endpoint behaviors affect only endpoint-related properties, and operation-level behaviors affect particular operations.

Example:

In the below configuration information, I have mentioned the Behavior at Service level. In the service behavior I have mention the servieMetadata node with attribute httGetEnabled='true'. This attribute will specifies the publication of the service metadata. Similarly we can add more behavior to the service.
<system.serviceModel>
    <services>
      <service name="MathService"
        behaviorConfiguration="MathServiceBehavior">
        <endpoint address="" contract="IMathService"
          binding="wsHttpBinding"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MathServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>  

Note:

Application can be controlled either through coding, configuring or through combination of both. Specification mention in the configuration can also be overwritten in code.

WCF Basics

Windows Communication Foundation Basics

Introduction

In this article, I am describing what is Window Communication Foundation (WCF) and why it is introduced in .NET Framework 3.0.

Background

In Modern Application (Distributed Application) development, you can use COM+, .NET Enterprise Services, MSMQ, .NET Remoting, Web services, etc. for communication. All these technologies play a different role and to use it you need to develop different solutions for different technologies. You have to focus on each of the technologies to develop rather than the application business logic.
WCF unifies the capabilities into single, common, general service oriented programming model for Communication. WCF provides a common approach using a common API which developers can focus on their application rather than on communication protocol.
Sample Image - maximum width is 600 pixels

Why Do We Need WCF?

There is one main Bank system which is directly connected with the database, that provides other systems like ATM machine, Loan System data using various communication protocols like Remoting, web service, etc. For communicating with different Systems using different communication protocols, you have to know the API of that technology. In WCF, you have to just make different End points for different services. There is no need to learn a different API. You can use only one common API for communication with different System.
In WCF, you have to just make different End points for different services. There is no need to learn a different API. You can use only one common API for communication with a different System.
Sample Image - maximum width is 600 pixelsSample Image - maximum width is 600 pixels

WCF Architecture

Sample Image - maximum width is 600 pixels

ABC of an EndPoint in WCF

Sample Image - maximum width is 600 pixelsAll communications with the WCF service will happen via the endpoints. The endpoints specify a Contract that defines which methods of the Service class that will be accessible via the endpoint; each endpoint may expose a different set of methods. The endpoints also define a binding that specifies how a client will communicate with the service and the address where the endpoint is hosted.
A-Address(Where?): Specifies the location of the service which will be like http://Myserver/MyService.Clients will use this location to communicate with our service.
//
// The sample address for above transport schema may look like 

http://localhost:81
http://localhost:81/MyService
net.tcp://localhost:82/MyService
net.pipe://localhost/MyPipeService
net.msmq://localhost/private/MyMsMqService
net.msmq://localhost/MyMsMqService

//
B-Binding-Address(How?): Specifies how the two parties will communicate in terms of transport and encoding and protocols.

WCF Supports Nine Types of Bindings

Basic Binding

Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.

TCP Binding

Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.

Peer Network Binding

Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.

IPC Binding

Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.

Web Service (WS) Binding

Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.

Federated WS Binding

Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.

Duplex WS Binding

Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.

MSMQ Binding

Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.

MSMQ Integration Binding

Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.

Choosing Binding Type

Sample Image - maximum width is 600 pixelsC-Contract(What?): Specifies the interface between client and the server. It's a simple interface with some attribute.

Types of Contracts

Sample Image - maximum width is 600 pixels

What are Various Ways of Hosting WCF Services?

There are three major ways of hosting a WCF services:
  • Self-hosting the service in its own application domain. The service comes into existence when you create the object of Service Host class and the service closes when you call the Close of the Service Host class.
  • Host in application domain or process provided by IIS Server.
  • Host in application domain and process provided by WAS (Windows Activation Service) Server.

Choose Type of Hosting

Sample Image - maximum width is 600 pixels

Advantage

  1. WCF is interoperable with other services when compared to .Net Remoting,where the client and service have to be .Net.
  2. WCF services provide better reliability and security in compared to ASMX web services.
  3. In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.
  4. WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.

Disadvantage

Making right design for your requirement is little bit difficult. I will try to help you on solving these difficulties in the following article.

Difference between WCF and Web service

Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service, following table provides detailed difference between them.
FeaturesWeb ServiceWCF
HostingIt can be hosted in IISIt can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming[WebService] attribute has to be added to the class[ServiceContraact] attribute has to be added to the class
Model[WebMethod] attribute represents the method exposed to client[OperationContract] attribute represents the method exposed to client
OperationOne-way, Request- Response are the different operations supported in web serviceOne-Way, Request-Response, Duplex are different type of operations supported in WCF
XMLSystem.Xml.serialization name space is used for serializationSystem.Runtime.Serialization namespace is used for serialization
EncodingXML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, CustomXML 1.0, MTOM, Binary, Custom
TransportsCan be accessed through HTTP, TCP, CustomCan be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
ProtocolsSecuritySecurity, Reliable messaging, Transactions

Wednesday, 11 September 2013

Win Form Basics

Tuesday, 10 September 2013

Working With Delegate

How to declare a delegate?
 To implement a delegate is a four step process declare, create, point and invoke.

 
The first step is to declare the delegate with the same return type and input parameters. For instance the below function ‘add’ has two input integer parameters and one integer output parameter.
private int Add(int i,int y)
{
return i + y;
}

So for the above method the delegate needs to be defined in the follow manner below. Please see the delegate keyword attached with the code.  
// Declare delegate
public delegate int PointetoAddFunction(int i,int y);

The return type and input type of the delegate needs to be compatible, in case they are not compatible it will show the below error as shown in the image below.
 

The next step (second step) is to create a delegate reference.
 
// Create delegate reference
PointetoAddFunction myptr = null;
The third step is to point the delegate reference to the method, currently we need to point the delegate reference to the add function.
 
// Point the reference to the add method
myptr = this.Add;

Finally we need to invoke the delegate function using the “Invoke” function of the delegate.
 
// Invoke the delegate
myptr.Invoke(20, 10)
Below figure sums up how the above four step are map with the code snippet.
 

Solving the abstract pointer problem using delegates 
 

In order to decouple the algorithm changes we can expose all the below arithmetic function through an abstract delegate.
 
So the first step is to add a generic delegate which gives one output and takes two inputs as shown in the below code snippet.
public class clsMaths
{
public delegate int PointerMaths(int i, int y);
}

The next step is to expose a function which takes in operation and exposes an attached delegate to the UI as shown in the below code snippet.
 
public class clsMaths
{
public delegate int PointerMaths(int i, int y);

public PointerMaths getPointer(int intoperation)
{
PointerMaths objpointer = null;
if (intoperation == 1)
{
objpointer = Add;
}
else if (intoperation == 2)
{
objpointer = Sub;
}
else if (intoperation == 3)
{
objpointer = Multi;
}
else if (intoperation == 4)
{
objpointer = Div;
}
return objpointer;
}
}

Below is how the complete code snippet looks like. All the algorithm functions i.e. ‘Add’ , ‘Sub’ etc are made private and only one generic abstract delegate pointer is exposed which can be used to invoke these algorithm function.
public class clsMaths
{
public delegate int PointerMaths(int i, int y);

public PointerMaths getPointer(int intoperation)
{
PointerMaths objpointer = null;
if (intoperation == 1)
{
objpointer = Add;
}
else if (intoperation == 2)
{
objpointer = Sub;
}
else if (intoperation == 3)
{
objpointer = Multi;
}
else if (intoperation == 4)
{
objpointer = Div;
}
return objpointer;
}

private int Add(int i, int y)
{
return i + y;
}
private int Sub(int i, int y)
{
return i - y;
}
private int Multi(int i, int y)
{
return i * y;
}
private int Div(int i, int y)
{
return i / y;
}
}

So at the client side the calls becomes generic without any coupling with the actual method names like ‘Add’ , ‘Sub’ etc.
 
int intResult = objMath.getPointer(intOPeration).Invoke(intNumber1,intNumber2);

Multicast delegates
 

In our previous example we have see how we can create a delegate pointer to a function or method. We can also create a delegate which can point to multiple functions and methods. If we invoke such delegate it will invoke all the methods and functions associated with the same one after another sequentially.
Below is the code snippet which attaches 2 methods i.e. method1 and method2 with delegate ‘delegateptr’. In order to add multiple methods and function we need to use ‘+=’ symbols. Now if we invoke the delegate it will invoke ‘Method1’ first and then ‘Method2’. Invocation happen in the same sequence as the attachment is done.
 
// Associate method1
delegateptr += Method1;
// Associate Method2
delegateptr += Method2;
// Invoke the Method1 and Method2 sequentially
delegateptr.Invoke();

So how we can use multicast delegate in actual projects. Many times we want to create publisher / subscriber kind of model. For instance in an application we can have various error logging routine and as soon as error happens in a application you would like to broadcast the errors to the respective components.
 

Simple demonstration of multicast delegates
 

In order to understand multicast delegates better let’s do the below demo. In this demo we have ‘Form1’, ‘Form2’ and ‘Form3’. ‘Form1’ has a multicast delegate which will propagate event to ‘Form2’ and ‘Form3’.
 
At the form level of ‘Form1’ (this form will be propagating events to form2 and form3) we will first define a simple delegate and reference of the delegate as shown in the code snippet below. This delegate will be responsible for broadcasting events to the other forms.
// Create a simple delegate
public delegate void CallEveryOne();

// Create a reference to the delegate
public CallEveryOne ptrcall=null;
// Create objects of both forms

public Form2 obj= new Form2();
public Form3 obj1= new Form3();

In the form load we invoke the forms and attach ‘CallMe’ method which is present in both the forms in a multicast fashion ( += ).
 
private void Form1_Load(object sender, EventArgs e)
{
// Show both the forms
obj.Show();
obj1.Show();
// Attach the form methods where you will make call back
ptrcall += obj.CallMe;
ptrcall += obj1.CallMe;
}

Finally we can invoke and broadcast method calls to both the forms.
 
private void button1_Click(object sender, EventArgs e)
{
// Invoke the delegate
ptrcall.Invoke();
}

Problem with multicast delegates – naked exposure
 

The first problem with above code is that the subscribers (form2 and form3) do not have the rights to say that they are interested or not interested in the events. It’s all decided by ‘form1’.
We can go other route i.e. pass the delegate to the subscribers and let them attach their methods if they wish to subscribe to the broadcast sent by ‘form1’. But that leads to a different set of problems i.e. encapsulation violation.
If we expose the delegate to the subscriber he can invoke delegate, add his own functions etc. In other words the delegate is completely naked to the subscriber.
 

Events – Encapsulation on delegates
 

Events help to solve the delegate encapsulation problem. Events sit on top of delegates and provide encapsulation so that the destination source can only listen and not have full control of the delegate object.
Below figure shows how the things look like:-
• Method and functions are abstracted /encapsulated using delegates
• Delegates are further extended to provide broadcasting model by using multicast delegate.
• Multicast delegate are further encapsulated using events.
 

Implementing events
 

So let’s take the same example which we did using multicast delegates and try to implement the same using events. Event uses delegate internally as event provides higher level of encapsulation over delegates.
So the first step in the publisher (‘Form1’) we need to define the delegate and the event for the delegate. Below is the code snippet for the same and please do notice the ‘event’ keyword.
We have defined a delegate ‘CallEveryOne’ and we have specified an event object for the delegate called as ‘EventCallEveryOne’.
 
public delegate void CallEveryone();
public event CallEveryone EventCallEveryOne;

From the publisher i.e. ‘Form1’ create ‘Form2’ and ‘Form3’ objects and attach the current ‘Form1’ object so that ‘Form2’ and ‘Form3’ will listen to the events. Once the object is attached raise the events.
 
Form2 obj = new Form2();
obj.obj = this;
Form3 obj1 = new Form3();
obj1.obj = this;
obj.Show();
obj1.Show();
EventCallEveryOne();

At the subscriber side i.e. (Form2 and Form3) attach the method to the event listener.
 
obj.EventCallEveryOne += Callme;

This code will show the same results as we have got from multicast delegate example.
 

Difference between delegates and events
 

So what’s really the difference between delegates and events other than the sugar coated syntax of events. As already demonstrated previously the main difference is that event provides one more level of encapsulation over delegates.
So when we pass delegates it’s naked and the destination / subscriber can modify the delegate. When we use events the destination can only listen to it.
 

Delegates for Asynchronous method calls
 

One of the other uses of delegates is asynchronous method calls. You can call methods and functions pointed by delegate asynchronously.
Asynchronous calling means the client calls the delegate and the control is returned back immediately for further execution. The delegate runs in parallel to the main caller. When the delegate has finished doing his work he makes a call back to the caller intimating that the function / subroutine has completed executing.
 
To invoke a delegate asynchronously we need call the ‘begininvoke’ method. In the ‘begininvoke’ method we need to specify the call back method which is ‘CallbackMethod’ currently.
 
delegateptr.BeginInvoke(new AsyncCallback(CallbackMethod), delegateptr);

Below is the code snippet for ‘CallbackMethod’. This method will be called once the delegate finishes his task.
 
static void CallbackMethod(IAsyncResult result)
{
int returnValue = flusher.EndInvoke(result);
}

Summarizing Use of delegates 

There are 6 important uses of delegates:-
1. Abstract and encapsulate a method (Anonymous invocation)
This is the most important use of delegates; it helps us to define an abstract pointer which can point to methods and functions. The same abstract delegate can be later used to point to that type of functions and methods. In the previous section we have shown a simple example of a maths class. Later addition of new algorithm functions does not affect the UI code.

2. Callback mechanismMany times we would like to provide a call back mechanism. Delegates can be passed to the destination and destination can use the same delegate pointer to make callbacks.

3. Asynchronous processingBy using ‘BeginInvoke’ and ‘EndInvoke’ we can call delegates asynchronously. In our previous section we have explained the same in detail.

4. Multicasting - Sequential processing Some time we would like to call some methods in a sequential manner which can be done by using multicast delegate. This is already explained in the multicast example shown above.

5. Events - Publisher subscriber modelWe can use events to create a pure publisher / subscriber model.
 

Difference between delegates and C++ pointer
 

C++ pointers are not type safe, in other words it can point to any type of method. On the other hand delegates are type safe. A delegate which is point to a return type of int cannot point to a return type of string.

Friday, 6 September 2013

Introduction to ASP.NET Web Programming Using the Razor Syntax (C#)

This article gives you an overview of programming with ASP.NET Web Pages using the Razor syntax. ASP.NET is Microsoft's technology for running dynamic web pages on web servers. This articles focuses on using the C# programming language.
What you'll learn:
  • The top 8 programming tips for getting started with programming ASP.NET Web Pages using Razor syntax.
  • Basic programming concepts you'll need.
  • What ASP.NET server code and the Razor syntax is all about.
Note   The information in this article applies to ASP.NET Web Pages 1.0 and Web Pages 2. Where there are differences between versions, the text describes the differences.

The Top 8 Programming Tips

This section lists a few tips that you absolutely need to know as you start writing ASP.NET server code using the Razor syntax.

Note   The Razor syntax is based on the C# programming language, and that's the language that's used most often with ASP.NET Web Pages. However, the Razor syntax also supports the Visual Basic language, and everything you see you can also do in Visual Basic. For details, see the appendix Visual Basic Language and Syntax.
You can find more details about most of these programming techniques later in the article.

1. You add code to a page using the @ 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>
This is what these statements look like when the page runs in a browser:
Razor-Img1

2. You enclose code blocks in braces

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 result displayed in a browser:
Razor-Img2

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 don't end with a semicolon.
<!-- Single-statement block -->
@{ var theMonth = DateTime.Now.Month; }

<!-- Multi-statement block -->
@{
    var outsideTemp = 79;
    var weatherMessage = "Hello, it is " + outsideTemp + " degrees.";
}

<!-- Inline expression, so no semicolon -->
<p>Today's weather: @weatherMessage</p>

4. You use variables to store values

You can store values in a variable, including strings, numbers, and dates, etc. You create a new variable using thevar 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>
The result displayed in a browser:
Razor-Img3

5. You enclose literal string values in double quotation marks

string is a sequence of characters that are treated as text. To specify a string, you enclose it in double quotation marks:
@{ var myString = "This is a string literal"; }
If the string that you want to display contains a backslash character (\) or double quotation marks ( " ), use averbatim string literal that's prefixed with the @ operator. (In C#, the \ character has special meaning unless you use a verbatim string literal.)
<!-- Embedding a backslash in a string -->
@{ var myFilePath = @"C:\MyFolder\"; }
<p>The path is: @myFilePath</p>
To embed double quotation marks, use a verbatim string literal and repeat the quotation marks:
<!-- Embedding double quotation marks in a string -->
@{ var myQuote = @"The person said: ""Hello, today is Monday."""; }
<p>@myQuote</p>
Here's the result of using both of these examples in a page:
Razor-Img4

Note   Notice that the @ character is used both to mark verbatim string literals in C# and to mark code in ASP.NET pages. 

6. Code is case sensitive

In C#, keywords (like vartrue, and if) and variable names are case sensitive. The following lines of code create 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 your page as@LastName, an error results because LastName won't be recognized.

Note   In Visual Basic, keywords and variables are not case sensitive.

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 web request, an email message, a customer record (database row), etc. Objects have properties that describe their characteristics and that you can read or change — a text box object has a Text property (among others), a request object has aUrl property, an email message has a From property, and a customer object has a FirstName property. Objects also have methods that are the "verbs" they can perform. Examples include a file object's Save method, an image object's Rotate method, and an email object's Send method.
You'll often work with the Request object, which gives you information like the values of text boxes (form fields) on the page, what type of browser made the request, the URL of the page, the user identity, etc. The following example shows how to access properties of the Request object and how to call the MapPath method of theRequest object, which gives you the absolute path of the page on the server:
<table border="1">
<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>
The result displayed in a browser:
Razor-Img5

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. The most 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.";
   }
}

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
<body>
<form method="POST" action="" >
  <input type="Submit" name="Submit" value="Submit"/>
  <p>@result</p>
</form>
</body>
</html>
    </body>
</html>
The statement if(IsPost) is a shorthand way of writing if(IsPost == true). Along with if statements, there are a variety of ways to test conditions, repeat blocks of code, and so on, which are described later in this article.
The result displayed in a browser (after clicking Submit):
Razor-Img6

A Simple Code Example

This procedure shows you how to create a page that illustrates basic programming techniques. In the example, you create a page that lets users enter two numbers, then it adds them and displays the result.
  1. In your editor, create a new file and name it AddNumbers.cshtml.
  2. Copy the following code and markup into the page, replacing anything already in the page.
    @{
        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;
        }
    }
    
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <title>Add Numbers</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">
        <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>
    Here are some things for you to note:
    • The @ character starts the first block of code in the page, and it precedes the totalMessage variable that's embedded near the bottom of the page.
    • The block at the top of the page is enclosed in braces.
    • In the block at the top, all lines end with a semicolon.
    • The variables totalnum1num2, and totalMessage store several numbers and a string.
    • The literal string value assigned to the totalMessage variable is in double quotation marks.
    • Because the code is case-sensitive, when the totalMessage variable is used near the bottom of the page, its name must match the variable at the top exactly.
    • The expression num1.AsInt() + num2.AsInt() shows how to work with objects and methods. TheAsInt method on each variable converts the string entered by a user to a number (an integer) so that you can perform arithmetic on it.
    • The <form> tag includes a method="post" attribute. This specifies that when the user clicks Add, the page will be sent to the server using the HTTP POST method. When the page is submitted, theif(IsPost) test evaluates to true and the conditional code runs, displaying the result of adding the numbers.
  3. Save the page and run it in a browser. (Make sure the page is selected in the Files workspace before you run it.) Enter two whole numbers and then click the Add button.
    Razor-Img7

Basic Programming Concepts

This article provides you with an overview of ASP.NET web programming. It isn't an exhaustive examination, just a quick tour through the programming concepts you'll use most often. Even so, it covers almost everything you'll need to get started with ASP.NET Web Pages.
But first, a little technical background.

The Razor Syntax, Server Code, and ASP.NET

Razor syntax is a simple programming syntax for embedding server-based code in a web page. In a web page that uses the Razor syntax, there are two kinds of content: client content and server code. Client content is the stuff you're used to in web pages: HTML markup (elements), style information such as CSS, maybe some client script such as JavaScript, and plain text.
Razor syntax lets you add server code to this client content. If there's server code in the page, the server runs that code first, before it sends the page to the browser. By running on the server, the code can perform tasks that can be a lot more complex to do using client content alone, like accessing server-based databases. Most importantly, server code can dynamically create client content — it can generate HTML markup or other content on the fly and then send it to the browser along with any static HTML that the page might contain. From the browser's perspective, client content that's generated by your server code is no different than any other client content. As you've already seen, the server code that's required is quite simple.
ASP.NET web pages that include the Razor syntax have a special file extension (.cshtml or .vbhtml). The server recognizes these extensions, runs the code that's marked with Razor syntax, and then sends the page to the browser.

Where does ASP.NET fit in?

Razor syntax is based on a technology from Microsoft called ASP.NET, which in turn is based on the Microsoft .NET Framework. The.NET Framework is a big, comprehensive programming framework from Microsoft for developing virtually any type of computer application. ASP.NET is the part of the .NET Framework that's specifically designed for creating web applications. Developers have used ASP.NET to create many of the largest and highest-traffic websites in the world. (Any time you see the file-name extension .aspx as part of the URL in a site, you'll know that the site was written using ASP.NET.)
The Razor syntax gives you all the power of ASP.NET, but using a simplified syntax that's easier to learn if you're a beginner and that makes you more productive if you're an expert. Even though this syntax is simple to use, its family relationship to ASP.NET and the .NET Framework means that as your websites become more sophisticated, you have the power of the larger frameworks available to you.
Razor-Img8

Basic Syntax

Earlier you saw a basic example of how to create an ASP.NET Web Pages page, and how you can add server code to HTML markup. Here you'll learn the basics of writing ASP.NET server code using the Razor syntax — that is, the programming language rules.
If you're experienced with programming (especially if you've used C, C++, C#, Visual Basic, or JavaScript), much of what you read here will be familiar. You'll probably need to familiarize yourself only with how server code is added to markup in .cshtml files.

Combining Text, Markup, and Code in Code Blocks

In server code blocks, you often want to output text or markup (or both) to the page. If a server code block contains text that's not code and that instead should be rendered as is, ASP.NET needs to be able to distinguish that text from code. There are several ways to do this.
  • Enclose the text in an HTML element like <p></p> or <em></em>:
    @if(IsPost) {
        // This line has all content between matched <p> tags.
        <p>Hello, the time is @DateTime.Now and this page is a postback!</p>
    } else {
        // All content between matched tags, followed by server code.
        <p>Hello <em>stranger</em>, today is: <br /> </p>  @DateTime.Now
    }
    The HTML element can include text, additional HTML elements, and server-code expressions. When ASP.NET sees the opening HTML tag (for example, <p>), it renders everything including the element and its content as is to the browser, resolving server-code expressions as it goes.
  • Use the @: operator or the <text> element. The @: outputs a single line of content containing plain text or unmatched HTML tags; the <text> element encloses multiple lines to output. These options are useful when you don't want to render an HTML element as part of the output.
    @if(IsPost) {
        // Plain text followed by an unmatched HTML tag and server code.
        @: The time is: <br /> @DateTime.Now
        <br/>
        // Server code and then plain text, matched tags, and more text.
        @DateTime.Now @:is the <em>current</em> time.
    }
    If you want to output multiple lines of text or unmatched HTML tags, you can precede each line with @:, or you can enclose the line in a <text> element. Like the @: operator, <text> tags are used by ASP.NET to identify text content and are never rendered in the page output.
    @if(IsPost) {
        // Repeat the previous example, but use <text> tags.
        <text>
        The time is: <br /> @DateTime.Now
        <br/>
        @DateTime.Now is the <em>current</em> time.
        </text>
    }
    
    @{
        var minTemp = 75;
        <text>It is the month of @DateTime.Now.ToString("MMMM"), and
        it's a <em>great</em> day! <br /><p>You can go swimming if it's at
        least @minTemp degrees. </p></text>
    }
    The first example repeats the previous example but uses a single pair of <text> tags to enclose the text to render. In the second example, the <text> and </text> tags enclose three lines, all of which have some uncontained text and unmatched HTML tags (<br />), along with server code and matched HTML tags. Again, you could also precede each line individually with the @: operator; either way works.

    Note   When you output text as shown in this section — using an HTML element, the @:operator, or the <text> element — ASP.NET doesn't HTML-encode the output. (As noted earlier, ASP.NET does encode the output of server code expressions and server code blocks that are preceded by @, except in the special cases noted in this section.)

Whitespace

Extra spaces in a statement (and outside of a string literal) don't affect the statement:
@{ var lastName =    "Smith"; }
A line break in a statement has no effect on the statement, and you can wrap statements for readability. The following statements are the same:
@{ var theName =
"Smith"; }

@{
    var
    personName
    =
    "Smith"
    ;
} 
However, you can't wrap a line in the middle of a string literal. The following example doesn't  work:
@{ var test = "This is a long
    string"; }  // Does not work!
To combine a long string that wraps to multiple lines like the above code, there are two options. You can use the concatenation operator (+), which you'll see later in this article. You can also use the @ character to create a verbatim string literal, as you saw earlier in this article. You can break verbatim string literals across lines:
@{ var longString = @"This is a
    long
    string";
}

Code (and Markup) Comments

Comments let you leave notes for yourself or others. They also allow you to disable (comment out) a section of code or markup that you don't want to run but want to keep in your page for the time being.
There's different commenting syntax for Razor code and for HTML markup. As with all Razor code, Razor comments are processed (and then removed) on the server before the page is sent to the browser. Therefore, the Razor commenting syntax lets you put comments into the code (or even into the markup) that you can see when you edit the file, but that users don't see, even in the page source.
For ASP.NET Razor comments, you start the comment with @* and end it with *@. The comment can be on one line or multiple lines:
@*  A one-line code comment. *@

@*
    This is a multiline code comment.
    It can continue for any number of lines.
*@ 
Here is a comment within a code block:
@{
    @* This is a comment. *@
    var theVar = 17;
} 
Here is the same block of code, with the line of code commented out so that it won't run:
@{
    @* This is a comment. *@
    @* var theVar = 17;  *@
} 
Inside a code block, as an alternative to using Razor comment syntax, you can use the commenting syntax of the programming language you're using, such as C#:
@{
    // This is a comment.
    var myVar = 17;
    /* This is a multi-line comment
    that uses C# commenting syntax. */
}
In C#, single-line comments are preceded by the // characters, and multi-line comments begin with /* and end with */. (As with Razor comments, C# comments are not rendered to the browser.)
For markup, as you probably know, you can create an HTML comment:
<!-- This is a comment.  -->
HTML comments start with <!-- characters and end with -->. You can use HTML comments to surround not only text, but also any HTML markup that you may want to keep in the page but don't want to render. This HTML comment will hide the entire content of the tags and the text they contain:
<!-- <p>This is my paragraph.</p>  -->
Unlike Razor comments, HTML comments are rendered to the page and the user can see them by viewing the page source.

Variables

A variable is a named object that you use to store data. You can name variables anything, but the name must begin with an alphabetic character and it cannot contain whitespace or reserved characters.

Variables and Data Types

A variable can have a specific data type, which indicates what kind of data is stored in the variable. You can have string variables that store string values (like "Hello world"), integer variables that store whole-number values (like 3 or 79), and date variables that store date values in a variety of formats (like 4/12/2012 or March 2009). And there are many other data types you can use.
However, you generally don't have to specify a type for a variable. Most of the time, ASP.NET can figure out the type based on how the data in the variable is being used. (Occasionally you must specify a type; you'll see examples where this is true.)
You declare a variable using the var keyword (if you don't want to specify a type) or by using the name of the type:
@{
    // Assigning a string to a variable.
    var greeting = "Welcome!";

    // Assigning a number to a variable.
    var theCount = 3;

    // Assigning an expression to a variable.
    var monthlyTotal = theCount + 5;

    // Assigning a date value to a variable.
    var today = DateTime.Today;

    // Assigning the current page's URL to a variable.
    var myPath = this.Request.Url;

    // Declaring variables using explicit data types.
    string name = "Joe";
    int count = 5;
    DateTime tomorrow = DateTime.Now.AddDays(1);
}
The following example shows some typical uses of variables in a web page:
@{
    // Embedding the value of a variable into HTML markup.
    <p>@greeting, friends!</p>

    // Using variables as part of an inline expression.
    <p>The predicted annual total is: @( monthlyTotal * 12)</p>

    // Displaying the page URL with a variable.
    <p>The URL to this page is: @myPath</p>
}
If you combine the previous examples in a page, you see this displayed in a browser:
Razor-Img9

Converting and Testing Data Types

Although ASP.NET can usually determine a data type automatically, sometimes it can't. Therefore, you might need to help ASP.NET out by performing an explicit conversion. Even if you don't have to convert types, sometimes it's helpful to test to see what type of data you might be working with.
The most common case is that you have to convert a string to another type, such as to an integer or date. The following example shows a typical case where you must convert a string to a number.
@{
    var total = 0;

    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();
    }
}
As a rule, user input comes to you as strings. Even if you've prompted users to enter a number, and even if they've entered a digit, when user input is submitted and you read it in code, the data is in string format. Therefore, you must convert the string to a number. In the example, if you try to perform arithmetic on the values without converting them, the following error results, because ASP.NET cannot add two strings:
Cannot implicitly convert type 'string' to 'int'.
To convert the values to integers, you call the AsInt method. If the conversion is successful, you can then add the numbers.
The following table lists some common conversion and test methods for variables.
Method
Description
Example
AsInt(),
IsInt()
Converts a string that represents a whole number (like "593") to an integer.
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 a decimal 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 a decimal value like "1.3" or "7.439" to a decimal number. (In ASP.NET, a decimal number is more precise than a floating-point number.)
var myStringDec = "10317.425";
var myDecNum = myStringDec.AsDecimal(); 
AsDateTime(),
IsDateTime()
Converts a string that represents a date and time value to the ASP.NET DateTime type.
var myDateString = "12/27/2012";
var newDate = myDateString.AsDateTime();
ToString()
Converts any other data type to a string.
int num1 = 17;
int num2 = 76;
// myString is set to 1776
string myString = num1.ToString() +
  num2.ToString();

Operators

An operator is a keyword or character that tells ASP.NET what kind of command to perform in an expression. The C# language (and the Razor syntax that's based on it) supports many operators, but you only need to recognize a few to get started. The following table summarizes the most common operators.
Operator
Description
Examples
+
-
*
/
Math operators used in numerical expressions.
@(5 + 13)
@{ var netWorth = 150000; }
@{ var newTotal = netWorth * 2; }
@(newTotal / 2)
=
Assignment. Assigns the value on the right side of a statement to the object on the left side.
var age = 17;
==
Equality. Returns true if the values are equal. (Notice the distinction between the =operator and the ==operator.)
var myNum = 15;
if (myNum == 15) {
    // Do something.
} 
!=
Inequality. Returns true if the values are not equal.
var theNum = 13;
if (theNum != 15) {
    // Do something.
}
<
>
<=
>=
Less-than,
greater-than,
less-than-or-equal, and
greater-than-or-equal.
if (2 < 3) {
    // Do something.
}
var currentCount = 12;
if(currentCount >= 12) {
    // Do something.
}
+
Concatenation, which is used to join strings. ASP.NET knows the difference between this operator and the addition operator based on the data type of the expression.
// The displayed result is "abcdef".
@("abc" + "def")
+=
-=
The increment and decrement operators, which add and subtract 1 (respectively) from a variable.
int theCount = 0;
theCount += 1; // Adds 1 to count
.
Dot. Used to distinguish objects and their properties and methods.
var myUrl = Request.Url;
var count = Request["Count"].AsInt();
()
Parentheses. Used to group expressions and to pass parameters to methods.
@(3 + 7)
@Request.MapPath(Request.FilePath);
[]
Brackets. Used for accessing values in arrays or collections.
var income = Request["AnnualIncome"];
!
Not. Reverses a true value to false and vice versa. Typically used as a shorthand way to test forfalse (that is, for not true).
bool taskCompleted = false;
// Processing.
if(!taskCompleted) {
    // Continue processing
}
&&
||
Logical AND and OR, which are used to link conditions together.
bool myTaskCompleted = false;
int totalCount = 0;
// Processing.
if(!myTaskCompleted && totalCount < 12) {
    // Continue processing.
}

Working with File and Folder Paths in Code

You'll often work with file and folder paths in your code. Here is an example of physical folder structure for a website as it might appear on your development computer:
C:\WebSites\MyWebSite
    default.cshtml
    datafile.txt
    \images
        Logo.jpg
    \styles
        Styles.css
 Here are some essential details about URLs and paths:
  • A URL begins with either a domain name (http://www.example.com) or a server name (http://localhost,http://mycomputer).
  • A URL corresponds to a physical path on a host computer. For example, http://myserver might correspond to the folder C:\websites\mywebsite on the server.
  • A virtual path is shorthand to represent paths in code without having to specify the full path. It includes the portion of a URL that follows the domain or server name. When you use virtual paths, you can move your code to a different domain or server without having to update the paths.
Here's an example to help you understand the differences:
Complete URLhttp://mycompanyserver/humanresources/CompanyPolicy.htm
Server namemycompanyserver
Virtual path/humanresources/CompanyPolicy.htm
Physical pathC:\mywebsites\humanresources\CompanyPolicy.htm
The virtual root is /, just like the root of your C: drive is \. (Virtual folder paths always use forward slashes.) The virtual path of a folder doesn't have to have the same name as the physical folder; it can be an alias. (On production servers, the virtual path rarely matches an exact physical path.)
When you work with files and folders in code, sometimes you need to reference the physical path and sometimes a virtual path, depending on what objects you're working with. ASP.NET gives you these tools for working with file and folder paths in code: the Server.MapPath method, and the ~ operator and Href method.

Converting virtual to physical paths: the Server.MapPath method

The Server.MapPath method converts a virtual path (like /default.cshtml) to an absolute physical path (likeC:\WebSites\MyWebSiteFolder\default.cshtml). You use this method any time you need a complete physical path. A typical example is when you're reading or writing a text file or image file on the web server.
You typically don't know the absolute physical path of your site on a hosting site's server, so this method can convert the path you do know — the virtual path — to the corresponding path on the server for you. You pass the virtual path to a file or folder to the method, and it returns the physical path:
@{
    var dataFilePath = "~/dataFile.txt";
}
<!-- Displays a physical path C:\Websites\MyWebSite\datafile.txt  -->
<p>@Server.MapPath(dataFilePath)</p>

Referencing the virtual root: the ~ operator and Href method

In a .cshtml or .vbhtml file, you can reference the virtual root path using the ~ operator. This is very handy because you can move pages around in a site, and any links they contain to other pages won't be broken. It's also handy in case you ever move your website to a different location. Here are some examples:
@{
    var myImagesFolder = "~/images";
    var myStyleSheet = "~/styles/StyleSheet.css";
}
If the website is http://myserver/myapp, here's how ASP.NET will treat these paths when the page runs:
  • myImagesFolderhttp://myserver/myapp/images
  • myStyleSheet : http://myserver/myapp/styles/Stylesheet.css
(You won't actually see these paths as the values of the variable, but ASP.NET will treat the paths as if that's what they were.)
In ASP.NET Web Pages 2, you can use the ~ operator both in server code (as above) and in markup, like this:
<!-- Examples of using the ~ operator in markup in ASP.NET Web Pages 2 -->
<!-- (Using the ~ operator like this in markup is not supported in ASP.NET
     Web Pages 1.0) -->

<a href="~/Default">Home</a>
<img src="~/images/MyImages.png" />
In markup, you use the ~ operator to create paths to resources like image files, other web pages, and CSS files. When the page runs, ASP.NET looks through the page (both code and markup) and resolves all the ~ references to the appropriate path.
In ASP.NET Web Pages 1, you can use the ~ operator in server code blocks, like the first example above. But in order to use it in markup, you have to put the ~ operator inside a call to the Href method. (ASP.NET does not parse through the markup looking for the ~ operator.)
For example, you can use the Href method in HTML markup for attributes of <img> elements, <link> elements, and <a> elements. Notice that the Href method is preceded by @ to mark it as server code. Also notice that theHref method is inside the double quotation marks that enclose attribute values.
<!-- Examples of using the Href method in ASP.NET Web Pages 1.0 to include
     the ~ operator in markup. -->

<a href="@Href("~/Default")">Home</a>

<!-- This code creates the path "../images/Logo.jpg" in the src attribute. -->
<img src="@Href("~/images")/Logo.jpg" />

<!-- This creates a link to the CSS file using ther server variable. -->
<link rel="stylesheet" type="text/css" href="@Href(myStyleSheet)" />

Conditional Logic and Loops

ASP.NET server code lets you perform tasks based on conditions and write code that repeats statements a specific number of times (that is, code that runs a loop).

Testing Conditions

To test a simple condition you use the if statement, which returns true or false based on a test you specify:
@{
  var showToday = true;
  if(showToday)
  {
    @DateTime.Today;
  }
}
The if keyword starts a block. The actual test (condition) is in parentheses and returns true or false. The statements that run if the test is true are enclosed in braces. An if statement can include an else block that specifies statements to run if the condition is false:
@{
  var showToday = false;
  if(showToday)
  {
    @DateTime.Today;
  }
  else
  {
    <text>Sorry!</text>
  }
}
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>
    }
}
In this example, if the first condition in the if block is not true, the else if condition is checked. If that condition is met, the statements in the else if block are executed. If none of the conditions are met, the statements in theelse block are executed. You can add any number of else if blocks, and then close with an else block as the "everything else" condition.
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>
}
The value to test is in parentheses (in the example, the weekday variable). Each individual test uses a casestatement that ends with a colon (:). If the value of a case statement matches the test value, the code in that case block is executed. You close each case statement with a break statement. (If you forget to include break in eachcase block, the code from the next case statement will run also.) A switch block often has a default statement as the last case for an "everything else" option that runs if none of the other cases are true.
The result of the last two conditional blocks displayed in a browser:
Razor-Img10

Looping Code

You often need to run the same statements repeatedly. You do this by looping. For example, you often run the same statements for each item in a collection of data. If you know exactly how many times you want to loop, you can use a for loop. This kind of loop is especially useful for counting up or counting down:
@for(var i = 10; i < 21; i++)
{
    <p>Line #: @i</p>
}
The loop begins with the for keyword, followed by three statements in parentheses, each terminated with a semicolon.
  • Inside the parentheses, the first statement (var i=10;) creates a counter and initializes it to 10. You don't have to name the counter i — you can use any variable. When the for loop runs, the counter is automatically incremented.
  • The second statement (i < 21;) sets the condition for how far you want to count. In this case, you want it to go to a maximum of 20 (that is, keep going while the counter is less than 21).
  • The third statement (i++ ) uses an increment operator, which simply specifies that the counter should have 1 added to it each time the loop runs.
Inside the braces is the code that will run for each iteration of the loop. The markup creates a new paragraph (<p>element) each time and adds a line to the output,  displaying the value of i (the counter). When you run this page, the example creates 11 lines displaying the output, with the text in each line indicating the item number.
Razor-Img11

If you're working with a collection or array, you often use a foreach loop. A collection is a group of similar objects, and the foreach loop lets you carry out a task on each item in the collection. This type of loop is convenient for collections, because unlike a for loop, you don't have to increment the counter or set a limit. Instead, the foreach loop code simply proceeds through the collection until it's finished.
For example, the following code returns the items in the Request.ServerVariables collection, which is an object that contains information about your web server. It uses a foreach loop to display the name of each item by creating a new <li> element in an HTML bulleted list.
<ul>
@foreach (var myItem in Request.ServerVariables)
{
    <li>@myItem</li>
}
</ul>
The foreach keyword is followed by parentheses where you declare a variable that represents a single item in the collection (in the example, var item), followed by the in keyword, followed by the collection you want to loop through. In the body of the foreach loop, you can access the current item using the variable that you declared earlier.
Razor-Img12
To create a more general-purpose loop, use the while statement:
@{
    var countNum = 0;
    while (countNum < 50)
    {
        countNum += 1;
        <p>Line #@countNum: </p>
    }
}
while loop begins with the while keyword, followed by parentheses where you specify how long the loop continues (here, for as long as countNum is less than 50), then the block to repeat. Loops typically increment (add to) or decrement (subtract from) a variable or object used for counting. In the example, the += operator adds 1 tocountNum each time the loop runs. (To decrement a variable in a loop that counts down, you would use the decrement operator -=).

Objects and Collections

Nearly everything in an ASP.NET website is an object, including the web page itself. This section discusses some important objects you'll work with frequently in your code.

Page Objects

The most basic object in ASP.NET is the page. You can access properties of the page object directly without any qualifying object. The following code gets the page's file path, using the Request object of the page:
@{
    var path = Request.FilePath;
}
To make it clear that you're referencing properties and methods on the current page object, you can optionally use the keyword this to represent the page object in your code. Here is the previous code example, with thisadded to represent the page:
@{
    var path = this.Request.FilePath;
}
You can use properties of the Page object to get a lot of information, such as:
  • Request. As you've already seen, this is a collection of information about the current request, including what type of browser made the request, the URL of the page, the user identity, etc.
  • Response. This is a collection of information about the response (page) that will be sent to the browser when the server code has finished running. For example, you can use this property to write information into the response.
    @{
        // Access the page's Request object to retrieve the Url.
        var pageUrl = this.Request.Url;
    }
    <a href="@pageUrl">My page</a>

Collection Objects (Arrays and Dictionaries)

collection is a group of objects of the same type, such as a collection of Customer objects from a database. ASP.NET contains many built-in collections, like the Request.Files collection.
You'll often work with data in collections. Two common collection types are the array and the dictionary. An array is useful when you want to store a collection of similar items but don't want to create a separate variable to hold each item:
@* Array block 1: Declaring a new array using braces. *@
@{
    <h3>Team Members</h3>
    string[] teamMembers = {"Matt", "Joanne", "Robert", "Nancy"};
    foreach (var person in teamMembers)
    {
        <p>@person</p>
    }
}
With arrays, you declare a specific data type, such as stringint, or DateTime. To indicate that the variable can contain an array, you add brackets to the declaration (such as string[] or int[]). You can access items in an array using their position (index) or by using the foreach statement. Array indexes are zero-based — that is, the first item is at position 0, the second item is at position 1, and so on.
@{
    string[] teamMembers = {"Matt", "Joanne", "Robert", "Nancy"};
    <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>
    }
}
You can determine the number of items in an array by getting its Length property. To get the position of a specific item in the array (to search the array), use the Array.IndexOf method. You can also do things like reverse the contents of an array (the Array.Reverse method) or sort the contents (the Array.Sort method).
The output of the string array code displayed in a browser:
Razor-Img13
A dictionary is a collection of key/value pairs, where you provide the key (or name) to set or retrieve the corresponding value:
@{
    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>
To create a dictionary, you use the new keyword to indicate that you're creating a new dictionary object. You can assign a dictionary to a variable using the var keyword. You indicate the data types of the items in the dictionary using angle brackets ( < > ). At the end of the declaration, you must add a pair of parentheses, because this is actually a method that creates a new dictionary.
To add items to the dictionary, you can call the Add method of the dictionary variable (myScores in this case), and then specify a key and a value. Alternatively, you can use square brackets to indicate the key and do a simple assignment, as in the following example:
myScores["test4"] = 79;
To get a value from the dictionary, you specify the key in brackets:
var testScoreThree = myScores["test3"];

Calling Methods with Parameters

As you read earlier in this article, the objects that you program with can have methods. For example, a Databaseobject might have a Database.Connect method. Many methods also have one or more parameters. A parameteris a value that you pass to a method to enable the method to complete its task. For example, look at a declaration for the Request.MapPath method, which takes three parameters:
public string MapPath(string virtualPath, string baseVirtualDir, 
    bool allowCrossAppMapping);
(The line has been wrapped to make it more readable. Remember that you can put line breaks almost any place except inside strings that are enclosed in quotation marks.)
This method returns the physical path on the server that corresponds to a specified virtual path. The three parameters for the method are virtualPathbaseVirtualDir, and allowCrossAppMapping. (Notice that in the declaration, the parameters are listed with the data types of the data that they'll accept.) When you call this method, you must supply values for all three parameters.
The Razor syntax gives you two options for passing parameters to a method: positional parameters and named parameters. To call a method using positional parameters, you pass the parameters in a strict order that's specified in the method declaration. (You would typically know this order by reading documentation for the method.) You must follow the order, and you can't skip any of the parameters — if necessary, you pass an empty string ("") or null for a positional parameter that you don't have a value for.
The following example assumes you have a folder named scripts on your website. The code calls theRequest.MapPath method and passes values for the three parameters in the correct order. It then displays the resulting mapped path.
@{
    // Pass parameters to a method using positional parameters.
    var myPathPositional = Request.MapPath("/scripts", "/", true);
}
<p>@myPathPositional</p>
When a method has many parameters, you can keep your code more readable by using named parameters. To call a method using named parameters, you specify the parameter name followed by a colon (:), and then the value. The advantage of named parameters is that you can pass them in any order you want. (A disadvantage is that the method call is not as compact.)
The following example calls the same method as above, but uses named parameters to supply the values:
@{
    // Pass parameters to a method using named parameters.
    var myPathNamed = Request.MapPath(baseVirtualDir: "/", 
        allowCrossAppMapping: true, virtualPath: "/scripts");
}
<p>@myPathNamed</p>
As you can see, the parameters are passed in a different order. However, if you run the previous example and this example, they'll return the same value.

Handling Errors

Try-Catch Statements

You'll often have statements in your code that might fail for reasons outside your control. For example:
  • If your code tries to create or access a file, all sorts of errors might occur. The file you want might not exist, it might be locked, the code might not have permissions, and so on.
  • Similarly, if your code tries to update records in a database, there can be permissions issues, the connection to the database might be dropped, the data to save might be invalid, and so on.
In programming terms, these situations are called exceptions. If your code encounters an exception, it generates (throws) an error message that's, at best, annoying to users:
Razor-Img14
In situations where your code might encounter exceptions, and in order to avoid error messages of this type, you can use try/catch statements. In the try statement, you run the code that you're checking. In one or more catchstatements, you can look for specific errors (specific types of exceptions) that might have occurred. You can include as many catch statements as you need to look for errors that you are anticipating.

Note   We recommend that you avoid using the Response.Redirect method in try/catchstatements, because it can cause an exception in your page.
The following example shows a page that creates a text file on the first request and then displays a button that lets the user open the file. The example deliberately uses a bad file name so that it will cause an exception. The code includes catch statements for two possible exceptions: FileNotFoundException, which occurs if the file name is bad, and DirectoryNotFoundException, which occurs if ASP.NET can't even find the folder. (You can uncomment a statement in the example in order to see how it runs when everything works properly.)
If your code didn't handle the exception, you would see an error page like the previous screen shot. However, thetry/catch section helps prevent the user from seeing these types of errors.
@{
    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(@"c:\batafile.txt");

            // This code works. To eliminate error on page,