• Webinars
  • Docs
  • Download
  • Blogs
  • Contact Us
Try Free
Show / Hide Table of Contents

Extensible Dependency Usage and Implementation

Note

This feature is only available in NCache Enterprise Edition.

In extensible dependency, the users can have their own dependencies scenarios that invalidate an item when a certain criterion is met. In this way, items can be expired from the cache several flexible ways where expiration logic meets the user’s business requirements. To implement extensible dependency in your application, NCache provides an abstract class ExtensibleDependency. Follow the guide below to understand how to implement and use this class.

Tip

Refer to Custom Cache Dependencies to get acquainted with all cache dependency custom methods provided by NCache.

Prerequisites

  • .NET/.NET Core
  • Java
  • To learn about the standard prerequisites required to work with all NCache server-side features please refer to the given page on Server Side API Prerequisites.
  • The project must be implemented as a Class Library (.dll) in Visual Studio. This will be deployed on NCache cluster.
  • The Dependency class must be deployed on cache.
  • For API details refer to: ICache, CacheItem, insert, ExecuteReader, CustomDependency, ExtensibleDependency, HasChanged, IDictionary, CommandText, CreateDependency, ICustomDependencyProvider.
  • To learn about the standard prerequisites required to work with all NCache server-side features please refer to the given page on Server Side API Prerequisites.
  • The class must be implemented as a Class project in Java IDE. This will be deployed on the NCache cluster.
  • The Dependency class must be deployed on cache.
  • For API details refer to: Cache, insert, CustomDependency, ExtensibleDependency, CacheItem, QueryCommand, Map, hasChanged, CustomDependencyProvider.

Step 1: Implement ExtensibleDependency Class

The first step in introducing your own logic for Extensible Dependency is to implement the ExtensibleDependency class.

Let's suppose there is a grocery store which has a big collection of products which customers often buy. These products can be cached from the database to check their units in stock. The following dependency implementation polls the Northwind database and expires all the Products for which units in stock are less than 100.

  • .NET/.NET Core
  • Java
[Serializable]
public class Dependency : ExtensibleDependency
{
    // Class parameters
    [NonSerialized]
    OleDbConnection connection;

    public Dependency(int productId, string connString)
    {
        connection =  new OleDbConnection(connString);
        connection.Open();
        productID = productId;
    }

    public bool HasChanged()
    {
        if (GetAvailableUnits(productID) < 100)
            return true;
        return false;
    }

    internal int GetAvailableUnits(int productID)
    {
        if (connection == null)
        {
            connection = new OleDbConnection(connString);
            connection.Open();
        }

        OleDbCommand command = connection.CreateCommand();
        command.CommandText = String.Format(CultureInfo.InvariantCulture,
            "Select UnitsInStock From Products" +
            " where ProductID = {0}", productID);

        int availableUnits = -1;
        OleDbDataReader reader = null;
        reader = command.ExecuteReader();
        if (reader.Read())
        {
            availableUnits = Convert.ToInt32(reader["UnitsInStock"].ToString());
        }
        reader.Close();
        return availableUnits;
    }
    protected void DependencyDispose()
    {
        // Dispose off all resources
    }
    // This class is to be deployed in NCache
}
public class Dependency extends ExtensibleDependency{
    // Class parameters
    Connection connection;

    public Dependency(int productID, String connString) {
        connection = DriverManager.getConnection(connString);
        connection.open();
        productId = productID;
    }

    public boolean hasChanged() {
        if (getAvailableUnits(productId) < 100) {
            return true;
        } else {
            return false;
        }
    }

    int getAvailableUnits(int productID) {
        int availableUnits = -1;
        ResultSet result = null;
        try {
            Statement statement = connection.createStatement();
            String query = "Select UnitsInStock FROM dbo.Products WHERE ProductID = " + "?";
            QueryCommand queryCommand = new QueryCommand(query);
            queryCommand.getParameters().put("ProductID", productID);
            result = statement.executeQuery(query);
            return Integer.valueOf(String.valueOf(result));
        } catch (Exception exception) {
            // Handle exceptions
        }
    }

    protected void dependencyDispose() {
        // Dispose off all resources
    }
    // This class is to be deployed in NCache
}

Step 2: Implement Custom Dependency Provider

A custom dependency provider for extensible dependency implements your logic that you created in step 1 on server side. Here's how you can implement your own extensible dependency provider:


This class implements the CustomDependencyProvider interface that is required to successfully create and deploy an Extensible Dependency Provider.

  • .NET/.NET Core
  • Java
public class ExtensibleDependencyProvider : ICustomDependencyProvider
{
    public void Init(IDictionary<string, string> parameters, string cacheName)
    {
        // Initialize cache and class parameters
    }

    public Dependency CreateDependency(string key, IDictionary<string, string> dependencyParameters)
    {
        int productId = 0;
        string connectionString = "";

        if (dependencyParameters != null)
        {
            if (dependencyParameters.ContainsKey("ProductID"))
                productId = Int32.Parse(dependencyParameters["ProductID"]);

            if (dependencyParameters.ContainsKey("ConnectionString"))
                connectionString = dependencyParameters["ConnectionString"];

            // Create extensible dependency 
            Dependency dependency = new Dependency(productId, connectionString);
            return dependency;
        }
        else
        {
            // No parameters found
        }
    }

    public void Dispose ()
    {
        // Dispose off all resources
    }
}
public class ExtensibleDependencyProvider implements CustomDependencyProvider {
    public void init(Map<String, String> parameters, String cacheName) {
        // Initialize cache and class parameters
    }

    public Dependency createDependency(String key, Map<String, String> dependencyParameters) {
        int productId = 0;
        String connectionString = "";

        if (dependencyParameters != null) {
            if (dependencyParameters.containsKey("ProductID")) {
                productId = Integer.valueOf(dependencyParameters.get("ProductID"));
            }

            if (dependencyParameters.containsKey("ConnectionString")) {
                connectionString = dependencyParameters.get("ConnectionString");
            }

            // Create extensible dependency
            Dependency dependency = new Dependency(productId, connectionString);
            return dependency;
        } else {
            // No parameters found
        }
    }

    public void dispose () {
        // Dispose off all resources
    }
}

Step 3: Deploy Implementation on Cache

Deploy this class and all dependent assemblies on NCache by referring to Deploy Providers in Administrator’s Guide for help.

Step 4: Use Extensible Dependency

Once extensible dependency class has been implemented and deployed, it is ready to be used in your application.


The following code shows how to add data into the cache using the Insert method with extensible dependency enabled.

  • .NET/.NET Core
  • Java
try
{   // Specify the connection string
    string connectionString = ConfigurationManager.AppSettings["connectionstring"];

    // Fetch the product to be added to the cache
    Product product = FetchProductFromDB(productId);

    // Specify the unique key of the item
    string key = $"Product:{product.ProductID}";

    // Create a cacheItem
    var cacheItem = new CacheItem(product);

    // Create dictionary for dependency parameters 
    IDictionary<string, string> param = new Dictionary<string, string>();
    param.Add("ProductID", product.Id.ToString());
    param.Add("ConnectionString", connectionString);

    // Create Extensible Dependency using Provider and Add it to Cache Item
    CustomDependency customDependency = new CustomDependency(ConfigurationManager.AppSettings["ProviderName"], param);
    cacheItem.Dependency = customDependency;

    // Add cacheItem to the cache with dependency
    cache.Insert(key, cacheItem);
}
catch (OperationFailedException ex)
{
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
}
catch (Exception ex)
{
    // Any generic exception like ArgumentNullException or ArgumentException
}
try {
    // Specify the connection string
    String connectionString = "";

    // Fetch the products to be added in the cache
    Product product = fetchProductByProductID(productId);

    // Specify unique key for this product
    String key = "Product:" + product.productID;

    // Create a cache item
    CacheItem cacheItem = new CacheItem(product);

    // Create map and add parameters in it
    Map<String, String> map = new HashMap<String, String>();
    map.put("ProductID", String.valueOf(product.productID));
    map.put("ConnectionString", connectionString);

    // Create Extensible Dependency using Provider and add it to cache item
    CustomDependency customDependency = new CustomDependency(providerName, map);
    cacheItem.setDependency(customDependency);

    // Add cacheItem to the cache with dependency
    cache.insert(key, cacheItem);
} catch (CacheException exception) {
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
} catch (Exception exception) {
    // Generic exception
}

Additional Resources

NCache provides sample application for extensible dependency on GitHub.

See Also

How to Configure Custom Dependency
Cache Data Dependency on External Source
WAN Replication across Multi Datacenters through Bridge
Data Source Providers (Backing Source)

Back to top Copyright © 2017 Alachisoft