Sunday, February 27, 2011

ASP.NET State Management Overview

What is a State?

In plain and simple terms state is data/information. When you log into facebook,  have you ever wondered what happens when you check the "keep me logged in" box? How does it automatically sign in the next time you come back and type The answer is, when you click that checkbox facebook stores who you are in a cookie in your computer. Cookie is one of the many ways state/information is stored by a website.

When you build your website you store the state in either the client's computer or in your web server. Figure 1 below shows how state management can be classified in

Figure 1. state management overview

Both client side and server side state management have their own advantages and drawbacks. Lets look at these in a little bit more detail.

Client side state management

Let me start by stating that never store any kind of sensitive information on the client. Definitely not in plain text. 

Cookie:  Every browser (ie, chrome, firefox etc) have their own folders for storing cookies. Cookies are used for storing a variety of site specific data. Most commonly cookies are used to store your identity when you log into a website. The identity/token is stored usually in an encrypted/hashed format . For every GET/POST request, all the cookies generated by that domain, is sent to that server. The browser allows 20 cookies from a single server and all together (from all the servers) a maximum of 300 cookies. Once the limit of 300 is reached, the browser starts deleting the old cookies. A cookie can only hold up to 4KB of data.

Viewstate: When you store data in viewstate, that data is sent to the browser in an html hidden field and the data is stored in an encoded format that only the server (not the client) can decode. Among the client side state management, viewstate is relatively the most secure option. The hidden field in viewstate looks something like this.


Note here that even is you disable viewstate, you would still see a hidden field as shown above. The reason is,   the engine saves the values of all the controls in viewstate. This feature cannot be disabled.

The viewstate is a very useful feature to save the state of usercontrols or other data that needs to be persisted between postbacks, without eating up the server resources. Viewstate can only be used for postbacks to the same page. ( If you want to retain information from one page to another, cookie or query strings are better options.)

An increased viewstate size means all that data is posted back and forth over the network (between the browser and the server) for every postback. This can in extreme cases, even add upto minutes to the time it takes to reload the page after a postback.

NOTE: To store the instance of a custom class in viewstate, mark the class with a [Serializableattribute.  

Query String: A  query string is passed through the url. For example if you make an invalid login attempt in facebook, you would see something like

The part ?login_attempt=1 is a query string.  Query strings are typically used to send data from one page to another or to retain data between postbacks to the same page. Most browsers impose a 2083 character limit on the query string so query strings can be used only for a small amount of data.

Hidden fields: Hidden fields control can be used to store data between postbacks to the same page. When you use an hidden field, then the html that is send to the browser is something like
<input type="hidden" value="myValue" />
There are two distinct advantages of hidden fields that I personally find appealing
1>You can set a serverside eventhandler that executes when the value of the hidden control changes between postbacks.
2>This value can be easily accesed by javascript.

Server side state management

The advantage of server side state management is that all that data is not sent across the network and the data stored is more secure. However, the downside is that more server resources utilized. Lets look at some of the server side state management options

Session: When you first visit an website, the web application assigns you a session ID that is stored in a cookie. You can also choose cookie less sessions by setting it in your web.config as shown.

      <sessionState mode="InProc" cookieless="true"  timeout="20"/>

When you choose cookieless session, then the session ID is stored in the url.

You can store data pertaining to sessions in session variables by doing something like
Session["userdetails"] = "xxx"; The default timeout for a session (and hence session variables) is 20 minutes. But this can be changed in the config file.

Certain points to note about sessions:
  • Session variables are stored in the RAM of the application server.
  • The session ID is stored in a cookie named "ASP.NET_SessionId". The assigned session ID looks something like hpb1lq55a0kdh3jdrtk4rhmruw.
  • The cookie that stores the session id is non persistent (which means when you close the the browser, this cookie is lost).
  • 20 minutes after the users last communication with the client, the session is terminated.
  • You can terminate the session on a button click (suppose log out button) by using Session.Abandon()
  • You can handle beginning and ending of sessions in Global.asax
  • Response.Redirect doesnot work in Global.asax
  • You get one sessionID at a time for a particular browser type. If you open the same web application in different browsers, say one in ie and another in firefox, then you get assigned two different session IDs in two different cookies (one in a firefox's cookie and another in  ie's cookie)
  • For cookieless sessions, even if you open the web site in multiple windows of the same browser, you get a new session ID for each window.

Application State: Application state is usually used to store small amounts of data that is global to the entire application. You generally don't use application variables for frequently changing data. Application variables are created by using something like 
Application variables are lost when an application is restarted.

Cache: Cache is similar to application state as in, it is available throughout the application. But it differs from application state in flexibility. There is a lot more you can do with cache, such as set a cache timeout, set a cache priority (when the application server is low on resources it starts getting rid of cache, starting from the low priority cache) etc.

Check this out for a continuation of discussion on caching

Further Reading:

ASP.NET State Management Recommendations:

Basic Security Practices for Web Applications:

Sunday, February 20, 2011

c# OOP ( C# OOP tutorial )

The need for Object oriented programming (OOP)

A long long time ago (up to the late 1950's) a computer program was essentially a long series of sequential commands. But as software applications got more and more complex, it started getting increasingly difficult to modify or fix an existing software program.
    Consider this example. You are working as an intern for an organization. Suppose all their documents are stacked on top of each other forming a pile of a million documents. And now, they ask you to find the documents among these million documents, that explains the dress code and modify it to include denim as an acceptable office wear. Wouldn't life have been a lot easier if these documents were properly organized in separate drawers in file cabinets, as opposed to being stacked on top of each other? That's what OOP does when it comes to programming. It helps in breaking down the code into many manageable parts.

What are Objects?

  To simplify things, you can think of it this way. When you write a program, you write it in blocks of code called objects. These blocks of code provide functionalities in two ways.
1>Properties:  This object or block of code can have a parameter (or property) that can be read from other code. For example I write a piece of code where I set a property pi=3.142. You can write code where you can get the value of pi from my code.
2>Methods (Functions): I can have a method in my code that takes an input and throws out an output. For example I can write a piece of code (a method) that takes two numbers as input, and spits out their sum as the output. So if you need the sum of two numbers you can pass it into the method I wrote.

What’s explained above is a very simplified version. But it’s a good start.

OOP Concepts

Now let’s delve a little deeper into the world of object oriented programming in C#. Instead of getting into the code, my focus here would be to give you a better understanding of the underlying concepts.

If nature used C# to create the world, then she would have done something like this.

Object Oriented Programming (OOP)

In the diagram look at abstract class Living Being. An abstract class is something that provides a framework to build something. You cannot have an instance of an abstract class. Here the abstract class Living being , tells classes human, elephant and whale that hey, if you want to be alive, you need to implement living being functions such and eating, breathing etc. If you don't implement all of them, you are not a living being.

Coming down the diagram, the black, white and brown races inherit from human race. What that means here is, all these races have features of being a human such as walking upright on two feet, talking, being intelligent and so on. In addition to the features of being a human, they add their own feature, skin color.

Further down, we see that nature has implemented every race. For example, nature has implemented black human race in two instances, Oprah and Mandela.

The reader would notice that the classes elephant and whale, besides inheriting from the abstract class living being, they also inherit from the interface Massive. Like abstract classes, interfaces only provide a framework.  You cannot have an instance of interfaces.

So now the reader may ask, what’s the difference between abstract and interface. The answer is simple. Abstract class can be thought of something that defines what you are, where as interface can be thought of merely a feature. For the same reason, you can derive from multiple interfaces but you can derive from only one abstract class (or any class for that matter).

Before I end this tutorial, let me touch one more concept in OOP. That is polymorphism. In the diagram above, Gandhi, can be converted into an instance of Human. The reason being that Gandhi is an instance of Brown race and the Brown race is derived from Human race. Any instance can be converted to a type of a class which is upstream in its chain of inheritance. (The other way is not true. C# does not support down casting, unless that instance was originally  a subclass to begin with, that was upcasted into the parent). The fact that an instance of a class can take different forms is called polymorphism.

Further Reading:

Object-Oriented Programming (C# and Visual Basic)

Object Oriented Programming Fundamentals (An msdn video tutorial)

Wednesday, February 16, 2011 db2 connection

In this article I will show you a simple way to read an IBM mainframe db2 table from an web application using the Microsoft oledb provider for db2 and enterprise library 5.0.

Before you start please note that although the Microsoft OLEDB DB2 provider is free, it cannot be installed unless you have SQL server developer version or above installed on your machine. 

To connect to DB2 using an ODBC provider instead of Microsoft OLEDB provider for DB2  check out

Visual studio 2008
.net framework 3.5
access to IBM db2 database
Microsoft oledb provider for db2 (

Five dlls that come with enterprise library 5.0 namely

  • Microsoft.Practices.EnterpriseLibrary.Data.dll
  • Microsoft.Practices.EnterpriseLibrary.Common.dll
  • Microsoft.Practices.ServiceLocation.dll
  • Microsoft.Practices.Unity.dll
  • Microsoft.Practices.Unity.Interception.dll

The enterprise library 5.0 can be downloaded from the Microsoft website

This is how you do it:

1>Create a web application

2>Modify the connection string in your web.config to include this

    <add name="mydb2" connectionString="Provider=DB2OLEDB;Password=xxx;User ID=xxx;
Initial Catalog=myDBName;Network Transport Library=TCP;Network Address=myServerAddress;Package Collection=mspkg" providerName="System.Data.OleDb"/>

3>Copy the five dlls
  • Microsoft.Practices.EnterpriseLibrary.Data.dll
  • Microsoft.Practices.EnterpriseLibrary.Common.dll
  • Microsoft.Practices.ServiceLocation.dll
  • Microsoft.Practices.Unity.dll
  • Microsoft.Practices.Unity.Interception.dll

    to a location inside the web application's folder

    4>Add references to them.

    Your references would look something like this

    5>Add a gridview named GridView1 to the aspx page.

    6>In the Default.aspx.cs page add these two using directives

    using System.Data.Common;
    using Microsoft.Practices.EnterpriseLibrary.Data;

    7>Add this code to read a db2 table and populate the gridview with it

                DataSet ds = new DataSet();
                string connectionStringName = "mydb2";
                Database db = DatabaseFactory.CreateDatabase(connectionStringName);
                DbCommand dbCommand = db.GetSqlStringCommand("SELECT * FROM mytable");
                db.LoadDataSet(dbCommand, ds, "tblName");
                GridView1.DataSource = ds.Tables[0];

    Now when you run the application the db2 table data will be displayed in the webpage.

    Wednesday, February 2, 2011

    Exception handling in C# ( C sharp)

        An exception or error in code is something that causes the system to abruptly stop from executing the code. This can happen in one of two ways.

    1>Run time Exception: These are exceptions defined by the .net framework. These errors are thrown by the CLR.
    ·         If you try something like 1/0 the .net frame work CLR will throw a System.DivideByZeroException. 
    ·         Suppose you try to access an array element that does not exist, the CLR would throw a System.IndexOutOfRangeException.

    2>Application Exception: These exceptions are defined by the developer of the application.  These errors are thrown by the application logic and not the CLR. The developer does this by defining a class that inherits from the System.ApplicationException class or System.Exception class. One common use of application exception would be to throw generic exceptions.

    How to handle an error in C#?

    The sample code below explains how to handle error.
    //some code
    catch (Exception ex)
    //clean up code (close connections etc)

    This is how it works
    1>The code tries executing what’s inside the try block.
    2>If that fails, it enters the catch block (otherwise it directly goes to finally block)
    3>After executing what’s inside the catch block, it enters the finally block.

    Certain points to note.
    ·         Finally block is always executed, regardless of whether or not an error occurs.
    ·         If you don’t re throw the error inside the catch block, after the finally block the code continues execution as if nothing went wrong. The application doesn’t abort.
    ·         If you throw the error again inside the catch block, the application aborts after the finally block. In that case the error is called an unhandled exception.
    ·         If you use a try block, either a catch or finally block is necessary.

    What’s explained above is a simplified version.

    Some notes/best practices on error handling

    Most of the below recommendations are Microsoft’s official recommendations

    1>You should never catch a system exception unless your intention is to log it or to throw it again. For example
    Reason: The code continues to execute as usual. It pretends nothing went wrong.

    This code is NOT recommended.
    {    int x = 0;
        int y = 1 / x;

    The code below is acceptable
    int x = 0;
    int y = 1 / x;

    2>An empty throw is preferred over re throwing an exception
    Reason: If you catch and re throw an exception the application thinks that the re throw location is the source of error. It wouldn’t know the original source of error.
    For example in the code below, line 32 is a divide by zero error
    This is wrong
    Wrong way to handle exception

    This is the right way to do it

    Correct way to handle exception

    3>An easy way to throw a custom error would be as shown below
    Int deptNumber=int.Parse(txtDept.text. ToString());
    throw new Exception("Department number entered is invalid.");

    3>It is a bad practice to use try catch block for adding functionality. It should only be used to handle errors.
    Reason: Once the code enters the catch block, it is resource intensive. (Try block however is NOT resource intensive)

    For example the code below should be avoided

    Instead you should use something like
    if (conn.State != ConnectionState.Closed)

    4>According to some experts, a well written code has more try finally blocks and less try catch finally blocks.

    Further Reading ( links to MSDN):

    Creating and Throwing Exceptions (C# Programming Guide)

    Exception Handling Statements (C# Reference)