WebMatrix Tutorial – Getting Started

In this WebMatrix Tutorial we will look at getting started with using WebMatrix and look at the new ASP.NET Pages coding method.

Introduction to WebMatrix

WebMatrix is a fully integrated development environment for building ASP.NET web apps. Currently developing an ASP.NET web will require using Visual Studio, IIS and SQL Server Management Studio all of which complicated tools in their own right. WebMatrix is Microsoft’s attempt to integrate a coding tool, database development tool and web server admin tool in one simple application for rapid application development.

WebMatrix incorporates several new technologies and tools from Microsoft which should make development faster and more simple. First is IIS Express, Visual Studio ships with an inbuilt  web server which is very convenient for testing during development but it is not 100% compatible with IIS 7 or 7.5 and so issues often arise when running the app in production. IIS Express which is incorporated into WebMatrix is a fully compatible but scaled down version of IIS meaning that developers can safely deploy apps that are only tested using the development environment. SQL Server Compact Edition 4 is the database incorporated into WebMatrix, the major innovation in SQL Server CE 4 is that it does not require any database server to run, you  simply build the tables etc in WebMatrix and just ftp the binaries created and the database will run (even on shared servers without admin privileges). Finally the web coding  itself features a simpler interface and the new lean ASP.NET Web pages  ”Razor” syntax syntax. The Razor syntax allows you to easily embed anywhere code in your page using the @ character and is definitely leaner and quicker to work with that the previous model of strictly separating code and markup (although this may not be as suitable for very large projects).

Getting Started with WebMatrix

Currently WebMatrix is in Beta (although it is still robust for  developing apps) and can be downloaded here.

Installation is a simple process (although you will be prompted to download and install Web Platform Installer 3.0 and ASP.NET 4.0 if you do not already have them). On your first run WebMatrix will present you with the below page:

WebMatrix Tutorial

You are presented with four options :

  • My Sites – which is the sites you previously used on WebMatrix
  • Site From Web Gallery – this is a similar listing of open source web-app projects as provided in the Web Platform Installer. Selecting a project such as Umbraco will install it as well as create and configure any associated databases.
  • Site From Template – WebMatrix ships with a limited number of pre-built site templates, none of which are especially useful for any purposes other than training.
  • Site From Folder – Allows you to open sites which were not previously opened with WebMatrix.

It isn’t immediately obvious from this list how to create a new site, but click Site From Web Gallery, then select Empty Site and click OK:

WebMatrix Tutorial


Using XML with DataSets

The disconnected data access model of ADO.NET is centered on DataSets. DataSets are the core of ADO.NET architecture and represent an in memory representation of the database. They can be used with a wide variety of data sources and contain one or more DataTable objects. These DataTable objects in turn comprise of one or more DataRows and DataColumns. While the DataTable object represents every table within a DataSet; the DataColumn and the DataRow objects represent the columns and rows within a DataTable. The DataSet class provides a seamless support for XML. Using XML, we can use the DataSet class in ADO.NET to perform the CRUD (Create, Read, Update and Delete) operations without an underlying database to store the data. This article discusses how we can use DataSets and XML – considered by many as a perfect combination to perform the CRUD operations devoid of any underlying database to hold data.

What are DataSets?

A DataSet is in effect an in-memory representation of cached, disconnected data that is available as a as a collection of tables, relationships, constraints, etc. In other words, a DataSet is actually an in-memory representation of the entire database along with its tables and relationships.


The DataSet class is contained in the System.Data namespace in ADO.NET. The DataSet class has the ability to represent itself as XML upon request or when you pass it through the tiers or components of an application.

The primary advantage in using DataSets in applications is its disconnected approach that enables data to be transferred across application boundaries. The primary disadvantage of using DataSets however that is it consumes large amount of memory that is particularly a nightmare if your DataSet contains high volume of data. Hence, it becomes detrimental to the application’s performance when the DataSet contains large amount of data due to excessive consumption of memory.

DataSet and XML – A perfect match

Before we delve deep any further, let us have a recap of XML. What is XML and why is it so useful? Extensible Markup Language (XML) is a simple, platform independent, flexible meta-markup language that provides a format for storing structured data and is great for efficient exchange of data across the internet. XML has rapidly gained wide popularity and the enterprise applications the world over are using XML as the primary format for data exchange across the globe.

The salient features of this language are:–

  • Robust
  • Support for UNICODE
  • Hierarchical structure
  • Platform Independent
  • Present in human readable format
  • Can support even complex data structures

Now that we have had a quick tour of XML, let us discuss the support for XML provided by the DataSet class in ADO.NET.

The DataSet class in ADO.NET contains a lot of methods that provide XML support. The following are some of the most important methods of this class:–

  • The ReadXml Method
  • The ReadXmlSchema Method
  • The GetXml Method
  • The GetXmlSchema Method
  • The WriteXml Method
  • The WriteXmlSchema Method

While the ReadXML, GetXML and WriteXML methods deal with the data as XML representation devoid of any schema, the ReadXMlSchema, WriteXMLSchema and the GetXMLSchema methods represent the schema only. These methods would become much clear as we move on to the next section where working (for CRUD operations) with DataSet instances and XML has been illustrated. //break//

Working with DataSet and XML

This section discusses how we can perform the CRUD operations using DataSet and XML as the database to store the data.

ASP.NET Caching Tutorial – Part 1

The ability to store data in the main memory and then allow for retrieval of the same as and when they are requested is one of the major factors that can yield high performance and scalable applications. This results in a gain in the application’s overall throughput by serving the subsequent requests for data from the Cache rather than recreating them or retrieving them from the database or any other storage device that works much slower compared to the main memory. This is one of the most striking features in Microsoft’s ASP.NET compared to its earlier counterparts and has been enhanced further with the introduction of the new release of ASP.NET (ASP.NET 2.0). This is the first in the series of articles on Caching in ASP.NET and discusses Caching, its types, benefits and the new features of Caching in ASP.NET 2.0.

Caching types, Cache Dependencies and Cache Expirations

ASP.NET features several different types of caching namely  Page Output Caching, Page Fragment Caching and Data Caching. In Page Output Caching, the entire page is cached in memory so all the subsequent requests for the same page are addressed from the cache itself. In Page Fragment Caching, a specific a portion of the page is cached and not the entire page.  Page Output or Fragment Caching can be enabled or disabled at the Page, Application or even the Machine levels.

Data Caching allows us to cache frequently used data and then retrieve the same data from the cache as and when it is needed. We can also set dependencies so that the data in the cache gets refreshed whenever there is a change in the external data store. The external data store can be a file or even a database. Accordingly, there are two types to dependencies, namely, file based and Sql Server based. There are also differing cache expiration policies.

New Caching features in ASP.NET 2.0

ASP.NET 2.0 has introduced a lot of new features in Caching. This new version of ASP.NET includes an excellent feature called automatic database server cache invalidation which is in turn based on database triggered cache invalidation technique. This powerful and easy-to-use feature enables us to output cache database-driven page and partial page content within a site and then leave it to ASP.NET invalidate these cache entries automatically and refresh the content whenever the there are any changes in the database. This ensures that the data in the Cache is in sync with that of the database. Note that the Cache API in ASP.NET 1.x does not allow you to invalidate an item in the cache when the data in the database changes. It is possible to invalidate cached data based on pre-defined conditions that relate to any change in the data in an external data store on which the dependency has been set. The data gets deleted from the Cache with any change in the data in the external data storage. However, the cached data cannot be refreshed directly.

ASP.NET 2.0 also features numerous enhancements to the Cache API. The CacheDependency class of ASP.NET 1.x was sealed to prevent further inheritance.
Thus preventing extension of this class to provide custom cache dependency features. ASP.NET 2.0 Cache API provides the ability to create custom cache dependency classes that are inherited from the CacheDependency class. I would discuss all these issues in details in the subsequent articles in this series of articles on Caching in ASP.NET applications.

Page Caching in ASP.NET

There are two types of Page caching, namely, Page Output Caching and Page Fragment Caching. Page Fragment Caching is also known Partial Page Caching.

Page Output Caching

Page Output Caching is the most basic form of caching. The output caching simply maintains a copy of the HTML which was sent in response to a memory request. Subsequent requests are then given the cached output until the cache expires.

ASP.NET Caching Tutorial – Part 2

Continuing from ASP.NET Caching Part 1

Caching is an essential feature of ASP.NET that reduces latency and the network traffic by storing frequently used data and pages in the Cache for quick retrieval later; hence greatly boosting the application’s performance. We have had a detailed look at the concepts of Caching in the first part of this series of articles on Caching in ASP.NET. This article presents Data Caching, a feature of ASP.NET that allows you to store your data in the cache memory for faster retrieval. It also discusses the Cache API and the Cache expiration strategies. As in the earlier articles in this series, it also throws light on the related newly added features in ASP.NET 2.0 Caching.

Data Caching using the Cache API

Data Caching is a feature that enables us to store frequently used data in the Cache. The Cache API was introduced in ASP.NET 1.x and was quite exhaustive and powerful. However, it did not allow you to invalidate an item in the Cache based on a change of data in a Sql Server database table. With ASP.NET 2.0, the Cache API provides you a database triggered Cache invalidation technique that enables you to invalidate the data in the Cache based on any change of data in the Sql Server database table. Besides this, you can also create custom cache dependencies.

The Cache class contains a numerous properties and methods. Of these, the Add, Insert, Remove methods and the Count property are the most frequently used. The Add/Insert method of the Cache class is used to add/insert an item into the cache. The Remove method removes a specified item from the cache. The Count property returns the current number of objects in the Cache.

The Cache property of the Page.HttpContext class can be used to store and retrieve data in the cache. The following code snippet illustrates the simplest way of storage and retrieval of data to and from the cache using the Cache class.

//Storing data

Cache ["key"] = objValue;

//Retrieving the data

object  obj = Cache ["key"];

We can also check for the existence of the data in the cache prior to retrieving the same. This is shown in the code snippet below:

object obj = null;
 if(Cache["key"] != null)

obj = Cache["key"];

The following code snippet illustrates how we can make use of the Cache API to store and retrieve data from the Cache. The method GetCountryList checks to see if the data (list of countries) exists in the cache. If so, it is retrieved from the cache; else, the GetCountryListFromDatabase method fills the DataSet from the database and then populates the Cache.

public DataSet GetCountryList()

string key = "Country";
DataSet ds = Cache[key] as DataSet;

if (ds == null)
ds = GetCountryListFromDatabase ();
Cache.Insert(cacheKey, ds, null, NoAbsoluteExpiration,
TimeSpan.FromHours(5),CacheItemPriority.High, null);

return ds;
} //End of method GetCountryList

public DataSet GetCountryListFromDatabase ()

// Necessary code to retrieve the list of countries from the database and
// store the same in a DataSet instance, which in turn is returned to the
// GetCountryList method.


Cache Dependency and Cache Expiration Strategies

Cache dependency implies a logical dependency between the data in the Cache and physical data storage.

ASP.NET Sever Side State Management

1. Application Object

The Application object provides a mechanism for storing data that is accessible to all code running within the Web application,The ideal data to insert into application state variables is data that is sharedby multiple sessions and does not change often.. And just because it is visibleto the entire application, you need to used Lock and UnLock pair to avoid having conflit value.


2. Session Object

The Session object can be used for storing session-specific information that needs to be maintained between server round trips and between requests for pages. Session object is per-client basis, which means different clients generate different session object.The ideal data to store in session-state variables is short-lived, sensitive data that is specific to an individual session.

Each active ASP.NET session is identified and tracked using a 120-bit SessionID string containing URL-legal ASCII characters.SessionID values are generated using an algorithm that guarantees uniqueness so that sessions do not collide,and SessionID’s randomness makes it harder to guess the session ID of an existing session.
SessionIDs are communicated across client-server requests either by an HTTP cookie or amodified URL, depending on how you set the application’s configuration settings.So how to set the session setting in application configuration? Ok, let’s go further to look at it.

Every web application must have a configuration file named web.config, it is a XML-Based file, there is a section name ‘sessionState’, the following is an example:

<sessionState mode=”InProc”stateConnectionString=”tcpip=″ sqlConnectionString=”datasource=;user id=sa;password=” cookieless=”false” timeout=”20″/>

‘cookieless’ option can be‘true’ or ‘false’. When it is‘false’(default value), ASP.NET will use HTTP cookie to identify users. When it is ‘true’, ASP.NET will randomly generate a unique number and put it just right ahead of the requested file, this number is used to identify users, you can see it on the address bar ofIE:


Ok, this is enough, let’s go back to the session object.

//to store information
//to retrieve information

3. Database

Database enables you to store large amount of information per taining to state in your Web application.

ASP.NET Client-Side State Management – ViewState, Cookies and QueryString

Web form pages are HTTP-Based, they are stateless, which means they don’t know whether the requests are all from the same client, and pages are destroyed and recreated with each round trip to the server, therefore information will be lost and state management is a major issue in developing web applications. In this article we review how to handle state manage on the client using ViewState , Cookies, Hidden Fields and QueryStrings.

1. ASP.NET ViewState

Each control on a Web Forms page, including the page itself, has a ViewState property, it is a built-in struture for automatic retention of page and control state, which means you don’t need to do anything about getting back the data of controls after posting page to the server.

Here, which is useful to us is the ViewState property, we can use it to save information between round trips to the server.

//to save information
//to retrieve information
string shapes=ViewState[“shape”];

Note: Unlike Hidden Fields, the values in ViewState are invisible in the ‘viewsource’ of the page, they are compressed and encoded.

2. ASP.NET Cookies .

A cookie is a small amount of data stored either in a text file on the client’s file system or in-memory in the client browser session. Cookies are mainly used for tracking data settings.

Let’s take an example: say we want to customize a welcome web page, when the user request the default web page, the application first to detect if the user has logined before, we can retrieve the user informatin from cookies:

 lbMessage.text=”Dear“+Request.Cookies[“username”].Value+”, Welcome shoppinghere!”;
 lbMessage.text=”Welcome shoppinghere!”;

If you want to storeclient’s information, you can use the following code:


So next time when the user request the web page, you can easily recongnize the user again.

3. ASP.NET Hidden Fields

A hidden field does not render visibly in the browser,but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in theHTTP Form collection along with the values of other controls.

A hidden field acts as a repository for any page-specific information that you would like tostore directly in the page. Hidden field stores a single variable in itsvalue property and must be explicitly added it to the page.
ASP.NET provides the HtmlInputHidden control that offers hidden field functionality.

protected System.Web.UI.HtmlControls.HtmlInput Hidden Hidden1;
//to assign a value to Hiddenfield
Hidden1.Value=”this is a test”;
//to retrieve a value

Note: Keep in mind, in orderto use hidden field, you have to use HTTP-Post method to post web page. Although its name is ‘Hidden’, its value is not hidden, you can see its value through ‘view source’ function.

4. ASP.NET QueryStrings

Query strings provide a simple but limited way of maintaining some state information.You can easily pass information from one page to another, But most browsers and client devices impose a 255-character limit on the length of the URL. In addition, the query values are exposed to the Internet via the URL so in some cases security may be an issue.Continues…

Implementing a Generic Data Access Layer in ADO.NET Part 2

In the first part of this series of articles on Data Access Layer, we have had a look at what the strategies are, for designing and implementing a Generic Data Access Layer. We have had a look at the enumerators and the factory classes that we will be using. In this part of this article of three part series, we will discuss how we can implement the DatabaseHelper class, one that would be responsible for performing the actual database operations.

The DatabaseHelper class encapsulates the various calls to the database to perform the CRUD operations. The DBManager class that we will discuss later acts as a wrapper on top of this class. You have various methods in the DatabaseHelper class to add parameters, to execute queries, stored procedures, etc.

Here is the code that illustrates how the connection to the database is established based on the provider type chosen and the command object created.

 public DatabaseHelper(string connectionstring, ProviderType provider)
this.strConnectionString = connectionstring;
objFactory = DBFactory.GetProvider(provider);
objConnection = objFactory.CreateConnection();
objCommand = objFactory.CreateCommand();
objConnection.ConnectionString = this.strConnectionString;
objCommand.Connection = objConnection;

In ADO.NET, you have the following data providers.

  • SQL Server Data Provider
  • Oracle Data Provider
  • Odbc Data Provider
  • OleDB Data Provider

Note: Depending on the data provider used, you need to use the command object that is specific to that provider. Your data reader should also be specific to the data provider used. The use of the DBFactory class as shown in the code snippet above. Note that you use the command objects to execute the database commands that contain the SQL statements. Added to this, we will have overloaded versions of AddParameter method to add parameters to the command objects so that we can pass parameters to the database stored procedures or SQL statements. Here is the simplest version of the AddParameter method.

internal int AddParameter(string name, object value)

DbParameter dbParameter = objFactory.CreateParameter();
dbParameter.ParameterName = name;
dbParameter.Value = value;
return objCommand.Parameters.Add(dbParameter);

While the ParameterName identifies the unique name of the parameter to be passed, the Value implies the value of the parameter passed. Hence, if the ParameterName comprises of “@EmpName”, the Parameter’s value might be “Joydip Kanjilal”.

Implementing a Generic Data Access Layer in ADO.NET Part 1

A Data Access Layer (DAL) is an integral part in the design of any application. There are plenty of articles that discuss how we an implement a DAL using ADO.NET. Most of these have constraints in the sense that they are not generic in nature. In other words, they are not provider independent. This series of articles will discuss the implementation of a generic, i.e., a provider independent Data Access Layer in ADO.NET. The basic prerequisite to learning this article is a proper understanding of ADO.NET and good coding skills in C#. I will present the code examples in this article in C#. However with little effort, you can twist it over to VB.NET as well.

The Strategies Involved in Creating a Data Access Layer

Let us first understand what the necessities are for building such a layer. I would rather start by discussing how an application designed using ADO.NET actually connects to the database and performs the CRUD (Create, Read, Update and Delete) operations.

First, you need to open the connection using a database provider. Fine, but what is a provider anyway? A provider is responsible for connecting to a specific database. Why specific? The reason is that a provider for an Oracle database cannot be used to connect to a SQL Server database and vice-versa. Next, you need a command object that can be used to execute the database commands of your choice. This is followed by the usage of a DataReader or a DataSet or a DataTable instance to retrieve data (if you are performing a Read operation) from the database table. When you use a DataSet, you need a DataAdapter as a bridge between the actual database and the DataSet instance.

Implementing the DAL Framework

With this in mind, let us design a provider independent Data Access Layer.

Let us first understand the ADO.NET Library. The major classes that constitute the ADO.NET library are:


  • Connection
  • Command
  • Data Reader
  • Data Adapter

The corresponding interfaces that the above classes implement are stated below.


  • IDBConnection
  • IDataReader
  • IDBCommand
  • IDBDataAdapter

The Data Providers that make up the library are specific to a particular database that they would connect to. These are the Data Providers that are available in ADO.NET.


  • SQL Server Data Provider
  • Oracle Data Provider
  • ODBC Data Provider
  • OleDB Data Provider

Now we are all set to implement our DAL. The major components that constitute our DAL block are:


  • ProviderType (Enum)
  • DatabaseConnectionState (Enum)
  • StoredProcedureParameterDirection (Enum)
  • DBManager (Class)
  • DBHelper (Class)

We will start our discussion with the enum data type that would contain the data provider types in it. These provider types relate to the databases that we will be connecting to, depending our requirements. The following code snippet illustrates the ProviderType enum that contains four values that correspond to a specific data provider.Continues…

Understanding The ASP.NET Page Life Cycle

Understanding the Page Life Cycle in ASP.NET is essential knowledge for developing ASP.NET apps, without a firm understanding of the Page Life Cycle developing apps will be an uphill battle.

When a web page is sent to the Web Server for processing, it goes through a sequence of steps before it finally gets displayed in the Web Browser. This article discusses these series of steps and events that occur in a page life cycle in ASP.NET.

From The Web Browser to IIS

When a POST request is initiated from the client side, the Web Server traps the request and it is usually routed to an .aspx web page. The request is actually routed to the HTTP Pipeline, a chain of managed objects.

After the HTTP Page handler class is identified, the ProcessRequest () method is called which eventually fires the different page events in the life cycle of a web page. The sequence of events that takes place in the life cycle of a web page in ASP.NET is:

  1. Page_Init
  2. LoadViewState
  3. LoadPostData
  4. Page_Load
  5. RaisePostDataChangedEvent
  6. RaisePostBackEvent
  7. Page_PreRender
  8. SaveViewState
  9. Page_Render
  10. Page_UnLoad

All these events are associated with their respective handlers and you can even override them to customize their default behaviour. The following section discusses each of these events in detail.

The Page Life Cycle Events Explained

Once the request for the web page arrives at the web server, the ASP.NET runtime determines whether the page needs to be parsed or whether a cached version of the page needs to be rendered to the requestor. Then the Request and the Response objects for the page are set and the page life cycle starts.

The Page_Init event is the first event to be triggered in the page life cycle. It is responsible for the initialization activities that are essential to create a page instance. In this phase of the page life cycle, all the server controls of the web page are initialized to their default values. However, it should be noted that the View State for a page is not available at this stage of the page life cycle and a server control of the page cannot access other server controls of the page at this phase.

You can use the Page_Init event to create or re-create the controls that need to be created or re-created dynamically. The following example illustrates how you can override the OnInit() method.

protected override void OnInit(EventArgs e)
if (Page != null)
Page.Trace.Write ("The OnInit method has been called");

Next, the LoadViewState method is called. “The load view state stage only happens when the page has been posted back.  During this stage the view state data saved from the previous page visit is loaded and recursively populated into the Page’s control hierarchy”. This method restores the View State information of a web page that was last saved using the SaveViewState method. You can override the LoadViewState() method to get an idea on how the viewstate is actually restored.

ASP.NET Security Best Practices

Security is one of the most important concerns in application software development. Building a robust security model is one of the most important factors that drive the success of application software. As far as security in ASP.NET is concerned, three terms come into my mind, i.e., Authentication, Authorization and Impersonation. Put simply, authentication authenticates the user’s credentials and authorization relates to the resources that an authenticated user has access to. This article is the first in a series of articles on ASP.NET security and discusses these concepts and their applicability.

Let us start our discussion with a brief outline on the sequence of events are as far as authentication and authorization are concerned when a new request comes in. When a new request arrives at IIS, it first checks the validity of the incoming request. If the authentication mode is anonymous (default) then the request is authenticated automatically. But if the authentication mode is overridden in the web.config file settings, IIS performs the specified authentication check before the request is passed on to ASP.NET.

ASP.NET then checks whether Impersonation is enabled or not. We will discuss impersonation later in this article. If impersonation is enabled, ASP.NET executes with the identity of the entity on behalf of which it is performing the task; otherwise, the application executes with the identity of the IIS local machine and the privileges of the ASP.NET user account. Finally, the ASP.NET engine performs an authorization check on the resources requested by the authenticated user and if the user is authorized, it returns the request through IIS pipeline.

The following section discusses Authentication, Authorization and Impersonation and how we can implement them in ASP.NET applications.

Authentication determines whether a user is valid or not based on the user’s credentials. Note that a user can be authorized to access the resources provided the user is an authenticated user. The application’s web.config file contains all of the configuration settings for an ASP.NET application. An authentication provider is used to prove the identity of the users in a system. There are three ways to authenticate a user in ASP.NET:

  • Forms authentication
  • Windows authentication
  • Passport authentication

Forms Authentication

This is based on cookies where the user name and the password are stored either in a text file or a database. It supports both session and persistent cookies.

After a user is authenticated, the user’s credentials are stored in a cookie for use in that session. When the user has not logged in and requests for a page that is secured, he or she is redirected to the login page of the application. The following code snippet illustrates how this can be implemented in ASP.NET.

<authentication mode="Forms"/>
<forms name="LoginForm" loginUrl="LoginForm.aspx" />
<deny users="?"/>

Note that the symbol “?” indicates all Non Authenticated and Anonymous users. Typically, the user enters the username and the password, clicks the login button and the form validates the values against values from that stored in a persistent store, usually a database. The following code snippet illustrates how this can be validated.

String username = txtUserName.Text;
String password = txtPassword.Text;
bool isUserValid = false;
//Code to validate the user name and password
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False);
else // User is not valid
lblMessage.Text = “Invalid login…”;

The RedirectFromLoginPage method creates an authentication ticket and is used to redirect an authenticated user back to the originally requested URL or the default URL. The following code snippet illustrates how we can specify the user’s credentials in the application’s web.config file.

<authentication mode="Forms">
<forms loginUrl="LoginForm.aspx">
<user name="JoydipK" password="JudeK" />

However you choose the above technique of authentication you should provide a means of encrypting the configuration file for security reasons. I will discuss these and other issues in the forthcoming articles in this series of articles on ASP.NET Security.