This article will go some common questions around caching which is asked during ASP.NET Interviews.
In this section, we will touch base on caching which is one of the most asked questions during ASP.NET Interviews. I have also created a 25 ASP.NET Interview questions with answer video series , please do watch to get more idea of what kind of questions are asked during interviews.
Previous parts of my interview questions series for architects:
UML interview questions Part 1: SoftArch5.aspx
Happy job hunting......
(I) How do we enable SQL Cache Dependency in ASP.NET 2.0?
Below are the broader steps to enable a SQL Cache Dependency:
aspnet_regsql -ed -E -d Northwind
- 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.
- -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
Now let us 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 a 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.
Figure 5.2: New stored procedures created
Just to make a 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_SqlCacheTablesFor ChangeNotification table, thereby indicating that the table has changed.
- Asp Net_Sql Cache Query Registered Tables Stored Procedure: This extracts just the table names from the AspNet_SqlCacheTablesForChangeNotification table. It is used to get a quick look at all the registered tables.
- 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 we have to notify saying which table needs to be enabled for notifications. That can be achieved in two ways:
- aspnet_regsql -et -E -d Northwind -t Products
- Exec spNet_SqlCacheRegisterTableStoredProcedure 'TableName'
Registering tables for notification internally creates a trigger for 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.
FOR INSERT, UPDATE, DELETE
SET NOCOUNT ON
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 to keep 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.
Figure 5.3: Entries in the Cache notification table
Enable ASP.NET polling using the 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:
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
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<ClsProductItem> products)
SqlCacheDependency sqlDependency = new SqlCacheDependency("Northwind", "Products");
HttpContext.Current.Cache.Insert("ProductsList", products, sqlDependency,
private static List<ClsProductItem> GetCachedProductList()
return HttpContext.Current.Cache["ProductsList"] as List<ClsProductItem>;
ClsProductItem is the business class, and here we are trying to cache a list of
ClsProductItems instead of a DataSet or DataTable. The following method is used by an
ObjectDataSource control to retrieve a
public static List<ClsProductItem> GetProductsList(int catId, string sortBy)
List<ClsProductItem> products = GetCachedProductList();
if (products == null)
ClsProductsDB db = new ClsProductsDB(_connectionString);
DbDataReader reader = null;
products = new List<ClsProductItem>(80);
if (catId > 0)
reader = db.GetProductsList(catId);
reader = db.GetProductsList();
products = BuildProductsList(reader);
if (sortBy.Contains("DESC")) products.Reverse();
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
<asp:SqlDataSource EnableCaching="True" SqlCacheDependency="Northwind:Products" ... />
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 if the SQL actually hits the database after the first run.
(I) What is Post Cache substitution?
Post cache substitution is used when we want to cache the whole page but also needs some dynamic region inside that cached page. Some examples like
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 an
<asp:Substitution> control to the page at the desired location, and set its
methodName attribute to the name of the callback method.
Figure 5.5: “Writesubstitution” in action
You can see we have a static function
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 has not 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 its content is never cached.
The above example was by using
WriteSubstitution. Now let's try to see how we can do this by using the
<asp:substitution> control. You can get the
<asp:substitution> control from the editor toolbox.
Figure 5.6: Substitution control
Figure 5.7: Substitution in action
Below is a sample code that shows how the 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.
(I) Why do we need methods to be static for Post Cache substitution?
ASP.NET should be able to call this method even when there is not an instance of your page class available. When your page is served from the cache, the page object is not created. Therefore, ASP.NET skips the page life cycle when the page is coming from cache, which means it will not create any control objects or raise any control events. If your dynamic content depends on the values of other controls, you will need to use a different technique, because these control objects will not be available to your callback.
For further reading do watch the below interview preparation videos and step by step video series.