Table of contents
Introduction
In this section, we will touch base on one of the important concepts in .NET caching.
Previous parts of my interview questions series for architects:
Happy job hunting......
(B) What is Application object?
The Application
object can be used in situations where we want data to be shared across users globally.
(I) What are the differences between the Cache object and the 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.
(I) How to access a 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.
(A) What are the dependencies in Cache and the types of dependencies?
When you add an item to the cache, you can define the dependency relationships that can force that item to be removed from the cache under specific activities of dependencies. For example, if the cache object is dependent on a file and when the file data changes, you want the cache object to be updated. Following are the supported dependencies:
- 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 a predefined time.
- Key dependency: Allows you to invalidate a specific cache item when another cached item changes.
(A) Can you show a simple code showing file dependency in cache?
Partial Class Default_aspx
Public Sub display Announcement()
Dim announcement As String
If Cache("announcement") Is Nothing Then
Dim file As New System.IO.StreamReader(Server.MapPath("announcement.txt"))
announcement = file.ReadToEnd
file. Close()
Dim depends As New System.Web.Caching.CacheDependency (Server.MapPath("announcement.txt"))
Cache.Insert("announcement", announcement, depends)
End If
Response.Write(CType(Cache("announcement"), String))
End Sub
Private Sub Page_Init(ByVal sender As Object, _
By Val e As System.EventArgs) Handles Me. nit
display Announcement()
End Sub
End Class
The above given method display Announcement()
displays the banner text from the Announcement.txt file which is in the application path of the web directory. The method first checks whether the cache object is Nothing
, if so, it moves further to load the cache data from the file. Whenever the file data changes, the cache object is removed and set to Nothing
.
(A) What is cache callback in cache?
The cache object is dependent on its dependencies, for example, file based, time based, etc...Cache items remove the object when the cache dependencies change. ASP.NET provides the capability to execute a callback method when that item is removed from the cache.
(A) What is scavenging?
When the 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 an item to cache. By setting the cache item priority controls, the items scavenging are removed according to priority.
(B) What are the different types of caching using the Cache object of ASP.NET?
You can use two types of output caching to cache information that is to be transmitted to and displayed in a web browser:
Page output caching adds the response of a page to the cache object. Later when the page is requested, the page is displayed from the cache rather than creating the page object and displaying it. Page output caching is good if the site is fairly static.
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.
- Page Output Caching
- Page Fragment Caching
(B) How can you cache different versions of the same page using the ASP.NET Cache object?
Output cache functionality is achieved using the OutputCache
attribute in the ASP.NET page header. Below is the syntax:
<%@ Output Cache Duration="20" Location="Server"
Vary By Param="state" Vary By Custom="minor version"
Vary By Header="Accept-Language"%>
- Vary By Param - Caches different versions depending on input parameters sent through HTTP POST/GET.
- Vary By Header - Caches different versions depending on the contents of the page header.
- Vary By Custom - Lets you customize the way the cache handles page variations by declaring the attribute and overriding the Get Vary By Custom string handler.
- Vary By Control - Caches different versions of a user control based on the value of properties of ASP objects in the control.
(A) How can we 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 need to be dynamically created for each user request, this is the best method when compared to page caching. You can wrap a Web Form user control and cache the control so that these portions of the page do not need to be recreated each time.
(B) Can you compare ASP.NET sessions with classic ASP?
ASP.NET session caches per user session states. It basically uses the HttpSessionState
class. Following are the limitations in classic ASP sessions:
- ASP session state is dependent on the IIS process very heavily. So if IIS restarts, ASP session variables are recycled. ASP.NET session can be independent of the hosting environment thus the ASP.NET session can be maintained even if IIS reboots.
- ASP session state has no inherent solution to work with Web Farms. ASP.NET session can be stored in state server and SQL Server which can support multiple servers.
- ASP session only functions when the browser supports cookies. ASP.NET session can be used with browser-side cookies or independent of it.
(B) Which are the various modes of storing an ASP.NET session?
- In Proc: In this mode, session state is stored in the memory space of the Aspnet_wp.exe process. This is the default setting. If IIS reboots or the web application restarts, then session state is lost.
- State Server: In this mode, session state is serialized and stored in a separate process (Aspnet_state.exe); therefore the state can be stored in a separate computer (a state server).
- SQL Server: In this mode, session state is serialized and stored in a SQL Server database.
Session state can be specified in <session State> element of application configuration file. Using State Server and SQL SERVER session state can be shared across web farms but note this comes at speed cost as ASP. NET needs to serialize and desterilize data over network repeatedly.
(A) Is Session End event supported in all session modes?
The Session End event occurs only in “Inproc” mode. State Server and SQL Server modes do not have a Session End event.
(A) What are the steps to configure State Server mode?
Following are the things to remember so that State Server mode works properly:
- State Server mode session data is stored in a different process so you must ensure that your objects are serializable.
<machine Key>
elements in Web.config should be identical across all servers. This ensures that the encryption format is the same across all computers. - IIS meta base (\LM\W3SVC\2) must be identical across all servers in that farm.
(A) What are the steps to configure SQL Server mode?
Following are the things to remember so that SQL Server mode works properly:
- SQL Server mode session data is stored in a different process so you must ensure that your objects are serializable.
- IIS metabase (\LM\W3SVC\2) must be identical across all servers in that farm.
- By default, Session objects are stored in “TempDB”; you can configure to store outside “TempDB” by running the Microsoft provided SQL script.
Note: “TempDB” database is re-created after SQL SERVER computer reboot.If you want to maintain session state with every reboot best is to run SQL Script and store session objects outside “TempDB” database.
(A) Where do you specify session state mode in ASP.NET?
<sessionState mode="SQLServer"
stateConnectionString="tcpip=192.168.1.1:42424"
sqlConnectionString="data source=192.168.1.1; Integrated Security=SSPI"
cookieless="false"
timeout="20"
/>
Above is sample session state mode specified for SQL SERVER.
(B) What are the other ways you can maintain state?
Other than session variables, you can use the following techniques to store state:
- Hidden fields
- ViewState
- Hidden frames
- Cookies
- Querystrings
(B) What are the benefits and limitations of using hidden fields?
Following are the benefits of using hidden fields:
- They are simple to implement.
- As data is cached on the client side, they work with Web Farms.
- All browsers support hidden fields.
- No server resources are required.
Following are the limitations of hidden fields:
- They can be tampered, creating a security hole.
- Page performance decreases if you store large data, as the data is stored in the page itself.
- Hidden fields do not support rich structures as HTML hidden fields are only single valued. Then you have to workaround with delimiters etc., to handle complex structures.
Below is how you will actually implement a hidden field in a project:
<input id="Hidden Value" type="hidden"
value="Initial Value" run at="server" NAME="Hidden Value">
(B) What is ViewState?
ViewState is a built-in structure for automatically retaining values amongst the multiple requests for the same page. The viewstate is internally maintained as a hidden field on the page but is hashed, providing greater security than developer-implemented hidden fields do.
(A) Does the performance for ViewState vary according to User Controls?
Performance of viewstate varies depending on the type of server control to which it is applied. Label
, TextBox
, CheckBox
, RadioButton
, and HyperLink
are server controls that perform well with ViewState. DropDownList
, ListBox
, DataGrid
, and DataList
suffer from poor performance because of their size and the large amounts of data making roundtrips to the server.
(B) What are the benefits and limitations of using ViewState for state management?
Following are the benefits of using ViewState:
- No server resources are required because the state is in a structure in the page code.
- Simplicity.
- States are retained automatically.
- The values in viewstate are hashed, compressed, and encoded, thus representing a higher state of security than hidden fields.
- Viewstate is good for caching data in web farm configurations because the data is cached on the client.
Following are the limitations of using ViewState:
- Page loading and posting performance decreases when large values are stored because viewstate is stored in the page.
- Although viewstate stores data in hashed format, it can still be tampered because it is stored in a hidden field in the page.
The information in the hidden field can also be seen if the page output source is viewed directly, creating a potential security risk. Below is sample code for storing values in viewstate:
this.View State["Enter Time"] = DateTime.Now.ToString();
(B) How can you use hidden frames to cache client data?
This technique is implemented by creating a hidden frame in a page which will contain your data to be cached.
<FRAMESET cols="100%,*,*">
<FRAMESET rows="100%">
<FRAME src="data_of_frame1.html"></FRAMESET>
<FRAME src="data_of_hidden_frame. html">
<FRAME src="data_of_hidden_frame.html"
frame border="0" no resize scrolling="yes">
</FRAMESET>
Above is a sample of hidden frames where the first frame “data_of_frame1.html” is visible and the remaining frames are hidden by giving whole col section to first frame. 100% is allocated to first frame and remaining frames thus remain hidden.
(I) What are the benefits and limitations of using hidden frames?
Following are the benefits of using hidden frames:
- You can cache more than one data field.
- The ability to cache and access data items stored in different hidden forms.
- The ability to access JS crept ® variable values stored in different frames if they come from the same site.
The limitations of using hidden frames are:
- Hidden frames are not supported in all browsers.
- Hidden frames data can be tampered thus creating security holes.
(I) What are the benefits and limitations of using Cookies?
Following are the benefits of using cookies for state management:
- No server resources are required as they are stored in the client.
- They are lightweight and simple to use.
Following are the limitations of using cookies:
- Most browsers place a 4096-byte limit on the size of a cookie, although support for 8192-byte cookies is becoming more common in the new browser and client-device versions available today.
- Some users disable their browser or client device’s ability to receive cookies, thereby limiting the use of cookies.
- Cookies can be tampered thus creating a security hole.
- Cookies can expire thus leading to inconsistency.
Below is a sample code for implementing cookies:
Request.Cookies.Add(New Http Cookie ("name", "user1"))
(I) What is QueryString and what are benefits and limitations of using QueryStrings?
A querystring is information sent to the server appended to the end of a page URL.
Following are the benefits of using querystrings for state management:
- No server resources are required. The querystring contains the HTTP requests for a specific URL.
- All browsers support querystrings.
Following are the limitations of querystrings:
- Querystring data is directly visible to the user thus leading to security problems.
- Most browsers and client devices impose a 255-character limit on URL length.
Below is a sample “Login” query string passed in a URL: http://www.querystring.com/login.asp?login=testing. This querystring data can then be requested by using Request.QueryString(“login”)
.
(I) What is Absolute and Sliding expiration?
Absolute expiration allows you to specify the duration of the cache, starting from the time the cache is activated. The following example shows that the cache has a cache dependency specified, as well as an expiration time of one minute.
Cache.Insert("announcement", announcement, depends, _
DateTime.Now.AddMinutes(1), Nothing)
Sliding expiration specifies that the cache will expire if a request is not made within a specified duration. Sliding expiration policy is useful whenever you have a large number of items that need to be cached, because this policy enables you to keep only the most frequently accessed items in memory. For example, the following code specifies that the cache will have a sliding duration of one minute. If a request is made 59 seconds after the cache is accessed, the validity of the cache would be reset to another minute:
Cache.Insert("announcement", announcement, depends, _
DateTime.MaxValue, _TimeSpan.FromMinutes(1))
(I) What is cross page posting?
Note: This is a new feature in ASP.NET 2.0.
By default, button controls in ASP.NET pages postback to the same page that contains the button, where you can write an event handler for the post. In most cases, this is the desired behavior, but occasionally you will also want to be able to post to another page in your application. The Server.Transfer
method can be used to move between pages, however the URL does not change. Instead, the cross page-posting feature in ASP.NET 2.0 allows you to fire a normal postback to a different page in the application. In the target page, you can then access the values of server controls in the source page that initiated the postback. To use cross page posting, you can set the PostBackUrl
property of a Button
, LinkButton
, or ImageButton
control, which specifies the target page. In the target page, you can then access the PreviousPage
property to retrieve values from the source page. By default, the PreviousPage
property is of type Page
, so you must access controls using the FindControl
method. You can also enable strongly-typed access to the source page by setting the @Previous Page Type
directive in the target page to the virtual path or type name of the source page. Here is a systematic guide for implementing cross-page postback using controls that implement the IButtonControl
interface.
- Create a Web Form and insert a
Button
control on it using the VS.NET designer. - Set the button's
PostBackUrl
property to the Web Form you want to post back.
For instance, in this case, it is "nextpage.aspx":
<asp: Button ID="Button1" run at="server"
PostBackUrl="~/nextpage.aspx" Text="Post to next page" />
When the PostBackUrl
property of the IButtonControl
is set, the ASP.NET framework binds the corresponding HTML element to a new JavaScript function named Web Form _Do Post Back With Options
. The corresponding HTML rendered by ASP.NET 2.0 will look like this:
<input type="submit" name="Button1" value="Post to Page 2"
on click="java script: Web Form_ Do Post Back With Options (new Web Form_ Post Back Options("Button1",
",false","Page2.aspx", false, false))" id="Button1" />
(I) How do we access the viewstate value of a page in the next page?
Viewstate is page specific; it contains information about controls embedded on the particular page. ASP.NET 2.0 resolves this by embedding a hidden input field name, __POST BACK
. This field is embedded only when there is an IButtonControl
on the page and its PostBackUrl
property is set to a non-null value. This field contains the viewstate information of the poster page. To access the viewstate of the poster page, you can use the new PreviousPage
property of the page:
Page poster = this.Previous Page;
Then you can find any control from the previous page and read its state:
Label poster Label = poster. find Control ("my Label");
string lbl = poster Label. Text;
This cross-page postback feature also solves the problem of posting a Form to multiple pages, because each control, in theory, can point to a different postback URL.
(I) Can we post and access view state in another application?
You can postback to any page and pages in another application too. However, if you are posting pages to another application, the PreviousPage
property will return null
. This is a significant restriction, as it means that if you want to use the view state, you are confined to, for example, posting to pages in the same virtual directory. Even so, this is a highly acceptable addition to the functionality of ASP.NET.
(I) 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 to a database table, any changes in the database table will invalidate the cached data object which can be a dataset or a data source.
For Further Reading do watch the below Interview preparation videos and step by step video series.