Month: December 2011

localStorage–Avoid Cookies!

With introduction of HTML 5 localStorage,  storing of small chunks of information in Cookies got eliminated! HTML 5 LocalStorage is an awesome feature which makes the storing and retrieving the data pretty easy.

Let us look at a simple example to demonstrate the HTML 5 LocalStorage feature!

The below example shows how to store “UserName” in to LocalStorage and retrieve it back!

<!DOCTYPE html>
<html>
<head>
    <title>HTML 5 World!!!</title>
</head>
<body>
    <header>HTML 5 Local Storage Demo!</header>
        <input type="text" id="txtUserName" />
        <input type="button" value="Save" onclick="SaveToOfflineStorage();" />
        <label id="msg" ></label>
    <footer>Copyright &copy;2011</footer>

    <script type="text/javascript">

        if (localStorage) {

            var UserName = localStorage.getItem("UserName");
            document.getElementById('txtUserName').value = UserName;
        }

        function SaveToOfflineStorage() {
            try {
                //If localStorage supports with the browser
                if (localStorage) {
                    var txtValue = document.getElementById('txtUserName').value;
                    localStorage.setItem("UserName", txtValue);
                    document.getElementById('msg').innerHTML = "Saved Successfully!";
                }
            }
            catch (err) {
                document.getElementById('msg').innerHTML = err.Description;
            }
        }
    </script>
</body>
</html>

NOTE: The above example works on HTML 5 Compatible browsers – Microsoft IE9 & above, Mozilla Firefox 3.5 & above, Google Chrome etc.,

You can also take advantage of sessionStorage,  which stores data temporarily for particular browser session! It works similar like Session in ASP.NET, JSP etc.,

Happy HTML5 Web Programming!!!

Invoking Server Side code using ASP.NET AJAX Client Callback on Web browser close

If your ASP.NET web application creates temporary data for the each session, it needs to be deleted while user logs out. If you use InProc session mode, then you can handle Session_End event in the Global Application file(Global.asax) to clear the temporary files.

Suppose if you use other than InProc session mode[i.e., StateServer, SQLServer etc.,], then you have to write custom logic to delete the temporary files while user logs out.

Till now you everything is fine, if user logs out of the using Logout option in your web application. What if User closes the browser unintentionally? The temporary files remain undeleted!

Let us discuss a solution which handles the above problem using ASP.NET AJAX with JavaScript.  First of all we need to a notification, when user closes the browser. So let us create a JavaScript function, which notifies the Web browser close.

<script type="text/javascript">
        window.onbeforeunload = NotifyBrowserClose;
        function NotifyBrowserClose() {
            return "Are you sure to close the browser?";
        }
    </script>

The above code notifies the user, if he tries to close the browser.

NOTE: User gets notification even when he traverse to other page. So you need to use a Boolean variable to check whether  the user is traversing to other page or trying to close the browser!

Now we will create Server Side Code to delete the temporary files! Implement the ICallbackEventHandler interface to call Server Side code from Client code(JavaScript).

#region ICallbackEventHandler Members

        public string GetCallbackResult()
        {
            return "";
        }

        public void RaiseCallbackEvent(string eventArgument)
        {
            string      strTempLoc      =  Session["TempFilesDir"].ToString();
            string[]    strTempFiles    = null;

            try
            {
                if (!string.IsNullOrEmpty(strTempLoc) &&
                    Directory.Exists(strTempLoc))
                {
                    strTempFiles = Directory.GetFiles(strTempLoc);

                    //Delete all the files in the temp location
                    foreach (string strTempFile in strTempFiles)
                    {
                        File.Delete(strTempFile);
                    }

                    Directory.Delete(strTempLoc);
                }
            }
            catch (IOException)
            {

            }

        }

        #endregion

Now register the JavaScript functions to invoke the Server Side code.

protected void Page_Load(object sender, EventArgs e)
{
//Get the Client Call back event reference
            string strCallBackRef = Page.ClientScript.GetCallbackEventReference(this, "", "DeleteStatus", "");

            //Form the callback function which is invoked in the Client side
            string strCallBackScript = "function DeleteTempFiles()" + "{" + strCallBackRef + ";}";

            //Register
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
                                                        "MyServerCall",
                                                        strCallBackScript,
                                                        true);
}//end: Page_Load function

Now invoke the function on Web browser close as shown below!

 <script type="text/javascript">

        window.onbeforeunload = NotifyBrowserClose;
        function NotifyBrowserClose() {
            //Server Side Code call back
             DeleteTempFiles();
        }

       //Client Call back
        function DeleteStatus(result) {
        }

    </script>

Hope it helps u…

Happy Web Programming!!!