Thursday, April 18, 2013

ASP.Net Caching - Output cache


What is the use of @ output cache directive? What are the other types of Catching is available?
Three types of catching are
1.Page Level Caching (called Output Caching)
2.Page Fragment Caching (often called Partial-Page Output Caching)
3.Programmatic or Data Caching
Output Caching
Output CachingPage level, or output caching, caches the HTML output of dynamic requests to ASP.NET Web pages. The way ASP.NET implements this (roughly) is through an Output Cache engine. Each time an incoming ASP.NET page request comes in, this engine checks to see if the page being requested has a cached output entry. If it does, this cached HTML is sent as a response; otherwise, the page is dynamically rendered, it's output is stored in the Output Cache engine.
Output caching is easy to implement. By simply using the @OuputCache page directive, ASP.NET Web pages can take advantage of this powerful technique. The syntax looks like this:
<%@OutputCache Duration="60" VaryByParam="none" %>
The Duration parameter specifies how long, in seconds, the HTML output of the Web page should be held in the cache.

The VaryByParam is a useful setting that can be used to cache different "views" of a dynamic page whose content is generated by GET or POST values. For example, you may have an ASP.NET Web page that reads in a Part number from the QueryString and displays information about a particular widget whose part number matches the QueryString Part number. Imagine for a moment that Output Caching ignored the QueryString parameters altogether (which you can do by setting VaryByParam="none"). If the first user visited the page with QueryString /ProductInfo.aspx?PartNo=4, she would see information out widget #4. The HTML for this page would be cached. The next user now visits and wished to see information on widget #8, a la /ProductInfo.aspx?PartNo=8. If VaryByParam is set to VaryByParam="none", the Output Caching engine will assume that the requests to the two pages are synonymous, and return the cached HTML for widget #4 to the person wishing to see widget #8! To solve for this problem, you can specify that the Output Caching engine should vary its caches based on the PartNo parameter by either specifying it explicitly, like VaryByParam="PartNo", or by saying to vary on all GET/POST parameters, like: VaryByParam="*".

Asp.Net Application Tricks and Tips


Asp.Net Application Tricks and Tips


1.       Previous Postback Action triggered on pressing F5

Issue:
                Consider a Data Entry Web Page.  There is a Dropdown to choose the car model and dropdown to choose the rating.  User can choose a Car model and rating and click on submit button.

On submitting the page, one row will be inserted into database, and the page is reloaded.
While reloading, we intentionally clear the last selected values in dropdown.

Now the user clicks on “F5”. Issue is one new row is inserted into database with last selected values. This is because “F5” triggers the last event made by user. Though the dropdown values are empty, the previous values are passed from view state.

We don’t have clue whether the Submit button event is called by the user or because of “F5” key press.

Solution:
As you may know the viewstate is posted back to server on every server call. So on pressing the F5, the same viewstate information will be passed to server. Using the below two functions, we can toggle a Boolean variable to find whether is the actual post back or caused by refresh.
a.       Create a global Boolean variable in your web page
b.      Add the below two methods in your web page.
protected override void LoadViewState(object savedState)
        {
            object[] AllStates = (object[])savedState;
            base.LoadViewState(AllStates[0]);
            refreshState = bool.Parse(AllStates[1].ToString());
            if (Session[SessionKeyNames.IsRefresh] != null)
            {
                if (Session[SessionKeyNames.IsRefresh].ToString() != string.Empty)
                    isRefresh = (refreshState == (bool)Session[SessionKeyNames.IsRefresh]);
            }
        }

protected override object SaveViewState()
        {
            Session[SessionKeyNames.IsRefresh] = refreshState;
            object[] AllStates = new object[3];
            AllStates[0] = base.SaveViewState();
            AllStates[1] = !(refreshState);
            return AllStates;
 }
c.       By checking the value of “isRefresh” in button click, you can decide the F5 or not. If isRefresh is true, you can simply write return to avoid any action.

2.       session expire check
There are multiple ways to check whether session expired or not. Here is the one which we used and working fine.
Here we check the new session property and whether the session id is stored in cookie is available.
                       Why do we check the cookie value?
For the very first time, when the page is accessed the NewSession property is true. But we should not consider this as expired session since it’s first time access. When the page is first accessed, though the NewSession property is true, the cookie is not set with session id. So first time access is passed as per IF condition in below code. In successive access, NewSession property would be false till session expires. Once the session is expired, for the next request, server generates new session id and send to client.
This time NewSession property is true. Also we would be having some value in cookie which is the previous session id value. So this is considered as Session Expired state.
public static bool IsValidSession()
        {
            HttpContext context = HttpContext.Current;
            bool isValidSession = true;

            if (context.Session != null)
            {
                if (context.Session.IsNewSession)
                {
                    HttpCookie newSessionIdCookie = context.Request.Cookies["ASP.NET_SessionId"];
                    if (newSessionIdCookie != null)
                    {
                        string newSessionIdCookieValue = newSessionIdCookie.Value;
                        if (newSessionIdCookieValue != string.Empty)
                        {
                            isValidSession = false;    // This means Session was timed Out and New Session was started      
                           // context.Session.Abandon();
                            ClearSession();
                        }
                    }
                }
            }

            return isValidSession;
        }


3.       on logout link click

Things to be done on logout link click should be decide on design time. Because after clicking the logout, usually we show the logout page. But by using the back button, user can navigate to previous page and do regular operations. To avoid this, do one of the following

a)      Close the browser window on clicking the logout
b)      Clear the session, so that though user navigates via back button, if user does any activity, he will be routed to session expired page. This is the most common approach for standard banking site which I have seen so far (try out www.icicibank.com)


4.       Request.UrlReferrer

How do we check from which page the user is coming from?
Use Request.UrlReferrer property to know the previous page. This can be used to avoid pasting the direct url in browser.
Issue:
For example, from home page user can navigate to details.aspx page. But if user directly paste like http://abc.com/details.aspx in browser and hit enter, then he will be directed to details page. But business rule is to go to detail page only after clicking the submit button in home page.

Solution:
In this scenario, we can use Request.UrlReferrer property to determine whether the user coming from home page or pasted url in browser directly. If he comes from home page, url referrer will have value of home.aspx otherwise null. Using this we can redirect the user appropriately.