Q.

What is ViewState? Explain how it affects performance?

A.

Viewstate in short can be described as Persist changes to the state of a Web Form across postbacks.
EnableViewState is ASP.NET property which can be added to page attributes or to individual asp.net controls. This is to enable/disable view state for that page/control. If you are using a static page or dynamic page where we dont have to retain page control values after postback, it is recommended to set false value to this property. Even this property can be disabled for individual controls in page like datagrid, dropdown/combobox,..etc. if we have no plans of retaining values after postback.
Cost of View State can be saved by disabling it; following are the details,

  1. InPage life cycle events, SaveViewState event Page class gathers collective view state for all controls in its control hierarchy and serializes state to a base-64 encoded string. Similarly on postbacks, LoadViewState event de-serialize the persisted view state data and update the controls in control hierarchy. This step can be minimized based on the number of controls or page using viewstate.
  2. _VIEWSTATE hidden variable which contains the base-64 encoded string form for controls state adds size to Web page(which can be tens of kilobytes) and will take some extra seconds to load in your web browser. This size can be minimized by disabling view state for controls or page.

Q.

What is enableViewStateMac?

A.

enableViewStateMac is an attribute added on the Pages directive to make ViewState tamper proof.Mac so called Message Authentication Code (MAC) is appended to _VIEWSTATE hidden variable when page is sent from server and is validated by comparing the MAC in server and sent from page when page is posted back.MAC validation is on by default in machine.config.

<%@ Page EnableViewStateMac="true" ----- %>

Q.

What is viewStateEncryptionMode?

A.

ViewState is encoded by default but not encrypted.So any use can decode and view the actual contents of ViewState.
So to encrypt ViewState, either a control on a page needs to explicitly request ViewState encryption or viewStateEncryptionMode attribute on

page directive must be set to Always. To request encryption, a control must call the RegisterRequiresViewStateEncryption method of Page class.

<%@ Page ViewStateEncryptionMode="Always" ----- %>

Encryption configuration is set in machine.config by default and can be set in web.config as well.

<machineKey
      validationKey="value,[IsolateApps]"
      decryptionKey="value,[IsolateApps]"
      validation="SHA1|MD5|3DES" />

Q.

What is ASP.NET Cache?

A.

Caching is storing data in memory, which is frequently used or data which is costly to generate for reuse. Usually the cache is preffered when data retrieval from memory is effecient than data retrieval from other locations like database. Cache is stored as key-value pair dictionary in dotnet. Opting cache based on cost can increase application performance to high levels.

Q.

What are different types of Caching?

A.

  1. Page or Output Caching – Used mainly for static pages or pages which change very less frequently.
  2. Fragmented Caching – Used to cache parts/sections of page, usually ascx pages.
  3. Cache API/ Data Cache – Usually used to cache Objects in code.

Q.

How is Caching different from Application or Session object?

A.

Expiration can be added to Items in Cache when we compare it to Application or Session Objects. Also Cache supports file, key, and time based dependencies as well as callbacks.

Q.

Explain Cache dependency in detail?

A.

File-based Dependency

CacheDependency dependency =
                 new CacheDependency(Server.MapPath("productslist.xml"));
XmlDocument xmlProductsList = new System.Xml.XmlDocument();
xmlProductsList.Load(Server.MapPath("productslist.xml"));
Cache.Insert("productslist", xmlProductsList, dependency);

CacheDependency namespace is System.Web.Caching.
XmlDocument namespace is System.Xml.

Here we are adding dependency of Cache to an XML file productslist.xml. So whenever the XML file is modified, productslist cache will be cleared.

Key-based Dependency

string[] dependency = new string[1];
dependency[0] = "productslist";
CacheDependency cacheDependency = new CacheDependency(null, dependency);
Cache.Insert("productdetaillist", dataSetProductDetailList, dependency);

dataSetProductDetailList can be any object which is stored in cache.
Here we are adding key based dependency. We already have a Cache productslist created earlier and in the above code, dependency is added to productdetaillist Cache with productslist Cache. So whenever productslist Cache changes productdetaillist will be removed from Cache.

Time-based Dependency
Two types of time-based dependency exists,

  • Absolute : Sets an absolute time for expiration. for eg: current time + 10 minutes for the Cache entry to expire.
  • Sliding : Resets the time for the item in the Cache to expire on each request.
TimeSpan ts = new TimeSpan(0, 5, 0);
DateTime dt = new DateTime(0, 0, 1);
Cache.Insert("productdetaillist", dataSetProductDetailList, null, dt, ts);

Here ts is for Absolute expiration and dt is for Sliding expiration.

Q.

How is Callback handled in ASP.NET Cache?

A.

ASP.NET supports 2 types of callbacks,

  • CacheItemRemovedCallback : Will be called after clearing the cache. Can be used to refill the cache or for notification.
    CacheItemRemovedCallback removeCallback =
                         new CacheItemRemovedCallback(AfterCacheRemoved);
    public void AfterCacheRemoved(string key,
                                              object cacheItem,
                                              CacheItemRemovedReason reason)
    {
         //Write logic for updating cache
        // or notify cache is cleared
    }

    CacheItemRemovedCallback, namespace will be System.Web.Caching.

  • CacheItemUpdateCallback : will be called just before cache is cleared. Can be used for notification or updating cache item before clearing it.
    CacheItemUpdateCallback updateCallback =
                       new CacheItemUpdateCallback(BeforeCacheRemoved);
    public void BeforeCacheRemoved(string key,
                    CacheItemUpdateReason reason,
    		out object cacheItem,out CacheDependency dependency,
    		out DateTime dt,out TimeSpan ts)
    {
    	//Write logic for updating cache
            //or notify cache is going to be cleared
    }

Q.

How to control page output caching duration?

A.

Use Duration attribute in page directive to control cache expiration time or duration for expiration of page cache.

<%@ OutputCache Duration="10" %>

The above directive added to the top of an page instructs ASP.NET to cache the html output of the page for 10 seconds and after 10 seconds the page will recompiled.

I will be adding contents to this article as i find time. Mainly it will cover most ASP.NET terms, technologies and optimization of application will be also concentrated.

Be Sociable, Share!