Thursday, May 1, 2008

DOTNET FAQ-6

5. Caching Concepts

(B) What is an application object ?
Application object ca be n used in situation where we want data to be shared across users
globally.
(I)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.
(I)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.
(A)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. Caching Concepts
179
(P)Can you show a simple code showing file dependency in cache ?
Partial Class Default_aspx
Public Sub displayAnnouncement()
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, ByVal e As
System.EventArgs) Handles Me.Init
displayAnnouncement()
End Sub
End Class
Note :- Above source code can be obtained from CD in “CacheSample”
folder.”Announcement.txt” is in the same folder which you can play around to see the
results.
Above given method displayAnnouncement() displays banner text from Announcement.txt
file which is lying in application path of the web directory. Above method first checks
whether the Cache object is nothing, if the cache object is nothing then 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 ?
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.
180
(A) 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.
(B) What are different types of caching using 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
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.
√ 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.
(B) 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.
181
√ 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.
(A) 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.
(B) What are ASP.NET session and compare ASP.NET session with
classic ASP session variables?
ASP.NET session caches per user session state. It basically uses “HttpSessionState” class.
Following are the limitations in classic ASP sessions :-
√ ASP session state is dependent on IIS process very heavily. So if IIS restarts
ASP session variables are also recycled.ASP.NET session can be independent
of the hosting environment thus ASP.NET session can 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 server.
√ ASP session only functions when browser supports cookies.ASP.NET session
can be used with browser side cookies or independent of it.
(B) Which various modes of storing ASP.NET session ?
√ InProc:- In this mode Session state is stored in the memory space of the
Aspnet_wp.exe process. This is the default setting. If the IIS reboots or web
application restarts then session state is lost.
182
√ StateServer:-In this mode Session state is serialized and stored in a separate
process (Aspnet_state.exe); therefore, the state can be stored on 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 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 deserialize data over
network again and again.
(A) Is Session_End event supported in all session modes ?
Session_End event occurs only in “Inproc mode”.”State Server” and “SQL SERVER”
do not have Session_End event.
(A) What are the precautions you will take in order that StateServer Mode
work properly ?
Following are the things to remember so that StateServer Mode works properly :-
√ StateServer mode session data is stored in a different process so you must
ensure that your objects are serializable.
elements in Web.config should be identical across all
servers.So this ensures that encryption format is same across all computers.
√ IIS metabase (\LM\W3SVC\2) must be identical across all servers in that
farm.
(A) What are the precautions you will take in order that SQLSERVER
Mode work properly ?
Following are the things to remember so that SQLSERVER Mode works properly :-
√ SQLSERVER 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.
183
√ By default Session objects are stored in “Tempdb”, you can configure it store
outside “TempDB” by running 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 ?
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 technique to store state :
√ Hidden fields
√ View state
√ Hidden frames
√ Cookies
√ Query strings
(B) What are benefits and Limitation of using Hidden fields ?
Following are the benefits of using Hidden fields :-
√ They are simple to implement.
√ As data is cached on client side they work with Web Farms.
√ All browsers support hidden field.
√ No server resources are required.
Following are limitations of Hidden field :-
184
√ They can be tampered creating a security hole.
√ Page performance decreases if you store large data, as the data are stored in
pages itself.
√ Hidden fields do not support rich structures as HTML hidden fields are only
single valued. Then you have to work around with delimiters etc to handle
complex structures.
Below is how you will actually implement hidden field in a project
runat="server"NAME="HiddenValue">
(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 benefits and Limitation of using Viewstate for state
management?
Following are the benefits of using Viewstate :-
√ No server resources are required because state is in a structure in
the page code.
√ Simplicity.
√ States are retained automatically.
185
√ The values in view state are hashed, compressed, and encoded, thus representing
a higher state of security than hidden fields.
√ View state is good for caching data in Web frame configurations because the
data is cached on the client.
Following are limitation of using Viewstate:-
√ Page loading and posting performance decreases when large values are
stored because view state is stored in the page.
√ Although view state stores data in a hashed format, it can still be tampered
because it is stored in a hidden field on 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 of storing values in view state.
this.ViewState["EnterTime"] = DateTime.Now.ToString();
(B) How can you use Hidden frames to cache client data ?
This technique is implemented by creating a Hidden frame in page which will contain
your data to be cached.

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. See allocation
where 100 % is allocated to first frame and remaining frames thus remain hidden.
(I) What are 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 JScript® 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 on all browsers.
√ Hidden frames data and be tampered thus creating security hole.
(I) What are benefits and limitations of using Cookies?
Following are benefits of using cookies for state management :-
√ No server resources are required as they are stored in client.
√ They are light weight and simple to use
Following are limitation 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 and thus creating a security hole.
√ Cookies can expire thus leading to inconsistency.
Below is sample code of implementing cookies
Request.Cookies.Add(New HttpCookie(“name”, “user1”))
(I) What is Query String and What are benefits and limitations of using
Query Strings?
A query string is information sent to the server appended to the end of a page URL.
Following are the benefits of using query string for state management:-
√ No server resources are required. The query string containing in the HTTP
requests for a specific URL.
√ All browsers support query strings.
Following are limitations of query string :-
√ Query string data is directly visible to 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 URL http://www.querystring.com/
login.asp?login=testing. This query string data can then be requested later 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?
188
Note :- This is a new feature in ASP.NET 2.0
By default, button controls in ASP.NET pages post back 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 occasionaly 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 doesn't change. Instead, the cross page posting feature in ASP.NET 2.0 allows
you to fire a normal post back 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 post
back.
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
@PreviousPageType directive in the target page to the virtual path or Type name of the
source page.
Here is a step-by-step guide for implementing the cross-page post back 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"
PostBackUrl="~/nextpage.aspx" Text="Post to nextpage" />
When the PostBackUrl property of the IButtonControl is set, the ASP.NET framework
binds the corresponding HTML element to new JavaScript function named
WebForm_DoPostBackWithOptions. The corresponding HTML rendered by the ASP.NET
2.0 will look like this:

189
How do we access viewstate value of this page in the next page ?
View state 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,
__POSTBACK . 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 view
state information of the poster page. To access the view state of the poster page, you can
use the new PreviousPage property of the page:
Page poster = this.PreviousPage;
Then you can find any control from the previous page and read its state:
Label posterLabel = poster.findControl("myLabel");
string lbl = posterLabel.Text;
This cross-page post back feature also solves the problem of posting a Form to multiple
pages, because each control, in theory, can point to different post back URL.
Can we post and access view state in another application?
You can post back to any page and pages in another application, too. But 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,
for example, to posting to pages in the same virtual directory. Even so, this is a highly
acceptable addition to the functionality of ASP.NET.
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.
How do we enable SQL Cache Dependency in ASP.NET 2.0?
Below are the broader steps to enable a SQL Cache Dependency:-
190
• 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
Enable notifications for the database.
Before you can use SQL Server cache invalidation, you need to enable notifications for
the database. This task is performed with the aspnet_regsql.exe command-line utility,
which is located in the c:\[WinDir]\Microsoft.NET\Framework\[Version] directory.
aspnet_regsql -ed -E -d Northwind
-ed :- command-line switch
-E: - Use trusted connection
-S: - Specify server name it other than the current computer you are working on
-d: - Database Name
So now let’s try to understand what happens in the database because of
“aspnet_regsql.exe”. After we execute the “aspnet_regsql -ed -E -d Northwind” command
you will see one new table and four new stored procedures created.
Figure 5.1 : - SQL Cache table created for notification
Essentially, when a change takes place, a record is written in this table. The SQL Server
polling queries this table for changes.
191
Figure 5.2 : - New stored procedures created
Just to make brief run of what the stored procedures do.
“AspNet_SqlCacheRegisterTableStoredProcedure” :- This stored procedure sets a table
to support notifications. This process works by adding a notification trigger to the table,
which will fire when any row is inserted, deleted, or updated.
“AspNet_SqlCacheUnRegisterTableStoredProcedure”:- This stored procedure takes a
registered table and removes the notification trigger so that notifications won't be generated.
“AspNet_SqlCacheUpdateChangeIdStoredProcedure”:- The notification trigger calls this
stored procedure to update the AspNet_SqlCacheTablesForChangeNotification table,
thereby indicating that the table has changed.
AspNet_SqlCacheQueryRegisteredTablesStoredProcedure :- This extracts just the table
names from the AspNet_SqlCacheTablesForChangeNotification table. It’s used to get a
quick look at all the registered tables.
192
AspNet_SqlCachePollingStoredProcedure :- This will get the list of changes from the
AspNet_SqlCacheTablesForChangeNotification table. It is used to perform polling.
Enabling notification for individual tables
Once the necessary stored procedure and tables are created then we have to notify saying
which table needs to be enabled for notifications.
That can be achieved by two ways:-
√ aspnet_regsql -et -E -d Northwind -t Products
√ Exec spNet_SqlCacheRegisterTableStoredProcedure 'TableName'
Registering tables for notification internally creates triggerfor the tables. For instance for
a “products” table the following trigger is created. So any modifications done to the
“Products” table will update the “AspNet_SqlCacheNotification’ table.
CREATE TRIGGER
dbo.[Products_AspNet_SqlCacheNotification_Trigger] ON
[Products]
FOR INSERT, UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON
EXEC dbo.AspNet_SqlCacheUpdateChangeIdStoredProcedure
N'Products‘
END
“AspNet_SqlCacheTablesForChangeNotification” contains a single record for every table
you're monitoring. When you make a change in the table (such as inserting, deleting or
updating a record), the change Id column is incremented by 1.ASP.NET queries this table
repeatedly keeps track of the most recent changed values for every table. When this
value changes in a subsequent read, ASP.NET knows that the table has changed.
193
Figure 5.3 : - Entries in the Cache notification table
Enable ASP.NET polling using “web.config” file
Now that all our database side is configured in order to get the SQL Cache working in the
ASP.NET side we need to do some configuration in the web.config file.
We need to set two attributes in the “web.config” file:-
√ Set “Enabled” attribute to true to set the caching on.
√ Set the poll time attribute to the number of milliseconds between each poll
Below is the snapshot of the web.config file.
Figure 5.4 :- Web.config file modifications for SQL cache
194
Finally use the Cache dependency object in your ASP.NET code
Now comes the final step to use our cache dependency with programmatic data caching,
a data source control, and output caching.
For programmatic data caching, we need to create a new SqlCacheDependency and supply
that to the Cache.Insert() method. In the SqlCacheDependency constructor, you supply
two strings. The first is the name of the database you defined in the element in the section
of the web.config file e.g: Northwind. The second is the name of the linked table e.g:
Products.
private static void CacheProductsList(List products)
{SqlCacheDependency sqlDependency = new SqlCacheDependency("Northwind",
"Products");
HttpContext.Current.Cache.Insert("ProductsList", products, sqlDependency,
DateTime.Now.AddDays(1), Cache.NoSlidingExpiration);}
private static List GetCachedProductList()
{return HttpContext.Current.Cache["ProductsList"] as List;}
ClsProductItem is business class, and here we are trying to cache a list of ClsProductItem
instead of DataSet or DataTable.
The following method is used by an ObjectDataSource Control to retrieve List of Products
public static List GetProductsList(int catId, string sortBy)
{
//Try to Get Products List from the Cache
List products = GetCachedProductList();
if (products == null)
{
//Products List not in the cache, so query the Database layer
ClsProductsDB db = new ClsProductsDB(_connectionString);
DbDataReader reader = null;
products = new List(80);
195
if (catId > 0)
{
//Return Product List from the Data Layer
reader = db.GetProductsList(catId);
}
else
{
//Return Product List from the Data Layer
reader = db.GetProductsList();
}
//Create List of Products -List if ClsProductItemproducts
= BuildProductsList(reader);
reader.Close();
//Add entry to products list in the Cache
CacheProductsList(products);
}
products.Sort(new ClsProductItemComparer(sortBy));
if (sortBy.Contains("DESC")) products.Reverse();
return products;
}
196
To perform the same trick with output caching, you simply need to set the SqlDependency
property with the database dependency name and the table name, separated by a colon:
<%@ OutputCache Duration="600" SqlDependency="Northwind:Products"
VaryByParam="none" %>
The same technique works with the SqlDataSource and ObjectDataSource controls:
SqlCacheDependency="Northwind:Products" ... />
Note :- ObjectDataSource doesn't support built in caching for Custom types such as the one
in our example. It only supports this feature for DataSets and DataTables.
Just to make a sample check run the SQL Server profiler and see that does the SQL
actually hit the database after the first run.
What is Post Cache substitution?
Post cache substitution is used when we want to cache the whole page but also need
some dynamic region inside that cached page. Some examples like QuoteoftheDay,
RandomPhotos, and AdRotator etc. are examples where we can implement Post Cache
Substitution.
Post-cache substitution can be achieved by two means:
√ Call the new Response.WriteSubstitution method, passing it a reference to the desired
substitution method callback.
√ Add a control to the page at the desired location, and set its
methodName attribute to the name of the callback method.
197
Figure 5.5 : - “Writesubstitution” in action
You can see we have a static function here “GetDateToString()”. We pass the response
substitution callback to the “WriteSubstitution” method. So now when ASP.NET page
framework retrieves the cached page, it automatically triggers your callback method to
get the dynamic content. It then inserts your content into the cached HTML of the page.
Even if your page hasn't been cached yet (for example, it's being rendered for the first
time), ASP.NET still calls your callback in the same way to get the dynamic content. So
you create a method that generates some dynamic content, and by doing so you guarantee
that your method is always called, and it’s content is never cached.
Ok the above example was by using “WriteSubstitution” now lets try to see how we can
do by using “” control. You can get the “” control
from the editor toolbox.
198
Figure 5.6 : - Substitution Control
Figure 5.7 : - Substitution in Action.
199
Above is a sample code which shows how substitution control works. We have ASPX
code at the right hand side and class code at the behind code at the left hand side. We
need to provide the method name in the “methodname” attribute of the substitution
control.
Why do we need methods to be static for Post Cache substitution?
ASP.NET should be able to call this method even when there isn't an instance of your
page class available. When your page is served from the cache, the page object isn't
created. So ASP.NET skips the page life cycle when the page is coming from cache,
which means it won't create any control objects or raise any control events. If your dynamic
content depends on the values of other controls, you'll need to use a different technique,
because these control objects won't be available to your callback

No comments: