Tuesday, October 14, 2003

Session Variables - Operational Information and Performance


MSDN Article By Vishal Joshi


Article Posted: October 21, 2003



It is many a times said that you should use minimum session variables in your web application and use of session variables actually affects the performance adversely. Did you ever try to analyze why is it so? In this article I have explained (in not so detail but have given required operational information) about the Session Variables, their use and their affect on web application performance.

Recollect your writing this simple code int intUserId = Convert.ToInt32(Session[“UserId”]);

Do you know what all does ASP.NET runtime actually does behind the scene? Well in fact to handle this there are lots of considerations taken into account and there is a lot of background processing happening.

To explain this in brief let me re-iterate over the fact that ASP.Net provides 3 different kinds of session storage facilities namely “InProc”, “StateServer” and “SQLServer”. So you can have your session data stored at any of these three different locations.

1. In Process – This is the default option by which the session values are kept alive as objects in Windows Server, by ASP.Net worker process.
2. State Server (Out of Process) – aspnet_state.exe runs as a separate process on the same box or on another machine. In this case the session values are serialized and stored in the memory of this separate process.
3. SQL Server – As the name suggests in this case the session values are stored in the SQL Server table. Again in this case the SQL server can be on the same box as well can be a dedicated DB server.


You can specify the state provider in the web.config file of your application in the section like

sqlConnectionString="data source=127.0.0.1;user id=sa;password="
cookieless="false" timeout="20” />


The mode in the above case can have four different values representing different locations of storage discussed above.


Off – Indicating application wide session state is not enabled. If your application is not going to use any session information remember to set the mode to “Off”. (Note: If you have not set the mode to “Off” and you have a Session_OnStart handler in your application session is saved even though it is empty, which can adversely affect the performance, so do not have Session_OnStart handler unless it is required for your application.)

InProc – This is the default option

StateServer – If you set this as mode then providing stateConnectionString parameter is important. (Note: 127.0.0.1 indicate local host, you may provide any server name, and 42424 is the default port number, providing it is mandatory. Also note that state service, process named - aspnet_state.exe, is installed but is stopped by default, so you may need to start that on the server before use.)

SQLServer – If you set this as mode then providing sqlConnectionString parameter is important (Note: ASP.Net uses default Databases and Initial Catalog so providing such arguments in the connection string is not allowed)


The cookieless parameter indicates whether session without cookies should be used to identify the client sessions or not. The default value is false indicating that cookies should be used to identify client sessions. (Note: This is one of the major differentiating features provided by ASP.NET Session State over classic ASP. In a single line cookieless sessions use mangled URL concept for browsers to identify the session state.)

The timeout parameter indicates the time in minutes after which, an idle user session should be abandoned. (Tip: You may want to take care of this parameter sometimes - like if you are building a catalog or gallery you may not want a user to get time-out notices in a short while but in case of banking application you may want to reduce the limit.)

Now, we understand that ASP.NET can store our session variables at different locations according to our choice, let us now understand roughly what it does behind the scene to get or set our session variables. Take a hypothetical scenario in which you have made no changes to the above settings and a single web page (in consideration) of the web application has got multiple frames. Each frame is reading or writing information into the Session. To add up to the trouble let us assume that only one particular Session Variable is being accessed and modified by all the frames. This scenario is possible right!! ASP.NET runtime needs to handle all such scenarios. To handle this ASP.NET runtime implements LOCK. There are two different types of locks namely - Reader Lock and Writer Lock. If a reader lock is set then concurrent read-only requests will be entertained but write requests will be held back and given last priority. But if a writer lock is set then all the remaining read-only or write requests have to wait. Thus it might so happen that till your one frame finishes the other frames might not even get start their processing. You can see how performance will be affected in this case. Thus ASP.NET implements queuing of requests to session and tries to handle it in an optimized way but we also need to be judicious in requests to the session too!!

Among the available three ways of maintaining session state it is quite evident that InProc mode is the most efficient. Researches have indicated that the use of OutProc (StateServer) mode effects performance up to 15% whereas SQL Server effects up to 25%. The figures indicated by these studies are for basic types and for user defined types they may even go higher. The reasons behind these hits are the serialization and de-serialization that occurs while moving the objects to the session state and then retrieving them. This overhead is clearly saved in InProc mode as the objects are saved in memory and there is no need to go through the serialization/de-serialization processes. The hit that is present in the InProc mode thus is mainly due to the memory consumption by addition of session variables. By judiciously adding objects to sessions thus can help in case of InProc mode.

So now if you ask why we at all need the other two modes when they are so performance expensive then the answer is because of the reliability. The data persisted in SQL Server or in OutProc mode is much safer as it is not hit by failures in IIS or ASP.NET or even by process recycling. Though if SQL Server or aspnet_state.exe is stopped or failed then there are potential chances of the loss of data (in case it is not handled properly!!) but when data is critical then these modes need to be used. So if we rate these modes according to performance then the ranks would be

1. InProc
2. StateServer
3. SQLServer


But if we rate the same from reliability perspective then the ranks would be

1. SQLServer
2. StateServer
3. InProc


Though you can note the ease that the way your application would read/write the data will remain the same as Session[“key”] = value;

Thus again, as usual you have to do the correct trade-off and decide what is good for your application no one can really give a statement on this. But at the first place remember that if you can do away without Session Variables then you should never go ahead and use them.

Now, as we understand the performance implications related to session state usage let us be conscious programmers and understand how we can control sessionState to increase performance of our individual pages. @page directive of ASP.NET page has a property called “EnableSessionState”. If your page is not accessing any session related information you can set this variable to “false”. If your page is going to only read from session then ensure that you set this value to “ReadOnly” and if you are going to do read write operations to session then set it to “true”.

At the end we will conclude by saying that Session Variables are designed for the convenience of us designers/developers but we should be careful enough to use them and should be conscious enough to know how much performance we are trading off by the way we use them.

Vishal Joshi
Microsoft MVP


Friday, October 03, 2003

This came in DotNetNuts.com and was brought to attention by Deepak Kumar Vasudevan, a fellow MVP... Thanks Deepak for the same...

The Ten Commandments of .NET

1. Thou shall learn XML, now! If .NET is an angel from Microsoft then its wings are woven with XML, and you need to understand the basics of XML before you can fly with .NET. XML is used for configuration files, SOAP,Serialization, and it's tightly integrated with ADO.NET. You can get away without knowing XML, but you won't get far.

2. Thou shall become an object-oriented programmer! To understand .NET and build successful applications you must understand OOP. VB programmers now have new object-oriented capabilities, but may not know how or when to use them. You should understand interfaces and abstract classes (there's a difference between the two in .NET), implementation inheritance, function overriding, and shared members. If your not familiar with OOP at all, start learning ASAP. If your established with OOP as it applies to VB6 then dig deeper into OOP methodology, it will certainly make .NET more enjoyable.

3. Thou shall concentrate on the .Net framework, not the language being used. No matter what .NET language you use, your still using the same framework, so it's very important to focus on the framework, not a particular language. Keep in mind that most of the functions you'll use while programming are from the framework, so using a new language is easy, simply adjust to the syntax. Plus, having C#, C++, VB, Perl, Pascal, COBOL, Fortran, and Eiffel on your resume is more impressive than having just one.

4. Thou shall not go it alone. Get involved in the .NET community. This is the best way to dive into .NET. Message boards are a great resource because you can read problems and questions posted by beginners, and examine the solutions they received. After all, it's better to learn from others mistakes than to learn by repeating them. DotNetNut.com is a great place to start. You'll find message boards, original articles, constantly updated FAQ, and an enormous amount of links to other great resources. We 'll help you spend more time learning and less time digging for answers.

5. Thou shall adapt to new development environment. For VB programmers the VS.NET IDE is a big change, and it's going to take some effort to adjust. Not only is there much better support for debugging than in VB6, but there is also the ability to record and playback macros. Get intimate with the IDE, missing out on great new features is shameful.

6. Thou shall abandon DCOM and use remoting. DCOM was a big step in Microsoft distributed computing, but it's time has passed. Remoting is the .NET model for distributed computing. It's more flexable, featuring plugable channels and protocols, and it generally out performs DCOM (Though note:Remoting outperforms DCOM is in intra-appdomains where as between processes and across network Remoting is slower by 250%..Thanks Sanjay Vyas for his inputs). Administration is done easily through application configuration files which elevate the headache of DCOM administration. Althought it takes a little more coding than DCOM the benefits are well worth it.

7. Thou shall not use VS.NETs code generators without understanding the code they generate. VS.NET has some great code generators that can save you time, but only use them if you understand the code they generate. Create a sample application, use the code generators, and be come very familiar with the results. It's impossible to support code ou don't understand.

8. Thou shall use structure error handling in VB. VB developers have a choice, either learn how to use structured error handling, or use the old On Error method. Using structured error handling brings flexibility and maintainability to VB and is one of the best new features. There are two reasons On Error should be left behind. One is because Try Catch Finally will be used in all .NET languages, On Error is VB specific. Two, because structured error handling is much more powerful, giving you the ability to nest Try Catch statements and layer exceptions.

9. Thou shall avoid using COM+ for single phase transactions. COM+ is great for two phase commits because of the DTC, but there is extra overhead for database locks due to the nature of the transaction. It's a waste of database resources to indiscriminately use COM+ when a less intensive lock can be used. Transactions through the Data namespaces are lighter and should be used for single phase transactions. It is possible to get the same automatic transaction enrollment available in COM+ by using the SinglePhaseTransactionContext component available for download (complete with source files) at DotNetNut.

10. Thou shall not underestimate the complexity of .NET. Is .NET going to make development easier? Yes, but (there's always a but) the .NET framework is so vast, and there are so many new concepts involved that NET will be difficult at first. If your new to the .NET runtime, than you may not know what value types and boxed types are, how the garbage collector works, or what application domains are. All these concepts are new to microsoft developers and important, to ignore them is sinful.

Monday, September 29, 2003

Microsoft's Visual Studio .Net 2003 (Code name "WHIDBEY") offers few of the coolest and most awaited features...

Did anyone of you while developing web applications faced following situation -
"You are developing a website for a certain client... There are certain standard controls, images and layouts that are going to be repeated across various pages. You have to make the allignment of all the images and those repeated control everytime. Some developers of your group do it differently and you spend quite some time in formatting so that everyone's pages look in similar lines... If yes then read ahead...
Also that sometimes some controls refuse to get a particular font in particular size displayed on them.. You try to do all kindof settings at design time but still at runtime your one control looks like an odd man out....Your overall asthetic appeal of your site is spoilt..."


Now there is an answer to these situations in the new release of VS.Net "Whidbey"... Now you have got MASTER PAGES... These pages will work somewhat similar to "Slide Master" in Microsoft Powerpoint. You can make a Master page for your project and make all the rest of the pages to inherit from this Master Page. The VISUAL INHERITANCE which was not possible earlier in web pages comes alive with Master Pages. You can place your standard banners, Log out links, Help links, Tool bars, Footers for pages etc etc in your Master page and there would be all the rest of your pages inheriting from Master Page have the same controls, same images at the same places. Your development time is reduced drastically, there will be consistency in all your pages giving asthetic appeal to your pages without efforts.

The other situation discussed earlier is solved by SKINS and THEMES.... Analogy here is your windows desktop themes... There will be inbuilt skins and themes available in "Whidbey" which when you simply apply to your web applications they will get an enhanced looks... Well to define these... SKIN can be said as the set of properties and templates that can used to set the size, font, color etc of various controls. When you include some set of skins or stylesheets to change the overall look of a website... then that becomes a THEME... You can even pack themes & skins and apply them to other websites by just transferring them...

Could it get further easier so early???....

- Vishal Joshi
Microsoft MVP .Net

Thursday, August 21, 2003

PREVENTING POSTBACKS OR SETTING FOCUS ON CORRECT CONTROLS ACROSS POSTBACKS

Hi Paddy,
If there are certain things that you need to do at server side on
selection of DropDownList and you anyways want the postback then the focus
to the same control on which the user was working on can be achieved by
SmartNavigation property of ASPX page. You can just go ahead and set the
property SmartNavigation="true" in the page directive of your page which
will maintain the focus across postbacks.
warm regards
Vishal Joshi
Asst. Convener - CNUG | Microsoft MVP
If You Think YOU CAN... You Can...

Hi Paddy,
Set the "AutoPostBack" property of the DropDownlist to false and the
page should not post back on any client side interaction with drop down. By
default this property is false check what is its value now.
Alternatively you can avoid postback using client side Jscript function
activated on selection on dropdownlist. You just need to return false in
the JScript function. But setting "AutoPostBack" property is the correct
way of doing it.
warm regards
Vishal Joshi
Asst. Convener - CNUG | Microsoft MVP
If You Think YOU CAN... You Can...


-----Original Message-----
From: Paddy1010762003
To: Chennai .NET User Group
Sent: 8/21/03 4:05 AM
Subject: Page refresh problem in asp.net

Hi guys,
here is the scenario...I have data entry screen developed in asp.net
with lot of info on the screen. I need to scroll down the screen to see
the whole information on the screen. This cannot be avoided as i need to
populate lot of information on the screen. I have a combo box web server
control displayed at the bottom of the screen To see the combox box
control , i need to scroll down the screen. When an event occurs in the
combo box, say i choose a value in the combo box, the page gets
refreshed becos of post back mechanism and goes to the top of the page.
As a user , it is very annoying everytime i click on the combox , the
page goes to the top . Is there anyway out in asp.net to avoid this kind
of problem. Please suggest.

Wednesday, August 20, 2003

Who am I?
I am one among the thousands of Software Professionals in the IT industry, trying to do what I really like doing. And at the moment I like .Net so am working in it as much as possible (?)... Don't ask how much that means... or how much it pays (It doesn't pay well believe me.. Just kiddin??)

What did I do?
I worked in .Net since December 2001 ( Beta release) and am still working in it. Lots of things I learnt lots unlearned. Just started realizing that there is no end, that many of us who claim to be knowing .Net really know very little of it... But interstingly of whatever little I knew I tried to share as well and did some community activities related to .Net too.

What community activities am I talking about?
Along with Anand M (Microsoft MVP .Net) and other group of friends, started working on a User Group in India called "Chennai .Net Users Group(CNUG)". We started with handful of people and today we are above 1350 in just over an year. Well the group does talk a lot about .Net (CNUG). By the time the group has matured and has caught momentum I came to US (from India, incase you haven't guessed!) for my professional needs, but I am working on a User Group here as well called .Net-Bloomington Users Group (.Net-BUG). Hope to see that also grow sometime.

Why community activities?
Coz there is never one way transaction in teaching/learning. Many a times a student teaches and the teacher learns and visa a versa is anyways true. By trying to give back to the community, does give back a lot in return. You keep learning on topics and subjects which you would probably never work on. I should say the groups and presentations and trainings I have ever attended or given, always made me feel that I was the beneficiary.

What other stuff I do?
I am involved in other activities on newsgroups and usergroups and I also intend to carry out other techincally related stuff. I was also awarded Microsoft's MVP Award. To know more about the award Click Here.

Why Blog?
Coz this is the way I can express myself to the world, to the community which matters to me. See you read it, one more step towards the goal...

What do I do other than work?
I love photograhy, travel, music, movies and swimming, I try that I devote some time to these activites too. I am in the process of expanding my horizons in photography. Though I haven't done anything, but whats harm in trying and blowing the trumpet, atleast out of sheer shame, I will do something.. What say??...

Vishal Joshi
Ph#: +1-309-310-1662.
If You Think YOU CAN.. You Can...

You Can Reach me @ vishalrjoshi@hotmail.com