Sunday, 16 March 2014

Interview Questions & Answers on Caching in ASP.NET(Part 1)

1.      What is  an application object ?
Application object can be  used in situation where we want data to be shared across users globally.

2.      What’s the difference between Cache object and application object ?
The main difference between the Cache and Application objects is that the Cache object  provides cache-specific features, such as dependencies and expiration policies.

3.      How can get access to cache object ?
The Cache object is defined in the System.Web.Caching namespace. You can get a reference to the Cache object by using the Cache property of the HttpContext class in the System.Web namespace or by using the Cache property of the Page object.

4.      What are dependencies in cache and types of dependencies ?
When you add an item to the cache, you can define dependency relationships that can
force that item to be removed from the cache under specific activities of dependenci
es.Example if the cache object is dependent on file and when the file data changes you
want the cache object to be update. Following are the supported dependency :-

File dependency :- Allows you to invalidate a specific cache item when a disk
based file or files change.
√ Time-based expiration :- Allows you to invalidate a specific cache item
depending on predefined time.
√ Key dependency :-Allows you to invalidate a specific cache item depending
when another cached item changes.

5.      What is Cache Callback in Cache ?
Cache object is dependent on its dependencies example file based, time based  etc...Cache items remove the object when cache dependencies change.

ASP.NET provides capability to execute a callback method when that item is removed from cache.

6.      What is scavenging ?
When server running your ASP.NET application runs low on memory resources, items are removed from cache depending on cache item priority. Cache item priority is set when you add item to cache. By setting the cache item priority controls the items scavenging are removed first.

7.      What are different types of caching using cache object of ASP.NET?
You can use three types of output caching to cache information that is to be transmitted to and displayed in a Web browser:

A). Page Output Caching - Page output caching adds the response of page to cache object. Later when page is requested page is displayed from cache rather than creating the page object and displaying it. Page output caching is good if the site is fairly static.
B). Page  Fragment Caching - If parts of the page are changing, you can wrap the static sections as user  controls and cache the user controls using page fragment caching.
C). Data Caching:  it uses cache object to store the cached data
8.      How can you cache different version of same page using ASP.NET  cache object ?
Output cache functionality  is achieved by using “OutputCache” attribute on ASP.NET
page header. Below is the syntax -

<%@ OutputCache Duration="20" Location="Server" VaryByParam="state"
VaryByCustom="minorversion" VaryByHeader="Accept-Language"%>

VaryByParam :- Caches different version depending on input parameters send
through HTTP POST/GET.

VaryByHeader:- Caches different version depending on the contents of the
page header.

VaryByCustom:-Lets you customize the way the cache handles page variations
by declaring the attribute and overriding the GetVaryByCustomString handler.

VaryByControl:-Caches different versions of a user control based on the value of properties of ASP objects in the control.

9.      How will implement Page Fragment Caching ?
Page fragment caching involves the caching of a fragment of the page, rather than the
entire page. When portions of the page are need to be dynamically created for each user request this is best method as compared to page caching. You can wrap Web Forms user control and cache the control so that these portions of the page don’t need to be recreated each time.

10.  What is SQL Cache Dependency in ASP.NET 2.0?
SQL cache dependencies is a new feature in ASP.NET 2.0 which can automatically invalidate a cached data object (such as a Dataset) when the related data is modified in the database. So for instance if you have a dataset which is tied up to a database tables any changes in the database table will invalidate the cached data object which can be a dataset or a data source.

11.  How do we enable SQL Cache Dependency in ASP.NET 2.0?
 Below are the broader steps to enable a SQL Cache Dependency:-
• Enable notifications for the database.
• Enable notifications for individual tables.
• Enable ASP.NET polling using “web.config” file.
• Finally use the Cache dependency object in your ASP.NET code.

12.  What are the various ways of doing caching in ASP.NET ?
You can cache by using output cache directive , cache object and application object.

13.    What's the difference between cache and application object ?
In cache object you can define dependency properties , in application object you can not. In other words when the data which is cached changes even the cache object gets refreshed , but this is not the case of application object. You need to do a pull to refresh the data.

14.      Define Caching in ASP.NET. 
Caching technique allows to store/cache page output or application data                on the client. The cached information is used to serve subsequent requests that avoid the overhead of recreating the same information.

16. What are the  types of Caching using Cache object of ASP.NET.
   Page output  Caching
   Page fragment  Caching
   Programmatic or data  Caching

17.Explain the types of Caching using Cache object of ASP.NET.
  • Page output: Is used to fetch information or data at page level. It is best used when the site is mainly static. Used by declaring the output page directive
  • Page fragment: Is used to cache the structure level information. It is used when parts of pages change. For example: user control
  • Programmatic or data: Is used to fetch the information of an application quickly based on the requirements.
   18.What are the Advantages of Caching?
  •  Cache concept can make the performance of your application.
  • Reduce load on Web Services/ Database.
  • Reliability.
19.   What are the  Disadvantages of Caching?

·         Caching approach will not be coherent with the actual data content in the delayed writes.
·         Increased Maintenance.
·         Scalability Issue.

20.Give me the reasons when ASP.NET removes the data from CACHE?
·Because memory on the server is low, a process known as scavenging.
·Because the item in the cache has expired.
·Because the item's dependency changes.

21.What are the different types of priorities?
  • AboveNormal
  • BelowNormal
  • Default
  • High
  • Low
  • Normal
  • NotRemovable
    22.Give name of three methods of putting data into the data cache:?
            cache()
            cache.add ()
       cache.insert().

     23 .What are different types Caching Properties?
·         CacheDuration
·         CacheExpirationPolicy
·         CacheKeyDependency
·         EnableCaching
·         CacheItemPriority

 24.  How do you cache multiple responses from a single Web form?
The VaryByParam attribute lets you cache multiple responses from a single Web form based on varying HTTP POST or query string parameters. Setting VaryByParam to None caches only one response for the Web form, regardless of the parameters sent.
You can also cache multiple responses from a single Web form using the VaryByHeaders or VaryByCustom attribute.

The VaryByCustom attribute lets you cache different responses based on a custom string. To use VaryByCustom, override the GetVaryByCustomString method in the Web application’s Global.asax file.
25. Is it possible to cache a web form without using @OutputCache directive?
Yes, you can cache a web form using the Response object’s Cache property, which returns an HttpCachePolicy object for the response. The HttpCachePolicy object provides members that are similar to the OutputCache directive’s attributes.

26.  Give a simple example to show how to cache a web form without using @OutputCache directive?
For example, the following code caches the Web form’s response for 60 seconds:
private void Page_Load(object sender, System.EventArgs e)
{
// Cache this page
DateTimeLabel.Text = System.DateTime.Now.ToString();
// Set OutputCache Duration. Response.Cache.SetExpires(System.DateTime.Now.AddSeconds(60));
// Set OutputCache VaryByParams.
Response.Cache.VaryByParams["None"] = true;
// Set OutputCache Location.
Response.Cache.SetCacheability(HttpCacheability.Public);
}

The preceding code is equivalent to the following OutputCache directive:
@ OutputCache Duration="5" VaryByParam="None" Location="Any"
27. What is @OutputCache directive’s Location attribute and the HttpCachePolicy object’s SetCacheability property used for?
The @OutputCache directive’s Location attribute and the HttpCachePolicy object’s SetCacheability property determine where Microsoft ASP.NET stores cached responses. By default, ASP.NET caches responses at any available location that accepts cache items - the client, proxy servers, or the host server. In practice, those locations might or might not allow caching, so you can think of the Location/SetCacheabilitysetting as more of a request than a command.
28.  What is HttpCachePolicy object’s SetAllowResponseInBrowserHistory method used for?
You can override the cache location settings using the HttpCachePolicy object’s SetAllowResponseInBrowserHistory method. Setting that method to True allows the response to be stored in the client’s history folder even if the location setting is None or Server.
 29.Which object can be used to store frequently used items in the server’s memory for quick retrieval?
Cache object can be used to store frequently used items in the server’s memory for quick retrieval.
30. Is the cache object available for all web forms with in a web application?
Yes, the Cache object is global, that is, data stored in the Cache object is available anywhere within a Web application. In this way, the Cache object is very similar to the intrinsic Application object.
31. What are the 3 different ways to store data in the Cache object?
Use assignment.
Assigning a value to an unused key in the Cache object automatically creates that key and assigns the value to that key. 
Assigning a value to a key that already exists replaces the cached value with the assigned value.
Use the Insert method.
The Insert method uses parameters rather than assignment to create or change cached data. Insert optionally accepts parameters to establish dependencies and set expiration policy.
Use the Add method.
The Add method is similar to Insert; however, it requires all parameters and returns an object reference to the cached data.

For example, the following Cache statements all add the same item to the cache:

using System.Web.Caching;
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
Cache["NewItem"] = "Some string data";
Cache.Add("NewItem", "Some string data", null, Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1), CacheItemPriority.Default, null);
Cache.Insert("NewItem", "Some string data");
}
}
32.  What are absoluteExpiration and slidingExpiration parmeters of the Insert and Add methods?absoluteExpiration
A DateTime object that identifies when the data should be removed from the cache. If you’re using sliding expiration, specify Cache.NoAbsoluteExpiration for this parameter.
slidingExpiration
A TimeSpan object that identifies how long the data should remain in the cache after the data was last accessed. If you’re using absolute expiration, specify Cache.NoSlidingExpiration for this parameter.
33. Which delegate can be used to notify the application when items are removed from the cache?onRemoveCallback is used to notify the application when items are removed from the cache.
 34. How do you retrieve the value of a cache item stored in the servers memory?
You can retrieve the value of a cache item stored in the servers memory through the item’s key, just as you do with the Application and Session objects. Because cached items might be removed from memory, you should always check for their existence before attempting to retrieve their value, as shown in the following code:
private void Button1_Click(object sender, EventArgs e)
{
if (Cache["ChachedItem"] == null)
{
Lable1.Text = "Cached Item not found.";
}
else
{
Lable1.Text = Cache["ChachedItem"].ToString();
}
}
35.Which method can be used to remove data from the cache?
Cache object’s Remove method can be used to remove data from the cache as shown in the following code example / sample.

private void RemoveButton_Click(object sender, System.EventArgs e)
{
Cache.Remove("CachedItem");
}
36.How do you control how long data is cached?
The Cache object’s Add and Insert method parameters allow you to control how long an item is stored in the server’s memory. In practice, these parameter settings provide only indirect control of how long data remains in memory. If your server runs low on available memory, ASP.NET recovers as much memory as possible from expired cache items. If that’s not enough, ASP.NET will unload unexpired items from the cache based on their priority and when they were last accessed.
 37.What is CacheItemPriority enumeration used for?
CacheItemPriority enumeration is used to set the relative importance of cached items. CacheItemPriority.NotRemoveable has the highest priority and CacheItemPriority.Low has the lowest priority.
38.Which is the only "event” provided by Cache object?
CacheItemRemoved "event” is the only "event” provided by Cache object.
39.How do you update the Cache object when data changes?
Items stored in the cache are often copies of data that is stored and maintained elsewhere, such as records in a database. Use the Add and Insert methods’ dependency parameter to establish a relationship between a cached data item and an external source, such as a file, a folder, or a group of files.

The dependency parameter accepts a CacheDependency object, which in turn identifies the file, folder, or set of files to watch for changes. ASP.NET checks the time stamp of the items in the CacheDependency object, if one of those time stamps is later than the DateTime entered for the cached item, ASP.NET unloads that item from the cache.
40.What is fragment caching?
 Caching parts of web form is called as fragment caching. Sometimes you want to cache only part of a Web form response. For instance, a Web form might contain many pieces of variable information plus a single large table that almost never changes. In this case, you might place that table in a Web user control and store the response for that control in cache. This technique is called fragment caching.
41.What are the steps to follow to cache parts of web form?
To cache part of a Web form, follow these steps:
1. Place the controls and content that you want to cache in a Web user control.
2. Set the caching attributes for that Web user control.
3. Create an instance of the Web user control on the Web form.
42.What is PartialCaching attribute used for?
You can include the PartialCaching attribute in the control’s class declaration to enable fragment caching.
43.What are the OutputCache directive attributes that apply only to user controls?
Shared
Cache a single response from a user control for use on multiple Web forms. By default, ASP.NET caches a separate response for each Web form that uses a cached user control. This attribute is only available in the .NET Framework version 1.1 or later.

VaryByControl
Cache multiple responses for a single user control based on the value of one or more controls contained in the user control. Can you cache multiple versions of a user control?Yes, You can cache multiple versions of a user control based on the value of controls contained in a user control (VaryByControl) or based on a custom string (VaryByCustom).
44.When caching is set at both the Web form and user control levels, How does the cache settings interact?
The cache location is determined by the Web form setting. Location settings on a user control have no affect. If the Web form’s cache duration is longer than the user control’s, both the Web form response and the user control response will expire using the Web form setting.
45.What is the difference between page-level caching and fragment caching?
In the page-level caching, an entire Web page is cached; whereas, in the fragment caching, a part of the Web page, such as a user control added to the Web page, is cached.




No comments:

Post a Comment