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

Notify Extensible Dependency Usage and Implementation

Note

This feature is only available in NCache Enterprise Edition for .NET Servers.

In addition to Extensible Dependency and Bulk Extensible Dependency, NCache provides another method for cache dependency called Notification Based Extensible Dependency or Notify Extensible Dependency. In Notify Extensible Dependency, client side is responsible for deploying a provider that holds the logic behind the dependency and when to invoke that dependency. Server then invokes cache for dependency related methods considering the logic provided by the client. Cache checks for items under notify extensible dependency and whether they need to be removed or not.

In notification based extensible dependency, clients have all the control on how and and when to call a dependency on an item. In this way, items can be expired from cache in an extremely flexible way. NCache provides an abstract class NotifyExtensibleDependency, an extension of custom dependencies provided by NCache, that implements this behavior.

Tip

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

Step 1: Implement NotifyExtensibleDependency Class

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

Prerequisites

  • Install either of the following NuGet packages in your application based on your NCahce edition:
    • Enterprise: Alachisoft.NCache.SDK
    • Professional: Alachisoft.NCache.Professional.SDK
  • To override the NotifyExtensibleDependency class, include the Alachisoft.NCache.Runtime.Dependencies namespace in your application.
  • The class implementing NotifyExtensibleDependency must be marked as Serializable along with any other parameters the process code might take in.
  • Make sure to Deploy Custom Dependency Providers using NCache Web Manager.
  • The project must be implemented as a Class Library (.dll) in Visual Studio. This will be deployed on NCache cluster.
Note

To get detailed information about the methods implemented in NotifyExtensibleDependency, refer to the Methods section.

Let's suppose you want to add customers to your Cosmos database with your own dependency logic. Here's how to implement notification extensible dependency with Cosmos DB in your application.

[Serializable]
    public class NotificationDependency<T> : NotifyExtensibleDependency
    {
        // Class parameters

        public NotificationDependency(/* */)
        {
            // Assign values to class members 
        }

        public override bool Initialize()
        {
            // Register dependency against key
            RegisterDependency(_key, this);
            return true;
        }

        public bool RegisterDependency(string key, NotifyExtensibleDependency dependency)
        {
            lock (this)
            {
                // Your logic here 
                dependencies.Add(key, dependency);
            }
            return true;
        }

        public void OnFeedChange(params object[] args)
        {
            // Find the matching dependency and fire its DependencyChangedEvent
            var key = args[0];
            var notifyExtensibleDep = (dependencies[key] as NotifyExtensibleDependency);
            notifyExtensibleDep?.DependencyChanged.Invoke(this);

            // Remove the matched keys from cache
            lock (dependencies)
            {
                dependencies.Remove(key);
            }
        }

        protected override void DependencyDispose()
        {
            // Dispose off resources 
        }
        // This class is to be deployed on NCache
    }

Step 2: Implement NotifyCustomDependencyProvider

To implement Notify Extensible Dependency provider in your application, use the following code snippet.

Prerequisites

  • Install either of the following NuGet packages in your application based on your NCahce edition:
    • Enterprise: Alachisoft.NCache.SDK
    • Professional: Alachisoft.NCache.Professional.SDK
  • To utilize NCache APIs, include the following namespaces in your application:
    • Alachisoft.NCache.Runtime.CustomDependencyProviders
    • Alachisoft.NCache.Runtime
    • Alachisoft.NCache.Runtime.Exceptions
  • This should be a class library project using Microsoft Visual Studio.
public class NotifyCustomDependencyProvider : ICustomDependencyProvider
{
    private string cacheName;
    private string monitoredUri;
    private string authKey;
    private string databaseName; 

    public void Init(IDictionary<string, string> parameters, string cacheName)
    {
        // Initialize cache and class parameters
    }

    public NotificationDependency CreateDependency(string key, IDictionary<string, string> dependencyParameters)
    {
        string customerId="";        
        string monitoredCollection = "";
        string leaseCollection = "";

        if (dependencyParameters != null)
        {
            if (dependencyParameters.ContainsKey("Key"))
                customerId = dependencyParameters["Key"];

            if (dependencyParameters.ContainsKey("MonitoredCollectionName"))
                monitoredCollection = dependencyParameters["MonitoredCollectionName"];

            if (dependencyParameters.ContainsKey("LeaseCollectionName"))
                leaseCollection = dependencyParameters["LeaseCollectionName"];

            // Create notify extensible dependency
            NotificationDependency<Customer> cosmosDbDependency = new NotificationDependency<Customer>(customerId,
                monitoredUri, authKey, databaseName, monitoredCollection, databaseName, leaseCollection);
            return cosmosDbDependency;
        }
        else
        {
            // Dependency parameters not found
        }
    }
    public void Dispose ()
    {
        // Dispose off all resources 
    }
}

Step 3: Deploy Implementation on Cache

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

Step 4: Use Notification Extensible Dependency

One notification based extensible dependency has been implemented and deployed on the cache, it is ready to be used in your application. The following code shows how to add data using Insert() with notification based custom dependency.

Prerequisites

  • Install the Alachisoft.NCache.SDK NuGet packages in your application.
  • To utilize NCache API, include the following namespaces in your application:
    • Alachisoft.NCache.Client
    • Alachisoft.NCache.Runtime.Dependencies
    • Alachisoft.NCache.Runtime.Exceptions
  • The NotifyExtensibleDependency class must be deployed on cache.
  • The application must be connected to cache before performing the operation.
  • Cache must be running.
  • To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
  • To handle any unseen exceptions, refer to the Troubleshooting section.
Note

In case of client cache, the user needs to explicitly deploy these assemblies on the client cache.

try
{   // Specify the connection credentials 
    string endPoint = ConfigurationManager.AppSettings["EndPoint"];
    string authKey = ConfigurationManager.AppSettings["AuthKey"];
    string monitoredCollection = ConfigurationManager.AppSettings["MonitoredCollection"];
    string leaseCollection = ConfigurationManager.AppSettings["LeaseCollection"];
    string databaseName = ConfigurationManager.AppSettings["DatabaseName"];
    string providerName = ConfigurationManager.AppSettings["ProviderName"];

    // Fetch a sample customer from the database 
    Customer customer = LoadCustomerFromDatabase(customerId);

    // Specify the unique key of the item
    string key = "Customer#" + customer.Id ;

    // Create dictionary for dependency parameters
    IDictionary<string, string> param = new Dictionary<string, string>();
    param.Add("CustomerID", customer.Id);
    param.Add("EndPOint", endPoint);
    param.Add("AuthKey", authKey);
    param.Add("MonitoredCollection", monitoredCollection);
    param.Add("LeaseCollection", leaseCollection);
    param.Add("DatabaseName", databaseName);

    //Creating notification dependency
    CustomDependency cosmosDbDependency = new CustomDependency(providerName, param);

    // Create a cacheItem
    var cacheItem = new CacheItem(customer);
    cacheItem.Dependency = cosmosDbDependency;

    // Add cacheItem to the cache with notification 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
}

Methods

Initialize()

Every time an item is added to the cache, Initialize() method is called to check whether cache has a secure connection with the data source or not. If this methods returns true, it means that the cache could establish a secure connection with the data source. It then places the item in the key-value store and the dependency list of the cache until it needs to be removed.

But, in case this method returns false, it shows that the data source required to access and monitor data isn't available to the cache, hence that item is removed from the cache. Initialize method is available for all extensible dependencies.

DependencyChanged()

After an item is successfully placed in the cache, there's a need to know how to invoke dependency on it. For this reason, a delegate DependencyChanged is used. A handler of this delegate is deployed on the cache. Client gets to control when to call this delegate and invoke dependency on an item. Whenever this delegate is called, it removes the item against which it was called from the cache.

Additional Resources

NCache provides sample application for notification extensible dependency on GitHub.

See Also

Custom Dependencies
Sync Cache using Extensible Dependency
Sync Cache using Bulk Extensible Dependency
Configure Custom Dependencies

Back to top Copyright © 2017 Alachisoft