Click here to Skip to main content
Click here to Skip to main content

Caching Interview Questions: Part 2

, 4 Mar 2014
Rate this:
Please Sign up or sign in to vote.
Caching Interview Questions Part 2

Caching Concepts

Introduction

In this section we will touch base on one of the important concepts in .NET Caching. You can download my .NET interview questions PDF here: http://www.questpond.com/SampleDotNetInterviewQuestionBook.zip.

I have also put all the design patterns in a video format and uploaded on http://www.questpond.com/FreeDesign1.htm. You can visit http://www.questpond.com and download the complete architecture interview questions PDF which covers SOA, UML, Design Patterns, Togaf, OOPs etc.

You can download the software architecture interview questions PDF here: Download Software Architecture Interview Questions.

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:

  • 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

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.

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 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:

  • 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

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, 
                DateTime.Now.AddDays(1), Cache.NoSlidingExpiration);
}
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 List of Products:

public static List<ClsProductItem> GetProductsList(int catId, string sortBy)
{
    //Try to Get Products List from the Cache
    List<ClsProductItem> 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<ClsProductItem>(80);
        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 ClsProductItem-
        products = 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;
}

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:

<asp:SqlDataSource EnableCaching="True" 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 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 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 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.

Other interview questions PDFs

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Shivprasad koirala
Architect http://www.questpond.com
India India

I am a Microsoft MVP for ASP/ASP.NET and currently a CEO of a small
E-learning company in India. We are very much active in making training videos ,
writing books and corporate trainings. Do visit my site for 
.NET, C# , design pattern , WCF , Silverlight
, LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server  training 
and Interview questions and answers


Comments and Discussions

 
QuestionKeep up the good work. PinmemberRene Pilon5-Mar-14 7:24 
GeneralMy vote of 1 Pinmemberlespauled4-Mar-14 3:58 
GeneralRe: My vote of 1 PinmvpShivprasad koirala4-Mar-14 4:12 
GeneralRe: My vote of 1 PinmemberRene Pilon5-Mar-14 7:22 
Questionwhat is diff between in these two way of adding item in cache Pinmemberfindtango6-Jan-10 0:33 
AnswerRe: what is diff between in these two way of adding item in cache Pinmemberlespauled4-Mar-14 3:51 
GeneralCache problem Pinmemberfgoldenstein28-Dec-09 6:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 4 Mar 2014
Article Copyright 2008 by Shivprasad koirala
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid