Introduction to ASP.NET MVC using C#

Getting Started
Start by running Visual Studio 2010  and select New Project from the Start page.

Visual Studio 2010 - Start Page
Visual Studio 2010 – Start Page
Creating Your First Application
You can create ASP.NET MVC Web applications using either Visual Basic or Visual C# as the programming language. Select Visual C# on the left and then select ASP.NET MVC 2 Web Application. Name your project “MvcBook” and then click OK.
ASP.NET MVC 2 Web Application
ASP.NET MVC 2 Web Application

This creates a simple “Hello World!” MVC project

MVC Home Controller Page
MVC Home Controller Page

Click Debug menu, select Start Debugging or Press F5

Visual Studio launches a browser and opens the application’s home page.
MVC 2 Application Home Page
MVC 2 Application Home Page


ASP.NET Web Application Security

ASP.NET with IIS, can authenticate user credentials such as names and passwords using any of the following authentication methods:

•Windows: Basic, digest, or Integrated Windows Authentication (NTLM or Kerberos).
•Microsoft Passport authentication
•Forms authentication
•Client Certificate authentication

ASP.NET has two security functions i.e Authentication and Authorization.

Authentication  – Helps to verify the user. Tells who the user is ?
Authorization – Limits access rights by granting or denying specific permissions to an authenticated identity

Cross Page Posting in ASP.NET Page

The Server.Transfer method can be used to move between webpages. This does not change the URL
In ASP.NET 2.0 , cross page posting feature was introduced . This allows one to fire a normal post back to a different page in the application. In the target page, one can then access the values of server controls in the source page that initiated the postback.
To use cross page posting, one can set the PostBackUrl property of a Button, LinkButton or ImageButton control, which specifies the target page.
In the target page, one can access the PreviousPage property to retrieve values from the source page. By default, the PreviousPage property is of type Page, so you must access controls using the FindControl
method. You can also enable strongly-typed access to the source page by setting the @PreviousPageType directive in the target page to the virtual path or Type name of the source page.

√ Create a Web Form Source.aspx and insert a Button control on it using the VS .NET designer.
√ Set the button’s PostBackUrl property to the Web Form you want to post back. For example in this case it is “Target.aspx”

Now how to access Source page controls value in target page :

Page sourcePage = this.PreviousPage;
Then you can find any control from the previous page and read its state:
TextBox sourceTextBox = sourcePage.FindControl(“TextBox1”)).Text;
string value = sourceTextBox.Text;

ASP.NET Error Handling and Tracing

ASP.NET introduces tracing functionality which allows one to view diagnostic information about a single request for an ASP.NET page simply by enabling it for your page or application.
Page Tracing Steps

Add trace directive at top of page
<%@ Page Trace=“True” %>

Add trace calls throughout page
Trace.Write(“Button Event Clicked”)
Trace.Warn(“Data Value: “ + checkValue)

Access page from browser

Trace Information generated :

Enabling Application-Level Tracing
To enable application level tracing add following line in Web.config :

<trace enabled=”true” localonly=”false” requestlimit=”40″>
Error Handling

All runtime errors is handled by exceptions.Exception would contain full stack information with error information.Exception handling is done using try/catch/finally/throw blocks and statements.

ASP.NET also provides declarative application custom error handling

  1. Enable programmatic logging of problems
  2. Automatically redirect users to error page when unhandled exceptions occur

Application_error is global applicaion event raised if unhandled exception occurs.This provides access to Current Request object. Also , provides access to Exception object. This enables developers to log and track errors.
One can use EventLog class to write custom logs in Application_Error event. Also one can use SmtpMail class to send mails to administrators.

NT Event Log

Dim LogName As String = “MyAppLog”
Sub Application_Start(Sender as Object, E as EventArgs)

If (Not EventLog.SourceExists(LogName)) Then

EventLog.CreateEventSource(LogName, LogName)

End if

End Sub

Sub Application_Error(Sender as Object, E as EventArgs)

Dim Message As String = “Url ” & Request.Path & ” Error: ” & Me.Error.ToString()

Dim Log as New EventLog

Log.Source = LogName

Log.WriteEntry(Message, EventLogEntryType.Error)

End Sub

Sending SMTP Mail

Sub Application_Error(Sender as Object, E as EventArgs)

Dim MyMessage as New MailMessage

MyMessage.To = “”

MyMessage.From = “MyAppServer”

MyMessage.Subject = “Unhandled Error”

MyMessage.BodyFormat = MailFormat.Html

MyMessage.Body = Request.Path  + Me.Error.ToString();


End Sub

Understanding ASP.Net Configuration settings

The properties and behavior of the ASP .Net application are determined by the settings contained within the specific files called as the configuration files. There are two types of configuration files as follows:


This file gets automatically installed on the server in the %windows%Microsoft .NetFramework[version]Config file at the time of installation of .Net. This is at the highest level and contains the defaults configuration settings for all the Web Applications that are hosted on the server.


When you create an ASP.Net Web Application the file gets automatically created in the project. This file contains the settings specific to an individual application. In addition to it, this file also inherits settings from the Machine.config. However it is possible to override those settings in web.config.

Logically, the complete configuration file can be divided into two parts:

Configuration section handler declaration: All the elements included with configSection tags are collectively called as configuration section handler declarations. All the configuration sections must be declared only once for all applications. This is because all applications inherit the configuration settings in the Machine.config file and therefore, the sections need not be declared again in the Web.config files.

Actual configuration section settings: This part contains the actual configuration sections. All tags defined in this section control the behavior of the ASP.Net runtime. There is one configuration section for each declaration in the configSections part. These configuration sections contain subsections with attributes that contain the settings for that section.

Digging into each section of the configuration files

• httpRuntime section:

General HTTP runtime settings include the time for which a request is processed before being timedout. The maximum length of the web request and whether or not to use the fully qualified URLs for the client redirects.


 executionTimeout: represents the time for which a web request is processed before the application times out. The default value is 90.

If you think your web application will take more time to process (e.g. in case of large database access) then you can increase this value.

 maxRequestLength: represents the maximum size of the web request in kilobytes. The default value is 1096KB.If the content of the web request is large (e.g. in upload sites) you can increase this value.

 useFullyQualifiedRedirectUrl: represents whether or not fully qualified URLs may be used for the client redirects. If takes a Boolean values and by default it is false.

appSettings section:

You can specify custom settings in this section. This section uses a set of key value pairs which in turn populates a hash table that you can access from your application. E.g. you can set your DSN name in the section and access it using the key associated with it. The values set in this section can be accessed from the application by using the ConfigurationSetting object as ConfigurationSettings.Appsettings(“<>”);

compilation section

The compilation section is where you can specify the settings related to the compilation of the ASP.Net application. Some of the settings that you can specify include the default language to be used for the dynamic compilation and whether or not to enable the explicit declaration feature of VB. It also enables you to add additional CLR compiler such as COBOL in this section and to specify the assemblies to link during compilation.


 language: specifies the language to be used

 extension: specifies the extension of the code behind file for the page.

 type: specifies the class to be used for compilation.

Sub Section

 assemblies: it is a sub section which lists the assemblies that are used during compilation.

customErrors section:

All settings related to custom error messages can be specified in this section


 defaultRedirect: the URL to which client browser should be redirected when an error occurs.

 mode: The mode in which custom errors function. The possible values taken are:

1. On : Custom errors are enabled. This value prohibits the display of original error messages in the client browser.

2. Off : Custom errors are disabled. This value forces the display of original error messages even if the custom errors pages are available.

 RemoteOnly: Custom error messages are shown to the remote clients only.

Sub Section:

 error: it is the sub section which takes two different attributes namely statusCode and redirect. The stausCode attribute represents the staus code of the error that redirect client browser to corresponding error page The redirect attribute represent the URL to which the client browser should be redirected.

trace section:

This feature enables you to trace the execution of the web application. To trace the execution of individual pages in the web application you can set Trace=”true” in the @page directive. But if you want to trace the execution of all the pages i.e. if you want application level tracing then setting Trace=”true” in all files will be quite cumbersome. In such cases you can use trace section of the config file.


 enabled: Indicate whether or not application level tracing is enabled. This attribute takes Boolean value . The default value is false indicating that tracing is not enabled.

 requestLimit: Indicates the maximum number of trace request to be stored in the server cache. The default value is 10.

 pageOutput: Indicates whether or not the trace information is displayed for each page in the application. The default value is false. When the trace information is not displayed it is available via trace.axd.

 traceMode: Indicates the sequence in which trace message are displayed. The possible values are sortByTime or sortByCategory. The default value is sortByTime.

 localOnly: Indicates whether the trace message is available for only client request(localhost) or also for the remote clients. It takes a Boolean value. The default value is true.

• sessionState section

You can use the session object provided in ASP .Net to perform the user-wise data maintenance and tracking on your web application. The configuration settings pertaining to the session state are contained in the sessionState section of the config file.


 Mode: this attribute specifies where to store session state data and takes one of the below four values.

1. Off: Indicates that the session is not enabled and thus no user session data is maintained and tracked.

2. Inproc: Indicates that the session state data is stored within the ASP .Net process. This is the default value for the mode attribute.

3. StateServer: Indicates that the session data is stored outside the ASP .Net process on some remote server(Windows NT service).

4. SqlServer: Indicates that the session data is stored outside the ASP .Net process on the SQL server.

 stateConnectionString: This attribute species the TCP/IP address and the port number of the remote server where the session state data is stored. You must set this attribute the mode is StateServer.

 sqlConnectionString: This attribute specifies the connection string for the Sql server where the session state data is stored. You must set this attribute when the mode is SqlServer.

 Cookieless: This attribute take a Boolean value and indicates whether or not the session state should be enabled for the clients that do not support HTTP cookies.

 Timeout: This attribute indicates the time in minutes for which the session can remain idle The default is 20.

authentication section

This section is used to define the settings related to the authentication of the Web requests on the server. It involves establishing identity between the server and the request.


 mode: The mode attribute can take one of the following values:

1. Windows: Indicates the ASP.Net authentication as the default authentication mode.

2. Forms: Indicates Microsoft passport authentication as the default authentication.

3. None: Indicates no authentication is used. It means anonymous access is allowed for your web application.

Sub Section:

 forms: If the mode attribute is set to Forms then this subsection is used then its behavior can be set in this sub section.

Attributes: the name of the HTTP cookie to be used for authentication. The default is .ASPXAUTH.

2.loginUrl: Represents the URL to which the user is redirected for login when no other valid cookie is found. The default value is default.aspx. Represents both the data validation and encryption of the HTTP cookie used for forms based authentication. It can take one of the following values.

i. All: Indicating both data validation and encryption is performed.

ii.None: Indicates that neither data validation nor encryption is performed.

iii.Encryption: Indicates that the encryption of the cookie is enabled.

iv. Validation: Indicates that the data validation of the cookie is enabled.

4. timeOut: Represents the time in minutes after which the cookies expires. The default us 30.

5. path: Represents the path of the cookie. The default is “/”, which indicates the root server.

Sub Section:

 credentials: it can be used to define username and password in the configuration file and takes one attribute, passwordFormat, which specifies the encryption format for storing the passwords. The possible values are MD5, SHA1 and Clear.

 user: it provides two attributes username and password.

authorization section

ASP.Net enables you to allow or deny access to your application resources by using this section.

Sub Section:

 allow: to allow access.

 deny: to deny access.

Attributes for the above sub sections:

1. users: Species a comma separated list of users who are given/denied access to the resources. Default is “*” indicating all users.”?” Is used to specify anonymous access.

2. roles: Specifies a comma separated list of roles that are given/denied access to the resources.

3. verbs: Specifies a comma separated list of HTTP transmission methods such as GET,HEAD or POST that are given/denied access to the resources.

httpHandlers section:

ASP.Net runtime uses this section to handle different requests from different Web requests such as for .aspx files, .ascx files etc. In this section you can create your own mappings for some custom web requests with the respective class and assembly.

Sub Section:

 add: to add mappings for some custom web requests.

 remove: to remove mappings.

 clear: to remove all handler entries in the configuration files.

Attributes for the above sub section:

 verb: Specifies a comma separated list of HTTP verbs, which should be mapped to the class or assembly specified in the type attribute.”*” indicates all HTTP requests.

 Path: Specifies the URL path or a wild card string(e.g. “*.aspx”) for which mapping should be performed.

 Type: Specifies a comma separated list of class and assembly combination that implement the HTTP handler code.

• globalization section:

You can access and specify locale-Specific configuration information in the globalization section


 requestEncoding: Represents the way the request data is encoded. The default value is set to “utf-8” which indicates an encoding system that represents a character as sequence of 8 bit bytes.

 responseEncoding: Represents the way the response data is encoded. The default value is set to “utf-8”

 fileEncoding: Represents the way the ASPX,ASMX and ASAX files are encoded.

 culture: Represents the culture string that is used to set the localized settings, such as the user interface language, the date time format and fonts of the application.

 uiCulture: Represents the culture string to be used to search for resources.

You can also have page level locale specific settings by setting the above attributes in the @Page directive.

Advantages of the ASP.Net Configuration files

• ASP .Net configuration files are XML based making it easy to read and write.

• Any modification made to the configuration files takes effect immediately. Unlike ASP, you need not restart the Web Server.

• The ASP .Net configuration settings are applied in a hierarchical manner, thus we can have different settings for different applications and different setting for different parts of the application.

• ASP. Net configuration system is extensible i.e. you can create custom configuration handler. This extensibility can then be used at runtime to affect the processing of the HTTP request.

ASP.NET Application Deployment

ASP.NET Application Deployment

Once an application has been developed and tested ,application is ready for deployment to client machines. The goal of deployment is the simple and easy installation of application files and any other required files to a client machine.

Types of deployment


– Used for simple applications
– Application copied directly to the target machine.

2. Windows Installer

– Used for complex applications
– Creates fully configurable setup projects.

XCOPY Deployment

  1. MS-DOS XCOPY command is used to copy the contents of a directory and subdirectories to a target directory.

  2. Accomplished from the command prompt. Eg: XCOPY E:MyApplication D:MyApplication /s


1. Works only for applications that have no external dependencies

2. Works only if the .NET framework is installed on every target machine.

Window Installer Deployment

Windows Installer projects are fully configurable for a variety of deployment plans. You can create a setup project for your application by adding a setup project to an existing solution.

Setup projects are used for deploying executable applications. A merge module, on the other hand, deploys controls or components that do not exist as stand-alone applications and cannot be deployed directly.

 Kinds of setup projects:

  1. Setup

  2. Merge Module

Can be created using Setup Project Wizard.

Steps to create Windows Installer

Step 1 : Use the Setup Project Wizard

Step 2: Build

Step 3: Distribute

Step 4: Deploy


ASP.NET Tutorial : Getting started with ASP.NET

ASP.NET Tutorial : Getting started with ASP.NET

ASP.NET allows one to create dynamic web applications

We will create a simple Hello World program

Step 1: Open Microsoft Visual Studio 2008 using Start->Programs -> Microsoft Visual Studio 2008

Microsoft Visual Studio 2008
Microsoft Visual Studio 2008

Step 2 : Click on File -> New -> Website

Click on File -> New -> Website
Click on File -> New -> Website


Step 3: Select File System and Visual C# and enter project name “HelloWorld”

Select File System and Visual C# and enter project name
Select File System and Visual C# and enter project name

Step 4: Drag and Drop Label control from Toolbar to div tag and set Text Property to “Hello World”

Drag and Drop Label control from Toolbar to div tag and set Text Property
Drag and Drop Label control from Toolbar to div tag and set Text Property






Step 5: Click on Debug button to run Hello World web site