About the author

Vijay Kodali
E-mail me Send mail

Recent comments



The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2024

Asp.net session on browser close

How to capture logoff time when user closes browser?


How to end user session when browser closed?

These are some of the frequently asked questions in asp.net forums.

In this post I'll show you how to do this when you're building an ASP.NET web application.

Before we start, one fact:

There is no full-proof technique to catch the browser close event for 100% of time. The trouble lies in the stateless nature of HTTP. The Web server is out of the picture as soon as it finishes sending the page content to the client. After that, all you can rely on is a client side script. Unfortunately, there is no reliable client side event for browser close.


The first thing you need to do is create the web service. I've added web service and named it AsynchronousSave.asmx. 

 Open Dialog

Make this web service accessible from Script, by setting class qualified with the ScriptServiceAttribute attribute... 


Add a method (SaveLogOffTime) marked with [WebMethod] attribute. This method simply accepts UserId as a string variable and writes that value and logoff time to text file. But you can pass as many variables as required. You can then use this information for many purposes.


To end user session, you can just call Session.Abandon() in the above web method.

To enable web service to be called from page’s client side code, add script manager to page. Here i am adding to SessionTest.aspx page


When the user closes the browser, onbeforeunload event fires on the client side. Our final step is adding a java script function to that event, which makes web service calls. The code is simple but effective


My Code

HTML:( SessionTest.aspx )


C#:( SessionTest.aspx.cs )


That’s’ it. Run the application and after browser close, open the text file to see the log off time.


The above code works well in IE 7/8. If you have any questions, leave a comment.

Posted by vijay on Thursday, April 29, 2010 6:09 PM
Permalink | Comments (22) | Post RSSRSS comment feed

Visual Studio 2008 short cuts

I know there are many posts dedicated to this topic. For example, Sara Ford posted about 290 shortcuts on her blog. Check Zain Naboulsi blog for VS 2010 tips.

But it’s almost impossible to use all of them on daily basis. And further most of them are really not that useful. Here are 10 of my favorite Visual Studio keyboard shortcuts, ones I use most..

1) Double TAB

If you know snippet key name, write and click double Tab.

For example: Write


and then click tab key twice to get

if (true)

Similarly write try then click tab key twice to get


catch (Exception)

2) CTRL + TAB to switch open windows in visual studio

3) CTRL+K and CTRL+D to format code

4) CTRL+SHIFT+V to cycle through clipboard

5) SHIFT+ALT+ENTER for full screen mode

6) F7 to switch between code behind and .aspx files

7) CTRL+H or CTRL+SHIFT+H for find and replace

8) Ctrl+F5 to run without debugging. F5 only will run in debugging mode

    F11 to step into a method. SHIFT+F11 to step out of a method. F10 to step over a method.

9) F9 toggle and un-toggle breakpoints

10)F12 to go to definition


What’s your favorite Visual Studio keyboard shortcut/hidden feature/trick..?

Posted by vijay on Thursday, March 4, 2010 9:42 PM
Permalink | Comments (1) | Post RSSRSS comment feed

Convert time from one timezone to another timezone in Asp.Net

Handling timzone is quite simple in Asp.Net applications. First thing,   you should always store DateTime values in the DB in one timezone (UTC is most commonly used).  This eliminates many conversion issues.

Here is the sample code..

DateTime time1 = new DateTime(2008, 12, 11, 6, 0, 0);  // your DataTimeVariable 
TimeZoneInfo timeZone1 = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); 
TimeZoneInfo timeZone2 = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"); 
DateTime newTime = TimeZoneInfo.ConvertTime(time1, timeZone1, timeZone2);

Get all available/supported Timezones in .Net TimeZoneInfo class

      foreach (var tz in TimeZoneInfo.GetSystemTimeZones())
                Response.Write(tz.DisplayName + " is Id =','" + tz.Id + "'");

Posted by Vijay on Wednesday, January 6, 2010 8:24 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Disabling script debugging in VS 2008 and IE8

With VS 2008 and IE 8, JavaScript debugging is automatically enabled even if script debugging is set to disabled in IE8 settings. This will help developers in debugging scripts without having to change debugging features within browser. While this is a good feature for most developers, it takes up to 10X time to load a page that is heavy on client side scripts. 

How to disable script debugging in IE8?

Go to a Command Prompt (cmd) and Enter… 

reg add HKLM\SOFTWARE\Microsoft\VisualStudio\9.0\AD7Metrics\Engine\{F200A7E7-DEA5-11D0-B854-00A0244A1DE2} /v ProgramProvider /d {4FF9DEF4-8922-4D02-9379-3FFA64D1D639} /f 

To enable it again go to the Command Prompt and Enter...

reg add HKLM\SOFTWARE\Microsoft\VisualStudio\9.0\AD7Metrics\Engine\{F200A7E7-DEA5-11D0-B854-00A0244A1DE2} /v ProgramProvider /d {170EC3FC-4E80-40AB-A85A-55900C7C70DE} /f 

Tip from:Gregg Miskelly of Visual Studio team debugger team

Posted by vijay on Wednesday, July 1, 2009 2:40 PM
Permalink | Comments (1) | Post RSSRSS comment feed

Web Application Project vs Web Site Project in Visual Studio

Web Site Project is deployed with source code to the server and all compilation takes place at runtime.

Web Application Projects, the code behind classes are compiled to dll. That dll is deployed and at runtime, the compiled code in the dll and the markup is combined to create a class which is used by the server to render output.


Good post by anthony on this

post by Stephen on this topic

Posted by vijay on Sunday, July 6, 2008 9:04 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Implicitly Typed Local Variables-“Var”

In C# 3.0, you can declare an integer  as –


var first = 7;

Console.WriteLine("First variable is of type: {0}", first.GetType());


It will return”Int32” as DateType, even though we declare it as “var”. So what  is “var”?

from MSDN..

Local variables can be given an inferred "type" of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.

To put it simply "var" is a keyword that results in variable being of the same data type, of the initializer. It works similar to “object” type in older version. But there is great difference between “Object” and “var”. Check following code snippet-


object newObj = 58;  

int test = newObj; //this line result in an error "Cannot implicitly convert type object to int"

 int test = (int)newObj; // this line will work. But result in boxing..additional overhead


So Objects have boxing and unboxing issues. Now consider same instance with “var”- 


var newObj = 22;

int test = newObj; //no boxing involved. It is type-safe


C# is still strongly typed. “Var” is NOT a variant, everything is known by the compiler at compile-time.

Posted by vijay on Friday, January 18, 2008 9:11 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Some new features in Visual studio 2008

1)       Multi-Targeting Support

Earlier you were not able to working with .NET 1.1 applications directly in visual studio 2005. Now in Visual studio 2008 you are able to create, run, debug the .NET 2.0, .NET 3.0 and .NET 3.5 applications. You can also deploy .NET 2.0 applications in the machines which contains only .NET 2.0 not .NET 3.x.

2)       Vertical Split View :

This feature show both design and source code in single window.  To enable vertical split-view orientation in VS 2008, select the tools->options menu item and go to the HTML Designer->General section.  Then check the "Split views vertically"  checkbox

3)       Javascript Debugging

Visual Studio 2008 makes it is simpler with javascript debugging. You can set break points and run the javaScript step by step and you can watch the local variables when you were debugging the javascript and solution explorer provides javascript document navigation support.

4)       Web Design and CSS Support

 Microsoft has added new Web Design and CSS Support to Visual Studio 2008

5)       AJAX & Silverlight Library support for ASP.NET

Previously developer has to install AJAX control library separately that does not come from VS, but now if you install Visual Studio 2008, you can built-in AJAX control library. Also in VS 2008 Silverlight Library is inbuilt.

6)       Access to .NET Framework Source Code

you can debug the source code of .NET Framework Library methods.


Posted by vijay on Friday, January 4, 2008 2:54 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Session timeout error in Asp.Net

1.) We were facing timeout issue on one of our servers. Web.config settings had no effect on the time out.

2.) I have set the session to last 24 hours with this statement in my web.config:

		<sessionState mode="InProc" timeout="720"/>	

     But the session still ends after 20 min of inactivity. What am I missing here?

I saw similar type of questions frequently in Asp.Net forums. Here is a post to help those

What is Session State?

ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. In order to preserve server memory, ASP.NET implements a rolling timeout mechanism which discards the session information for a user if no request is seen within the timeout period (default 20 minutes which is reset with each request).

You would also have to setup session timeout in IIS in addition to webconfig settings.

In IIS6 change the session timeout setting by going to:
'Configuration' Button -> 'Options' Tab -> Tick Enable Session state, increase value from default 20 mins to desired value

In IIS7 change the session timeout setting by going to:

Features View pane –> Application Development – >Sessions state

IIS 7-1 

IIS 7-2

Don’t see Session state icon in IIS 7? Check this blog post


Here are some other reasons for Session loss..

1.) IIS worker process restart or Application Pool recycle.(Check the System logs)

2.) Application Domain restart due to Antivirus scans or changes in Config files.


Please leave a comment.

Posted by vijay on Sunday, December 2, 2007 8:37 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Limit number of items to be selected in Asp.Net ListBox

Here is an example to validate ListBox. This validation will check user to select less than10 items 
<script type="text/javascript" language="javascript">
function CustomValidator1_ClientValidate(source,args)
var listbox = document.getElementById("<%=ListBox1.ClientID %>");
var total = 0;
var i=0;
for( i = 0; i < listbox.options.length; i++ )
 if (listbox.options[i].selected) 
   total ++; 
    if (total >10) {
      args.IsValid = false;
 args.IsValid = true; return;


<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" Height="100%"
<asp:Button ID="Button3" runat="server" OnClick="Button1_Click" Text="Button" />
<asp:CustomValidator ID="CustomValidator1" runat="server" Display="Dynamic" ErrorMessage="Please select 10 items only."
ClientValidationFunction="CustomValidator1_ClientValidate" OnServerValidate="CustomValidator1_ServerValidate">

Code Behind:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) 
  int count = 0; 
  for (int i = 0; i < ListBox1.Items.Count; i++) 
        if (ListBox1.Items[i].Selected) 
 args.IsValid = (count > 10) ? false : true; 

Posted by vijay on Wednesday, September 19, 2007 9:45 AM
Permalink | Comments (0) | Post RSSRSS comment feed