Sunday 5 January 2014

Handling Session Timeout for Ajax Requests

ASP.Net engine is clever enough to deal with normal (non-ajax) requests when user session times out, the asp.net engine automatically redirects the user to login page specified in the web.config file.
Now, the trouble is when the request is made through ajax. The aps.net engine does its bit by redirecting the user to login page but the problem is that redirected page goes as a response to ajax response handler in the javascript. And what happens then? Something very unexpected. You will observe very weird behavior like some javascript error or a distorted UI or may be nothing.
How to deal with such situation? I will suggest here a very simple solution that may help you escape this trouble.

Add following code in the Global.asax file of your web application:

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
        // This is a check for Ajax request so that other requests won't fall in this condition.
        if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
        {
            if (!Request.IsAuthenticated)
            {
                // You can set the status code to something else if you do not feel 401 as appropriate.
                Response.StatusCode = 401;
                Response.End();
            }
        }
}

Add following code in the javascript:

$(document).ajaxComplete(function (sender, e) {
        if (e.status == 401) {
            alert("Your session has timed out.");
            window.location.href = "Login.aspx";
        }
 });


Above code works if you are using Jquery else you can write the same code in onreadystatuschanged event of XMLHttpRequest.

Also keep in mind that the javascript code should be included in the master page of you application so that it is available to all the pages.



Thursday 2 January 2014

ClickOnce crashing visual studio

Here I am writing one of my deployment issue encounter which gave me tough time. I was trying to deploy an application through ClickOnce and each time I would try publishing it and the visual studio crashes each time.
After struggling a lot I could find out the issue but it took me hours to track it down however the issue was very small.
The issue was due to User Access Control (UAC).

Now, how can you resolved this issue:
1. Go to project properties
2. Go to application tab.

3. Change the Manifest property to Create application without a manifest in the dropdown highlighted in the image below.

Save the project settings and I hope your issue should be resolved.