How to keep session alive in ASP.Net using Webservice and jQuery

Most of the time when we develop intranet web applications, our clients request us that they only have to log in in the morning when they reach office. It seems very easy to implement i.e. increase session timeout to 10+ hours and we are done.

But there is a drawback of this approach. Even if user close the browser, session's data will occupy server's memory till 10+ hours and our site's performance will go down. So, this is certainly not a good choice for us.

There are many alternates to solve above problem. In this post, I am sharing one of the possible solution.

First I have created an asmx service i.e. SessionAlive:-

/// <summary>
    /// Summary description for SessionAlive
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class SessionAlive : System.Web.Services.WebService
    {
 
        [WebMethod]
        public void UpdateSession()
        {
            HttpContext.Current.Session["tempVariable"] = DateTime.Now;
        }
    }

Note that by default [System.Web.Script.Services.ScriptService] is commented when you create a new service. You need to uncomment above line to ensure that methods in this service are accessible for javascript or jQuery.

Also i have created UpdateSession() method which updates a value in session.

Now here is the javascript which I added in my page.

<script type="text/javascript" src="JS/jquery-1.4.2.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        setTimeout(updateSession, 1000*60);//Timeout is 1 min
    });
    
    function updateSession() {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "SessionAlive.asmx/UpdateSession",
            data: "{}",
            dataType: "json"
        });
        setTimeout(updateSession, 1000 * 60);
    }
</script>

Above function calls web service after every minute to ensure that session is not time out. Hopefully this will be useful for you. Feel free to add comments and suggestions.

PageMethod an easier and faster approach for Asp.Net AJAX

We can easily improve user experience and performance of web applications by unleashing the power of AJAX. One of the best things which I like in AJAX is PageMethod.

PageMethod is a way through which we can expose server side page's method in java script. This brings so many opportunities we can perform lots of operations without using slow and annoying post backs.

In this post I am showing the basic use of ScriptManager and PageMethod. In this example I am creating a User Registration form, in which user can register against his email address and password. Here is the markup of the page which I am going to develop:-

<body>
    <form id="form1" runat="server">
    <div>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup"  />
    </div>
    </form>
</body>
</html>

Here is how my Page looks like:-


To setup page method, first you have to drag a script manager on your page.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

Also notice that I have changed EnablePageMethods="true. This will tell ScriptManager that I am going to call Page Methods from client side.

Now Next step is to Create a Server Side function. Here is the function which I created, this function validates user's input:-


[WebMethod]
public static string RegisterUser(string email, string password)
{
    string result = "Congratulations!!! your account has been created.";
    if (email.Length == 0)//Zero length check
    {
        result = "Email Address cannot be blank";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }
 
    else if (password.Length == 0)
    {
        result = "Password cannot be blank";
    }
    else if (password.Length < 5)
    {
        result = "Password canonot be less than 5 chars";
    }
 
    return result;
}

To tell script manager that this method is accessible through javascript we need to ensure two things. First this method should be 'public static'. Second there should be a [WebMethod] tag above method as written in above code.

Now I have created server side function which creates account. Now we have to call it from client side. Here is how we can call that function from client side:-

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>

To call my server side method Register user, ScriptManager generates a proxy function which is available in PageMethods. My server side function has two paramaters i.e. email and password, after that parameters we have to give two more function names which will be run if method is successfully executed (first parameter i.e. onSucess) or method is failed (second parameter i.e. result).

Now every thing seems ready, and now I have added OnClientClick="Signup();return false;" on my Signup button. So here complete code of my aspx page :-

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="Signup();return false;" />
    </div>
    </form>
</body>
</html>

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>


Finally I have pressed Signup button and I am geting these messages.

See it is really simple. Now there is a fair chance that instead of these fancy looking messages you might be getting this error:-

If you see error like this then double check following things:-
  1. You have set EnablePageMethods="true" in ScriptManager.
  2. You have added [WebMethod] tag in your server side method.
  3. Your server side method is 'public static'

Hopefully this will be useful for you feel free to share your comments and suggestions.