Jun 19, 2008

State Management in 2.0

State Management Techniques in ASP.NET
This article discusses various options for state management for web applications developed using ASP.NET. Generally, web applications are based on stateless HTTP protocol which does not retain any information about user requests. In typical client and server communication using HTTP protocol, page is created each time the page is requested.Developer is forced to implement various state management techniques when developing applications which provide customized content and which "remembers" the user.
Here we are here with various options for ASP.NET developer to implement state management techniques in their applications.
Broadly, we can classify state management techniques as client side state management or server side state management. Each technique has its own pros and cons. Let's start with exploring client side state management options.

Client side State management Options:
ASP.NET provides various client side state management options like Cookies, QueryStrings (URL), Hidden fields, View State and Control state (ASP.NET 2.0). Let's discuss each of client side state management options.
Bandwidth should be considered while implementing client side state management options because they involve in each roundtrip to server. Example: Cookies are exchanged between client and server for each page request.

A cookie is a small piece of text stored on user's computer. Usually, information is stored as name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user visits a website, cookies are retrieved from user machine and help identify the user. Let's see an example which makes use of cookies to customize web page.
if (Request.Cookies["UserId"] != null)
lbMessage.text = "Dear" + Request.Cookies["UserId"].Value + ", Welcome to our website!";
lbMessage.text = "Guest,welcome to our website!";

If you want to store client's information use the below code
Cookies can be disabled on user browsers
Cookies are transmitted for each HTTP request/response causing overhead on bandwidth
Inappropriate for sensitive data

Hidden fields:
Hidden fields are used to store data at the page level. As its name says, these fields are not rendered by the browser. It's just like a standard control for which you can set its properties. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page. Now that all the web controls have built in state management in the form of view state and new feature in 2.0 control state, hidden fields functionality seems to be redundant. We can still use it to store insignificant data. We can use hidden fields in ASP.NET pages using following syntax
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;

//to assign a value to Hidden field
Hidden1.Value="Create hidden fields";
//to retrieve a value
string str=Hidden1.Value;
Simple to implement for a page specific data
Can store small amount of data so they take less size.
Inappropriate for sensitive data
Hidden field values can be intercepted(clearly visible) when passed over a network

View State:
View State can be used to store state information for a single user. View State is a built in feature in web controls to persist data between page post backs. You can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true. View state mechanism poses performance overhead. View state information of all the controls on the page will be submitted to server on each post back. To reduce performance penalty, disable View State for all the controls for which you don't need state. (Data grid usually doesn't need to maintain state). You can also disable View State for the entire page by adding EnableViewState=false to @page directive.
View state data is encoded as binary Base64 - encoded which add approximately 30% overhead. Care must be taken to ensure view state for a page is smaller in size. View State can be used using following syntax in an ASP.NET web page.
// Add item to ViewState
ViewState["myviewstate"] = myValue;

//Reading items from ViewStateResponse.Write(ViewState["myviewstate"]);
Simple for page level data
Can be set at the control level
Overhead in encoding View State values
Makes a page heavy

Query strings:

Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text. Now that cross page posting feature is back in 2.0, Query strings seem to be redundant. Most browsers impose a limit of 255 characters on URL length. We can only pass smaller amounts of data using query strings. Since Query strings are sent in clear text, we can also encrypt query values. Also, keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode.
Let's assume that we have a Data Grid with a list of products, and a hyperlink in the grid that goes to a product detail page, it would be an ideal use of the Query String to include the product ID in the Query String of the link to the product details page (for example, productdetails.aspx?productid=4).
When product details page is being requested, the product information can be obtained by using the following codes:
string productid;productid=Request.Params["productid"];
Simple to Implement
Human Readable
Client browser limit on URL length
Cross paging functionality makes it redundant
Easily modified by end user

Control State:

Control State is new mechanism in ASP.NET 2.0 which addresses some of the shortcomings of View State. Control state can be used to store critical, private information across post backs. Control state is another type of state container reserved for controls to maintain their core behavioral functionality whereas View State only contains state to maintain control's contents (UI). Control State shares same memory data structures with View State. Control State can be propagated even though the View State for the control is disabled.
For example, new control Grid View in ASP.NET 2.0 makes effective use of control state to maintain the state needed for its core behavior across post backs. Grid View is in no way affected when we disable View State for the Grid View or entire page

Server Side State management:

As name implies, state information will be maintained on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server.
Care must be taken to conserve server resources. For a high traffic web site with large number of concurrent users, usageof sessions object for state management can create load on server causing performance degradation

Application object:
Application object is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object.
In classic ASP, application object is used to store connection strings. It's a great place to store data which changes infrequently. We should write to application variable only in application_Onstart event (global.asax) or application.lock event to avoid data conflicts. Below code sample gives idea

Session object:

Session object is used to store state specific information per client basis. It is specific to particular user. Session data persists for the duration of user session you can store session's data on web server in different ways. Session state can be configured using the section in the application's web.config file.
Configuration information: cookieless = <"true" "false"> timeout = sqlconnectionstring= server = port =

Mode:This setting supports three options. They are InProc, SQLServer, and State ServerCookie less:
This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one.

This indicates the Session timeout vale in minutes. This is the duration for which a user's session is active. Note that the session timeout is a sliding value; Default session timeout value is 20 minutesSqlConnectionString:
This identifies the database connection string that names the database used for mode SQLServer. Server:
In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state.
Port:This identifies the port number that corresponds to the server setting for mode State Server. Note that a port is an unsigned integer that uniquely identifies a process running over a network.
You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.
Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability
In process mode (in-memory)- State information is stored in memory of web server
Out-of-process mode- session state is held in a process called aspnet_state.exe that runs as a windows service.
Database mode session state is maintained on a SQL Server database.
In process mode:This mode is useful for small applications which can be hosted on a single server. This model is most common and default method to store session specific information. Session data is stored in memory of local web server
Configuration information:
Fastest mode
Simple configuration
Session data will be lost if the worker process or application domain recycles
Not ideal for web gardens and web farms

Out-of-process Session mode (state server mode):
This mode is ideal for scalable and highly available applications. Session state is held in a process called aspnet_state.exe that runs as a windows service which listens on TCP port 42424 by default. You can invoke state service using services MMC snap-in or by running following net command from command line.

Net start aspnet_state
Configuration information:
Supports web farm and web garden configuration
Session data is persisted across application domain recycles. This is achieved by using separate worker process for maintaining state
Out-of-process mode provides slower access compared to In process
Requires serializing data

SQL-Backed Session state:

ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL Server offers resilience that can serve sessions to a large web farm that persists across IIS restarts.SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET Framework's installed directory C:\\\framework\. Running this utility will create a database which will manage the session state.
Configuration Information:

Supports web farm and web garden configuration
Session state is persisted across application domain recycles and even IIS restarts when session is maintained on different server.
Requires serialization of objects
Choosing between client side and Server side management techniques is driven by various factors including available server resources, scalability and performance. We have to leverage both client side and server side state management options to build scalable applications.
When leveraging client side state options, ensure that little amount of insignificant information is exchanged between page requests.
Various parameters should be evaluated when leveraging server side state options including size of application, reliability and robustness. Smaller the application, In process is the better choice. We should account in the overheads involved in serializing and deserializing objects when using State Server and Database based session state. Application state should be used religiously.

Jun 18, 2008

Joins With examples

1)These are used to retrieve the data from more than one table.
2)To retrieve the data from more than one table the datatypes of fields which related to different tables need not be same while using the joins
Types of joins:
1):Inner Join
2):Cross Join
a)Left Outer Join
b)Right Outer Join
c)Full Outer Join
4)Natural Join
5)Equi Join
Examples and Description:
EmployeeID EmployeeName 1 Ramesh2 Sukumar3 Ravi 4 Kalyani
ProductID EmployeeID Productname1 1 2 Pen12 3 Pencil1 2 3 Eraser1 3 6 Book
1):Inner Join:This join returns all the rows from the both the tables where there is a match.The result set consists of only matched rows.
select E. Employeeid,E.EmployeeName,P.ProductName from Employees E inner join Products on E.EmployeeID=P.EmployeeID
1) EmployeeID EmployeeName Productname 2 Sukumar Pen3 Ravi Pencil 3 Ravi Eraser
2)Cross Join:Cross join is nothing but retrieving the data from more than one table with out using the condition.
Here two cases are there:
a)select E.EmployeeID,E.EmployeeName,P.Productname from Employees E,Products P
Note:(here we are using the cross join defaultly.Means we have not mentioned the any condition here.)
b)select E.EmployeeID,E.EmployeeName,P.Productname from Employees E cross join Products P
Note:this is the syantax of cross join..both queries(a &b)returns the same result) only the difference is Synatx but the o/p is same.
3)Outer Join:In outer join the resulting table may have empty columns.
a)Left Outer Join:Here left means first reurns all the rows from the first table even though it does not have the matchs in Second table.But it returns only the matched rows from the second table.
select E. Employeeid,E.EmployeeName,P.ProductName from Employees E left join Products on E.EmployeeID=P.EmployeeID
1) EmployeeID EmployeeName Productname 2 Sukumar Pen3 Ravi Pencil 3 Ravi Eraser
1 Ramesh null
4 Kalyani null
a)Right Outer Join:Here Right means Second returns all the rows from the second table even though it does not have the matchs in First table.But it returns only the matched rows from the First table.
select E. Employeeid,E.EmployeeName,P.ProductName from Employees E right join Products on E.EmployeeID=P.EmployeeID
1) EmployeeID EmployeeName Productname 2 Sukumar Pen3 Ravi Pencil 3 Ravi Eraser
6 null Book
5)Natural JOIN:it eliminates the duplicate values from the output.
6)Equi JOIN:An inner join is called equi-join when all the columns are selected with a *, or natural join otherwise

VS 2005 Keyboard Shortcuts

VS 2005 Keyboard Shortcuts
Shortcut (memorize)
Function (memorize)

Shift + F5--------> Debug.StopDebugging
CTRL + F5---------> Debug.StartWithoutDebugging
F9----------------> Debug.ToggleBreakpoint
CTRL + ALT + V, T--> Debug.This
CTRL + ALT + H ----> Debug.Threads
F10 ---------------> Debug.StepOver
CTRL + F10 --------> Debug.RunToCursor
F11 ---------------> Debug.StepInto
Shift + F4 --------> View.PropertyPages
Shift + F11--------> Debug.StepOut
CTRL + ALT + C-----> View.ClassView
CTRL + ALT + L ----> View.SolutionExplorer
CTRL + ALT + K ----> View.TaskList
CTRL + ALT + O ----> View.Output
CTRL + ALT + B ----> Debug.Breakpoints
CTRL + ALT + C ----> Debug.CallStack
CTRL + ALT + I ----> Debug.Immediate C
TRL + ALT + E ----> Debug.Exceptions
CTRL + ALT + X ----> View.Toolbox
CTRL + ALT + V, L--> Debug.Locals
CTRL + Shift + B---> Build.BuildSolution
CTRL + F7 ---------> Build.Compile
CTRL + F12---------> Edit.GoToDeclaration
F12 ---------------> Edit.GoToDefinition
CTRL + - --------> View.NavigateBackward
CTRL + Shift + - -> View.NavigateForward
ALT + Shift + Enter -> View.FullScreen
CTRL + K, CTRL + U --> Edit.UncommentSelection
CTRL + K, CTRL + C --> Edit.CommentSelection
Shift + Tab ---------> Edit.TabLeft
CTRL + L -----------> Edit.LineCut
CTRL + Shift + L ----> Edit.lineDelete
CTRL + ] ------------> Edit.GoToBrace
CTRL + Shift + ] ----> Edit.GoToBraceExtend
CTRL + M, CTRL + M --> Edit.ToggleOutliningExpansion
CTRL + K, CTRL + K --> Edit.ToggleBookmark
CTRL + F ------------> Edit.Find
CTRL + Shift + F -----> Edit.FindInFiles
F7 ------------------> View.ViewCode
Shift + F7 ----------> View.ViewDesigner

How to Implement themes to GridView in asp.net2.0

The theme of this article is Themes. I will show you that what Themes are used for and how you can make you own Themes quickly and easily. This is a multi series article so stay tuned for the rest of the series. What's up with Themes? Hey! we got CSS (Cascading Style Sheets) so why do we need Themes? The thing about CSS is that it only exposes some fixed style properties which we can use. If we want to change some property like AlternatingItemStyle of the GridView control we will not be able to do this by using simple CSS. Themes allow you to change the control properties. This mean you can change most of the properties exposed by any server control in ASP.NET 2.0.

Gettting Started With Themes: Let's get started with Themes. The first thing that you need to do is to add a skin file. Once you try to add a new skin file ASP.NET will make a folder called App_Themes in which all Themes will be placed. After the App_Themes folder has been created you can simply add .skin files inside the App_Themes folder. You can name the Theme files according to their action. Like if you are adding a Theme which makes the appearance of your page orange you can name is [YourSideName]_Orange_Theme. You can name it anything you want from orange Theme to "Yellow Banana" Theme.

What is in that Skin?
Skin files contains the definition of the server controls on which the Themes will be applied. Here is my Skin file called "Red" whose purpose is to make the GridView red.

As, you might have already noticed that the GridView definition does not contain the ID attribute. That is because this Theme is applied to all the GridViews on the page. There are couple of ways that you can apply different Themes for the same server control.

Applying Themes: There are various ways to apply the Theme to the page. The simplest one of them is to use the Page directive to apply the Theme to the current page.
The above will apply the Theme to the current page. If you wish to apply the same Theme to all the pages of your website then it is a better idea to define the Themes in the configuration file.

You can also apply Themes dynamically using the Page.Theme property. The thing to remember about applying the Themes programmatically is that you can only apply it inside the Page_PreInit event.
Check out the code below which applies the Theme at runtime. protected void Page_PreInit(object sender, EventArgs e)
Page.Theme = "Green";

One thing that you need to remember is that when you set the Theme at different stages the Theme that is set dynamically takes precedence over the Page directive and Web.config. This means that if you have define your Theme to be "Blue" in Web.config and "Green" is Page directive and "Red" dynamically then the Theme set for the page will be set "Red". There is much more to cover in Themes which will be covered in later articles.
Reference: GridViewGuy

Jun 17, 2008

Difference between out and ref parameters in

C# Imp. Basics - Ref and Out parameters

Well, I am still learning .net, so please excuse me for some confusing words.
Sometimes there is a confusion whether to pass the parameters to a method byreference (ref keyword) or using out keyword. As, both keywords are sometimes confused to be used to get the multiple return values from the target method.
1. When to use ref:
the parameters that are needed to be changed by the target method and the change in value is required to be visible after the method call returns should be passed byref.first, the key thing to remember is that each parameter passed by ref must be initialized before passing to the target method (which will finally change their values) and the change will be visible after the target method call returns.secondly, it is not mandatory to change the values of any of the parameter recieved as by ref in the target method.---------------------------------------------------------------------------

2. When to use out:
out parameters are used when there is a certain need to return multiple values from a method call.first, its not mandatory to initialize each parameter marked as out in the target method, before calling that method.secondly, each parameter which is marked as out in the target method, must be assigned a value corresponding to its type in all code return paths of the target method implementation (otherwise compile error).---------------------------------------------------------------------------
Hope the readers understand what i have tried to explain. Suggestions and questions are always welcome.
Note: out parameters are not supported in the Visual Basic.Net language
Reference: Essential C# 2.0 by Mark Michaelis

Use of Out and Ref parameter in C#


The out keyword causes arguments to be passed by reference. This is like the ref keyword, except that ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword. For example:

Class Sample
static void Method(out int i)
i = 2;
static void Main()
int value;
Method(out value);
// value is now 2// We can use this value for further process

The ref and out keywords are treated differently at run-time, but they are treated the same at compile time. Therefore methods cannot be overloaded if one method takes a ref argument and the other takes an out argument

Example of ref

Class Sample


static void Method(ref int i)


i = i + 2;


static void Main()


int value = 2;\\ should be initialized for ref method

Method(ref value);// value is now 4
// We can use this value for further process



This methods are mainly used when hirarchical function where method A(ref int a) --> calls method B(ref int b) -->calls method C(ref int c)

Here in this case the value got in method c is returned to method B which is returned and got in method A.In this next section we ll discuss about out parameters in SQL2005

Jun 11, 2008

how to select middle rows using ROW_NUMBER() in SQL2005

Here the example describes the ROW_NUMBER() approach to select a set or rows using virtual rownumber
AS Row FROM TableName) Rows
WHERE Row BETWEEN 10 and 20

The other option is using of CTE

How to select middle rows using CTE in SQL2005

CTE Common Table Expression are used for custom paging in
Gets the row number from the number of IDs present in the table


-- each CTE should be followed by an select statement