vijay

welcome Netizen

Share Your Knowledge.It is a way to achieve immortality

Sunday, July 21, 2013

ASP.Net Interview Questions Part4



Caching-


What is caching?
High-performance Web applications should be designed with caching in mind. Caching is the technique of storing frequently used items in memory so that they can be accessed more quickly. Caching is important to Web applications because each time a Web form is requested, the host server must process the Web form’s HTML and run Web form code to create a response. By caching the response, all that work is bypassed. Instead, the request is served from the reponse already stored in memory.

Caching an item incurs considerable overhead, so it’s important to choose the items to cache wisely. A Web form is a good candidate for caching if it is frequently used and does not contain data that frequently changes. By storing a Web form in memory, you are effectively freezing that form’s server-side content so that changes to that content do not appear until the cache is refreshed.

What directive is used to cache a web form?
The @OutputCache page directive is used to cache a Web form in the server’s memory.

What is the use of duration attribute of @OutputCache page directive?
The @OutputCache directive’s Duration attribute controls how long the page is cached. For example if you set the duration attribute to 60 seconds, the Web form is cached for 60 seconds.

The first time any user requests the Web form, the server loads the response in memory and retains that response for 60 seconds. Any subsequent requests during that time receive the cached response.

After the cache duration has expired, the next request for the Web form generates a new response, which is then cached for another 60 seconds. Thus the server processes the Web form once every 60 seconds at most.

What are the 2 required attributes of the @OutputCache directive?
The @OutputCache directive has two required attributes:
1. Duration
2. VaryByParam. 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.

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.

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"

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/SetCacheability setting as more of a request than a command.

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.

Which object can 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.

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.

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"); 
}
}

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.

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.

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(); 
}
}

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");
}

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.

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.

Which is the only "event” provided by Cache object?
CacheItemRemoved "event” is the only "event” provided by Cache object. 

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.

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.

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.

What is PartialCaching attribute used for?
You can include the PartialCaching attribute in the control’s class declaration to enablefragment caching.

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).

If a user control is read from the cache, can you access its members from code?
No, In general, cached controls are used to present data such as queries from a database, rather than as interactive components. However, if you do need to access a cached control from code, you must first check that the control exists. If the control is read from the cache, you can’t access its members from code. Control members are available only when the control is not read from the cache, such as when the control is first instantiated and when it is reloaded after its cache duration has expired.

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.

Cookies-

What are Cookies in ASP.NET? 
Cookies are small pieces of information stored on the client computer.Use cookies to store small amounts of information on the client’s machine. Web sites often use cookies to store user preferences or other information that is client-specific. Because cookies can be refused, it is important to check whether the browser allows them before you try to create them.They are limited to storing only character data and they are limited to 4K in size.

What are different types of Cookies?
Session Cookies
Persistent Cookies

What are Session Cookies? 
Session cookies are stored in-memory during the client browser session. When the browser is closed the session cookies are lost.

How can you create Session Cookies?
You can create session cookies by calling the Add method of the Cookies collection on the Response object. The Cookies collection contains individual cookie objects of type HttpCookie.

//Code to create a UserName cookie containing the name David.
HttpCookie CookieObject = new HttpCookie("UserName", "David");
Response.Cookies.Add(CookieObject); 


//Code to read the Cookie created above
Request.Cookies["UserName"].Value;

What is the difference between Session Cookies and Persistent Cookies?
Persistent Cookies are same as Session Cookies except that, persistent cookies have an expiration date. The expiration date indicates to the browser that it should write the cookie to the client's hard drive. Keep in mind that because a user can delete cookies from their machine that there is no guarantee that a cookie you "drop" on a user machine will be there the next time they visit your site.

What are Persistent Cookies used for? 
Persistent cookies are generally used to store information that identifies a returning user to a Web site. Typical information found in Persistent Cookies includes user names or user IDs.

How do you create a Persistent Cookie?
You create a persistent cookie the same way as session cookies except that you set the Expires property to a Date in the future which will store the Cookie to the client computer harddrive.

//Code to create a UserName Persistent Cookie that lives for 10 days
HttpCookie CookieObject = new HttpCookie("UserName", "David");
CookieObject.Expires = DateTime.Now.AddDays(10);
Response.Cookies.Add(CookieObject); 


//Code to read the Cookie created above
Request.Cookies["UserName"].Value; 

What is Cookie Dictionary? 
A cookie dictionary is a single cookie object that stores multiple pieces of information. You use the Values property to access and assign new values to the cookie dictionary.

Give an example using Cookie Dictionary?
//Code to create a Cookie Dictionary
HttpCookie CookieObject = new HttpCookie("UserPreference"); 

//Use the Values property to assign new values to the cookie dictionary
CookieObject.Values.Add("UserName", "David");
CookieObject.Values.Add("Country", "USA");
CookieObject.Values.Add("PreviousVisit", DateTime.Now.ToString());
CookieObject.Expires = DateTime.MaxValue; 


//Add the Cookie to the client machine using the Response object
Response.Cookies.Add(CookieObject);

//Code to read the Cookie created above
HttpCookie ObjectCookie = Request.Cookies["UserPreference"];
string UserName = ObjectCookie.Values["UserName"];
string Country = ObjectCookie.Values["Country"];
string PreviousVisit = ObjectCookie.Values["PreviousVisit"];

What are the advantages of Using Cookies? 
1. Cookies do not require any server resources since they are stored on the client.
2. Cookies are easy to implement.
3. You can configure cookies to expire when the browser session ends (session cookies) or they can exist for a specified length of time on the client computer (persistent cookies).

What are the disadvantages of Using Cookies?
1.
 Users can delete a cookies.
2. Users browser can refuse cookies,so your code has to anticipate that possibility.
3. Cookies exist as plain text on the client machine and they may pose a possible security risk as anyone can open and tamper with cookies.

How do you create a Cookie that never expires?
To create a Cookie that never expires set the Expires property of the Cookie object to DateTime.MaxValue.

Are Cookies secure? 
No, Cookies are not secure. You must pay attention to the type of data you store in cookies.
1. Cookies are not designed to store critical information so storing passwords in a cookie is a bad idea.
2. Keep the lifetime of a cookie as short as practically possible.
3. Encrypt cookie data to help protect the values stored in the cookie.

0 comments:

Post a Comment