NCache 4.3 - Online Documentation

Implementing IWriteThruProvider

 
NOTE: This feature is not available in NCache Express and Professional edition. 
 
Implementing Interface:
 
Following is a list of methods needs to be defined by the class implementing interface and a brief description of their purpose.
 
  • public void Init(System.Collections.IDictionary parameters, String cacheId);
 
This method is responsible for performing tasks like allocating resources, acquiring connections etc. When the cache is initialized and write-through is enabled, it calls Init method to notify the client that cache has initialized and you might initialize your data source too. Init method passed cache name and parameters (contains all the parameters (if any) that were specified using  NCache Manager backing source settings). These parameters can be utilized in many ways. For example, connection string of a data source can be specified as a parameter. Whenever cache will be initialized, the connection to the data source could be made using this connection string passed as an argument. Thus, it provides a flexible way to change the data source dynamically without requiring code changes.
 
public void Init(System.Collections.IDictionary parameters, String cacheId);
{
String connectionString = "Data Source=Localhost//SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True" ;
connection = new SqlConnection (connectionString);
connection.Open();
}
 
  • void Dispose();
 
This method is responsible for performing tasks like releasing the resources etc. When Cache is stopped it calls Dispose() method to notify the client that the cache has stopped now and you can free the resources related to your data source.
 
public void Dispose()
{
connection.Close();
}
 
 
  • Write operation & OperationResult:
 
IWriteThruProvider provides WriteToDataSource  APIs which is responsible for all types of write operations on data source. The argument passed in these APIs is WriteOperation. This data structure holds following information:
 
  • Key.
  • Write operation type (Add, Delete and Update).
  • Retry count (specify number of operation retries in case of failure).
  • Provider Cache item (contains an item's value, dependency, group, subgroup, tag etc).
 
Retry Count will be updated on each operation retry. User can also update provider cache item in case he/she wants to update the item later in cache store. OperationResult holds information about:
 
  • WriteOperation : Operation performed on data source.
  • Update in cache flag : This flag specifies whether to update the returned write operation in cache or not. This is only applicable for Add and Insert operation types. In NCache an operation is first applied on cache store and then to data source (if write through caching is enabled). So if user wants to synchronize the cache store after updating  data source then this flag will be used.
  • Data source operation status : Write through caching basically synchronize your data source with cache store. Previously in case of operation failure on data source, item is also removed from cache, now NCache provides more flexible ways to allow user to decide whether to keep the item in cache based on these operation statuses.
 
  • Success: This means item was successfully added to the data source so keep it in the cache as well.
  • Failure: This means item could not be added to data source, so in case of Add/Insert operations, item will be removed from cache. Operation failure exception will thrown to user in case of write thru and logged in case of write behind.
  • FailureDontRemove: This means item could not be added to the data source, but keep it in the cache. Operation failure exception will thrown to user in case of write thru and logged in case of write behind.
  • FailureRetry: This means item could not be added to the data source, keep the item in cache and retry. In case of write thru retry will be performed as write behind operation.
Note:
    In case of unhandled exception, operation status will be considered as failure and item will be removed from cache.
    An object will only be updated or added in cache when status is success and update in cache flag is set true.
  • Exception/ Error message :User can set exception/error message with operation result. This exception will be propagated to client in case of Failure and FailureDontRemove statuses.
 
 
  • public  OperationResult  WriteToDataSource(WriteOperation operation);
 
For write-thru, this  method is responsible for handling all types of atomic operations (Add, Insert and Remove) on data source. In write-behind, this operation will corresponds to all atomic and bulk operations if non batch mode is configured i.e. this method will be called in non batch mode only.
 
public OperationResult WriteToDataSource(WriteOperation operation);
{
 
      Product product = (Product)operation.ProviderCacheItem.Value;
        SqlCommand command =new SqlCommand();
        command.Connection = connection;
 
        if(operation.OperationType == WriteOperationType.Add)
    command.CommandText="INSERT INTO Products(ID,Name,Category)
    VALUES("+operation.Key+",'"+product.ProductName+"','"+product.Categories+"')";
            
            
        if(operation.OperationType == WriteOperationType.Delete)
            command.CommandText = "DELETE FROM Products WHERE ID =" + operation.Key + "";
 
        if(operation.OperationType == WriteOperationType.Update)
    command.CommandText = "UPDATE Products SET Name = '" + product.ProductName + "', Category='" +
    product.Categories + "'WHERE ID=" + operation.Key + "";
            
            
        int result = command.ExecuteNonQuery();
            
        OperationResult operationResult = new OperationResult(operation, OperationResult.Status.Success);
            
        if(result < 1)
          {
            operationResult.DSOperationStatus = OperationResult.Status.Failure;
          }
            
        return operationResult;
}
 
  • public OperationResult [] WriteToDataSource (WriteOperation[] operations)
 
Similarly for write thru this  method is responsible for handling bulk operations on data source. For write behind this method will be called for batch mode only and all atomic and bulk operations will be batched according to configured write behind batch settings. Array of WriteOperation is passed as parameter and returns operation result array against all  operations in bulk.
 
 
public OperationResult [] WriteToDataSource ( WriteOperation [] operations)
{
OperationResult []operationResult=new OperationResult[operations.Length];
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        int counter=0;
 
        foreach(WriteOperation operation in operations)
          {
 
            Product product = (Product)operation.ProviderCacheItem.Value;
 
            if (operation.OperationType == WriteOperationType.Add)
          command.CommandText = "INSERT INTO Products(ID,Name,Category) VALUES(" + operation.Key + ",'" +   
          product.ProductName + "','" + product.Categories + "')";
 
 
            if (operation.OperationType == WriteOperationType.Delete)
                  command.CommandText = "DELETE FROM Products WHERE ID =" + operation.Key + "";
 
            if (operation.OperationType == WriteOperationType.Update)
    command.CommandText = "UPDATE Products SET Name = '" + product.ProductName + "', Category='" +  
    product.Categories + "'WHERE ID=" + operation.Key + "";
 
 
            int result = command.ExecuteNonQuery();
 
            operationResult[counter] = new OperationResult(operation, OperationResult.Status.Success);
 
            if (result < 1)
              {
                  operationResult[counter].DSOperationStatus = OperationResult.Status.Failure;
              }
 
              counter++;
          }
 
      return operationResult;
 
}
 
 
Using Write-Thru Provider:
 
The code to access the cache should look like:
 
Cache mycache = NCache.InitializeCache("myreplicatedcache");
Product product = new Product();
CacheItem citem = new CacheItem (product);
cache.Add(textBox.Text, citem, DSWriteOption.WriteThru, null);
 
If you do not want to give provider name in API, you can provide it in client.ncconf. If provider name is not provided in both API and client.ncconf, default provider will automatically be used.
NCache also provide data source events for write behind mode.
 
 
<cache id = "myreplicatedcache" client-cache-id = "" default-readthru-provider = "XmlReadThruProviderclient-cache-syncmode="optimistic" default-writethru-provider = "XmlWriteThruProvider" load-balance="True" server-runtime-context="NCACHE">
<server name = "20.200.20.5">
</cache>
 
config.ncconf :
 
  <write-thru enable-write-thru="true">
    <provider class-name="Alachisoft.NCache.Writers.Writer1" default-provider="true" provider-name="xmlwritethru" 
              assembly-name="Providers.dll" full-name="Providers.dll" async-mode="false"/>
      <write-behind throttling-rate-per-sec="500" failed-operations-queue-limit="5000" mode="batch"  
                    failed-operations-eviction-ratio="5%">
          <batch-mode-config batch-interval="5s" operation-delay="0ms"/>
      </write-behind>
  </write-thru>
 
 
NCache logs the warnings in Application event log in case of an exception during loading the assemblies.
For debugging your providers see How to Debug Providers.
 
 
 
See Also
 
© Copyright  2014 Alachisoft. All rights reserved.