How to implement Cookieless Session in ASP. Net

By default ASP.Net relies on cookies to store session id. Cookies are actually a text data which is stored in browser. Generally cookies are not considered a safe way to store information. Also there is a chance that browser have disabled the cookies and in that case our application wont work on that browser.

To avoid such situation, we can use Cookieless session. To implement that you just need to set cookieless attribute to true in your session tag. Here is how you can do this:-
<system.web>
  <sessionState mode="InProc" cookieless="true" timeout="120" />
</system.web>

Once you have done that your URL will contain the session id, here is the snapshot of URL before and after implementing cookieless=true:-
As you can see that in the URL session id is visible.

Feel free to share your comments, Happy Codding !!!

How to Clear all elements from Cache

There are many situations when we want to clear contents of the cache in our ASP. Net application. Here is a quick and dirty way to remove all the contents from our cache.

        /// <summary>

        /// Clears all the data from Cache

        /// </summary>

        public void ClearCache()

        {

            try

            {

                List<string> keyList = new List<string>();

                IDictionaryEnumerator CacheEnum = HttpContext.Current.Cache.GetEnumerator();

                string cacheKey;

 

                //Read all the keys from cache and store them in a list

                while (CacheEnum.MoveNext())

                {

                    cacheKey = CacheEnum.Key.ToString();

                    keyList.Add(cacheKey);

                }

 

                //Remove entries from cache

                foreach (string key in keyList)

                {

                    HttpContext.Current.Cache.Remove(key);

                }

                keyList.Clear();

                Response.Write("Cache Cleared");

            }

            catch

            {

                Response.Write("Cache NOT Cleared");

            }

        }


General I create a page name ClearCache.aspx and call above function in page_load method. So when ever I want to clear cache's contents I just call that page using URL.

Feel free to comment. Happy Coding !!!

Understanding Asp.net Cache Sliding Expiration and Absolute Expiration

Asp .Net provides two different ways to expire the cache on the basis of time. Here are two aproaches:-
  1. Sliding Expiration
  2. Absolute Expiration 
1. Absolute Expiration
Absolute expiration means that your data will be removed from cache after fixed amount of time either it is accessed or not. Generally we use it when we are displaying data which is changing but we can afford to display outdated data in our pages.  Mostly I put all of my dropdown values in cache with Absolute Expiration. Here is how you can code:-
DataTable dt = GetDataFromDatabase();
Cache.Insert("AbsoluteCacheKey", dt, null,
DateTime.Now.AddMinutes(1), //Data will expire after 1 minute
System.Web.Caching.Cache.NoSlidingExpiration);

2. Sliding Expiration
Sliding expiration means that your data will be removed from cache if that is not accessed for certain amount of time. Generally we store that data in this cache mode which is accessed many time on certain occasions. For example if you go in account settings section of a site, then you will be frequently accesing account information in that section. But most of the time you wont be using account setting's related data so there is no point of storing that data in cache. In such scenarios sliding expiration should be used. here is how you can save data in cache with sliding expiration:-

DataTable dt = GetDataFromDatabase();

Cache.Insert("SlidingExpiration", data, null,

System.Web.Caching.Cache.NoAbsoluteExpiration,

TimeSpan.FromMinutes(1));//Data will be cached for 1 mins


Hopefully this information will be useful for you, feel free to share your feedback with me. Happy Coding !!!

Article of the Day, PageMethod - An Easier and Faster Approach for ASP.NET Ajax

On Sunday, Feb 20, 2011, my article 'PageMethod - An Easier and Faster Approach for ASP.NET Ajax' was selected as 'Article of the Day' at http://www.asp.net.


I also recommend to all of readers to do share useful articles on http://www.asp.net/community. Whenever you found an article which is interesting and can be useful for others.

How to Pass value from ASP.Net to Javascript

Many times we have to pass a value from server side (ASP.Net) to client side (java script) and many peoples ask this question that how we can accomplish this task. Here I am sharing some examples in which I will tell different approaches to send values from ASP.Net to javascript.

1- <%=%> Construct
You can simply use a <%=%> construct to pass server side variable to client side. Here is how you can do this:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
<script type="text/javascript">
    var myVariable = '<%=ServerSideVariable %>';
    alert(myVariable);
</script>

Here is the server side code in which I assigned value to my variable:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    public string ServerSideVariable { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        ServerSideVariable = "Zeeshan Umar";
    }
}

Here is the output when I run the page, a popup appears saying 'Zeeshan Umar'.

2) Hidden Field
You can also use hidden fields to store values which can be used in javascript here is how you can do this:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:HiddenField ID="hfValueFromServer" runat="server" />
    </div>
    </form>
</body>
</html>
<script type="text/javascript">
    var valueFromServer= document.getElementById('<%=hfValueFromServer.ClientID%>').value;
    alert(valueFromServer);
</script>

Here is the server side code in which I assigned value to hidden field:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        hfValueFromServer.Value = "Zeeshan Umar javascript tutorial";
    }
}

And here is the output of above code, same as expected 'Zeeshan Umar javascript tutorial':-

See how simple is it to access server side variables in javascript. Do share me with your valuable feedback and comments. Happy coding !!