Wednesday, October 20, 2010

Keeping Session Alive in Asp.Net

some time we have a requirement that we want to keep our session alive. A sudden solution that come to mind is that increase the session timeout in IIS. But this solution don't work well as we might except. It create issues like we have to increase timeout also for Application Pool. Because Application Recycles itself after 30 mins if no request hit server. I am Demonstrating two Strategies here for keeping session alive.

1. Approach No 1 Using JQuery and Handler.
Simply Add a Generic Handler to your web site like "Ping.ashx" or "KeepAlive.ashx" whatever you want. (The Reason i prefer handler over aspx pages in such scenarios is because Handler are fast as compare to aspx page which has a complete life cycle to run). In this handler simply add line of code like.
Context.Response.Write(" "); /// not necessory.
Now on your aspx page add following Code


2. Using IFrame.
Create a aspx page or Handler same as above and add the following line of code
context.Response.AddHeader("Refresh", Convert.ToString(( Session.Timeout * 60 ) -120 ));
after that Add following javascript code on you page.


I hope this will help.

Thursday, October 14, 2010

Perfect way to get Client IP Address in Asp.Net

Getting visitor IP is very frequent requirement in Web Development. There are many confusion about the method to get IP in best way. First of all be aware not to use System.Net.Dns.GetHostAddresses(strHostName) method because it will always return IP Address of the local machine on which Application is running. Use the following function to get IP Address


string clientIP;
string ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ip))
{
string[] ipRange = ip.Trim().Split(',');
int le = ipRange.Length - 1;
clientIP = ipRange[le];
}
else
clientIP = Request.ServerVariables["REMOTE_ADDR"];


First check HTTP_X_FORWARDED_FOR. It will give IP address of the client machine if client is using proxy server and if its null then read the IP address from Header.
Currently these are the only options available in Asp.Net. and they mostly work fine.

Note:Some times if NAT is enabled on Web server there are cases when It always pick local IP no matter what method you use. Check of NAT (Network Address Translation) for further information.
Hope this will help :). Any Suggestion, Correction and Updation is welcomed.