Alachisoft NCache 4.1 - Online Documentation

Database Dependencies with CAB

 
NOTE: This feature is not available in NCache Express and Professional edition.
 
Alachisoft.NCache.EnterpriseLibrary.Caching.Expirations contains few classes which can be used for cache dependencies with caching application block. These classes are DbDependency and SqlYukonDependency. DbDependency holds Db dependency data and is later used by NCache to create a polling based Db dependency object. While SqlYukonDependency holds the SQL2005 dependency data and is only available for SQL Server 2005.
 
To use DBDependency, it is required to enable the notifications for database. For details, see Enabling Notifications For SQL Server, Enabling Notifications For DB2 and Enabling Notifications For Oracle. This is a row based dependency. The cache key is associated with the table's primary key value. Thus an item expires only if the row with that primary key gets changed.
 
DBDependency:
 
Following is the step-by-step guide for using DBDependency. The example given is for SQL Server, however, Oracle and DB2 databases can also be used.
 
  1. Enable Notifications for Products table in Northwind database. See Enabling Notifications For SQL Server.
  2. Create an ASP.NET Application inside Visual Studio.NET by the name DataCachingUsingNCache.
  3. Register NCache as Custom Cache Manager for MS Enterprise Library 4.1 such that 'theCache' is used as a backing store. See Register NCache With CAB
  4. Include the following namespaces in your application:
     
    using Alachisoft.NCache.Runtime.Caching;
    using Alachisoft.NCache.Runtime.Dependencies;
     
  5. Add a new Web Form named DataCacheSample.aspx to your project.
  6. Add a nested class Product inside the code behind.
     
    [Serializable]
    class Product
    {
    public Product() { }
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public int SupplierID { get; set; }
    public int CategoryID { get; set; }
    public decimal UnitPrice { get; set; }
    }
     
  7. Declare a private variable "_cache" in the code behind of the DataCacheSample as.
     
    private CacheManager _cache;
     
  8. Add the following code in Page_Load event of the DataCacheSample as.
     
    protected void Page_Load( object sender, EventArgs e)
    {
    if (_cache == null ) { _cache = CacheFactory.GetCacheManager( "NCacheManager" ); }
    }
     
  9. On the Design view tab for the Web Form, add a DataGrid to the DataCacheSample page.
  10. Add a Web Form button. Change the ID property of this button to FetchFromDB, and then change the Text property to Fetch From Database.
  11. Add a second Web Form button. Change the ID property to FetchFromCache, and then change the Text property to Fetch From Cache.
  12. Add a Web Form label. Change the ID property to Status, and then clear the Text property.
  13. On the Design view tab, double-click the FetchFromDB button to open the FetchFromDB_Click event in the code-behind page.
  14. Add the following code to the FetchFromDB_Click event:
     
    protected void FetchFromDB_Click( object sender, System.EventArgs e)
    {
    string connectionString = "Server=localhost;initial catalog=northwind;User ID = sa; password =;" ;
    string commandText = "SELECT ProductID, ProductName, SupplierID, CategoryID, UnitPrice FROM dbo.Products where productid < 11" ;
    DataSet ds = new DataSet();
    //Create the connection and pass in the ConnectionString
    SqlConnection mySqlConn = new SqlConnection(connectionString);
    SqlCommand sqlCmd = new SqlCommand(commandText, mySqlConn);
    mySqlConn.Open();
    SqlDataReader sqlReader = sqlCmd.ExecuteReader();
    List<Product> products = new List<Product>();
    while (sqlReader.Read())
    {
    Product product = new Product();
    product.ProductID = sqlReader.GetInt32(0);
    product.ProductName = sqlReader.GetString(1);
    product.SupplierID = sqlReader.GetInt32(2);
    product.CategoryID = sqlReader.GetInt32(3);
    product.UnitPrice = sqlReader.GetDecimal(4);
    Alachisoft.NCache.EnterpriseLibrary.Caching.Expirations.DbDependency dependency =
    Alachisoft.NCache.EnterpriseLibrary.Caching.Expirations.DbDependency(connectionString, product.ProductID + ":dbo.Products" );
    _cache.Add(product.ProductID + ":dbo.Products" , product, dependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, Alachisoft.NCache.Runtime.CacheItemPriority.Normal);
    products.Add(product);
    }
    //Set the DataGrid's DataSource to the "products" list
    DataGrid1.DataSource = products;
    mySqlConn.Close();
    //Display the status
    Status.Text = products.Count+ " products fetched from database." ;
    DataGrid1.DataBind();
    }
     
  15. On the Design view tab for the DataCacheSample.aspx page, double-click the FetchFromCache button to open the FetchFromCache_Click event in the code-behind page.
  16. Add the following code to the FetchFromCache_Click event:
     
    protected void FetchFromCache_Click(object sender, EventArgs e)
    {
    List<Product> products = new List<Product>();
    for (int i = 0; i < 11; i++)
    {
    object cachedProduct = _cache.GetData(i + ":dbo.Products");
    if(cachedProduct == null){ continue;
    }
    Product product = cachedProduct as Product;
    products.Add(product);
    }
    DataGrid1.DataSource = products;
    DataGrid1.DataBind();
    Status.Text = products.Count + " products fetched from cache.";
    }
     
  17. On the Build menu in the Visual Studio .NET IDE, click Build to build the project.
  18. To run the code, right-click the DataCacheSample.aspx page in Solution Explorer, and then click View in Browser.
  19. Click the FetchFromDB button; the Status label should display "10 products fetched from database." and the DataGrid control is populated. All products are stored in cache.
  20. Click the FetchFromCache button; the Status label should display "10 products fetched from cache." and the DataGrid control is populated.
  21. Modify one of the displayed records in the Northwind database by using SQL Query Analyzer or another tool. After you modify the record, cached data for that row is invalidated.
  22. Click the FetchFromCache button again. The Status label displays the message "9 products fetched from cache." and 9 products are populated. The modified record in database was removed from cache.
     
    Note: If Status is still "10 products fetched from cache.", repeat step 21. As the Clean Interval may not have elapsed yet.
 
SQLYukonDependency:
 
For SQLYukonDependency to work with Caching application block, we need to do a minor change in the above code. We will use the class Alachisoft.NCache.EnterpriseLibrary.Caching.Expirations.SqlYukonDependency instead of Alachisoft.NCache.EnterpriseLibrary.Caching.Expirations.DBDependency. So the code snippet in step 16 of above example should be changed like following.
 
protected void FetchFromDB_Click(object sender, System.EventArgs e)
{
string connectionString = "Server=localhost;initial catalog=northwind;User ID = sa; password =;";
string commandText = "SELECT ProductID, ProductName, SupplierID, CategoryID, UnitPrice FROM dbo.Products where productid < 11";
DataSet ds = new DataSet();
//Create the connection and pass in the ConnectionString
SqlConnection mySqlConn = new SqlConnection(connectionString);
SqlCommand sqlCmd = new SqlCommand(commandText, mySqlConn);
mySqlConn.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
List<Product> products = new List<Product>();
while (sqlReader.Read())
{
Product product = new Product();
product.ProductID = sqlReader.GetInt32(0);
product.ProductName = sqlReader.GetString(1);
product.SupplierID = sqlReader.GetInt32(2);
product.CategoryID = sqlReader.GetInt32(3);
product.UnitPrice = sqlReader.GetDecimal(4);
string sqlCommand = "select ProductID, ProductName, SupplierID, CategoryID, UnitPrice from dbo.Products where ProductID="+product.ProductID;
Alachisoft.NCache.EnterpriseLibrary.Caching.Expirations.SqlYukonDependency dependency =
Alachisoft.NCache.EnterpriseLibrary.Caching.Expirations.SqlYukonDependency(connectionString, sqlCommand);
_cache.Add(product.ProductID + ":dbo.Products", product, Alachisoft.NCache.Runtime.CacheItemPriority.Normal, null, dependency );
products.Add(product);
}
//Set the DataGrid's DataSource to the "products" list
DataGrid1.DataSource = products;
mySqlConn.Close();
//Display the status
Status.Text = products.Count+ " products fetched from database.";
DataGrid1.DataBind();
}
 
Note: If SQL Server goes down/restarts, all dependencies become invalid and are removed from the cache.
 
 
See Also
 

 
Copyright © 2005-2012 Alachisoft. All rights reserved.