Add/Update Data in Cache with Named Tags
In order to associate Named Tags with any cache item, it is required to provide a list of Named Tags, each having two parameters that are key as string which is the name of the tag and value as any primitive type which is the assigned value to the key. NCache then allows you to associate your objects with these Named Tags.
When items are already added in the cache with certain named tags, NCache provides the user with an option of updating named tags already present in the cache.
Pre-Requisites for Using Named Tags
- Include the following namespace in your application:
Alachisoft.NCache.Web.Caching
Alachisoft.NCache.Runtime
- The application must be connected to cache before performing the operation.
- Cache must be running.
- Make sure that the data being added is serializable.
- To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Add Data to Cache with Named Tags
NamedTagsDictionary is a class provided by NCache so you can associate these named tags with a particular data set. In order to add items with named tags; first create a named tag dictionary and add the tags and their values to it using the Add() API.
Following example first creates a named tag and then adds an item to the cache along with the named tags and its value; after checking if the item already exists in the cache.
Warning
- If the key already exists, an exception will be thrown.
- Providing
Null
tag array will throw an ArgumentNullException.
Tip
One quick way to verify whether item has been added is to use either properties of the Cache class:
try
{
// Pre-condition: Cache is already connected
// Get product from database
Product product = FetchProductFromDB("1001");
// Create a unique cache key for this product
string key = $"Products:{product.ProductID}";
// Creating a Named Tags Dictionary
NamedTagsDictionary productNamedTag = new NamedTagsDictionary();
// Adding Named Tags to the Dictionary where
// Keys are the names of the tags as string type
// Values are the instances of data, of primitive data types.
productNamedTag.Add("FlashSaleDiscount", 0.5);
// product is now added in cache with the productNamedTag dictionary
CacheItemVersion version = cache.Add(key, product, productNamedTag);
// Item is added in the cache successfully with the named tags
}
catch (OperationFailedException ex)
{
// NCache specific exception
if (ex.Message.Contains("The specified key already exists."))
{
// If same key already exists in cache
}
else
{
// Exception can occur due to:
// Connection Failures
// Operation performed during state transfer
// Operation Timeout
}
}
catch (Exception ex)
{
// Any other generic exception like ArgumentNullException or ArgumentException
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Add Named Tags through CacheItem
CacheItem is a custom class provided by NCache which can be used to add data to the cache.
This class encapsulates data as its value property. CacheItem
also lets you set additional
specifications associated with an object as property of the NamedTags class.
In the following example Named Tags are set by assigning them as a property of
CacheItem
.
try
{
//Pre-condition: Cache is already connected
// Get product from database against given productID
Product product = FetchProductFromDB("1001");
// Create a unique cache key for this product
string key = $"Products:{product.ProductID}";
// Creating a Named Tags Dictionary
NamedTagsDictionary productNamedTag = new NamedTagsDictionary();
// Adding Named Tags to the Dictionary where
// Keys are the names of the tags as string type
// Values are the instances of data, of primitive data types.
productNamedTag.Add("FlashSaleDiscount", 0.5);
// Create a new CacheItem
CacheItem cacheItem = new CacheItem(product);
// Setting the named tag property of the cacheitem
cacheItem.NamedTags = productNamedTag;
// Add product object to the cache
CacheItemVersion version = cache.Add(key, cacheItem);
// CacheItem added successfully
}
catch (OperationFailedException ex)
{
// NCache specific exception
if (ex.Message.Contains("The specified key already exists."))
{
// If same key already exists in cache
}
else
{
// Exception can occur due to:
// Connection Failures
// Operation performed during state transfer
// Operation Timeout
}
}
catch (Exception ex)
{
// Any other generic exception like ArgumentNullException or ArgumentException
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Add Named Tags to Existing Data
If an item already exists in the cache, named tags can be added to that item using the Insert method.
Following are the two scenarios for using the Insert
API.
If no named tags exist with the item, the provided tags will be added to the item.
If name tags already exist with the item, the already existing tags will be overwritten.
The following example adds new named tags to the already existing item.
Warning
Providing Null
tag array will throw an ArgumentNullException.
try
{
// Pre-condition: Cache is already connected
// Item is already added in the cache
// Get product from cache against given productID
string key = "Products:1001";
Product product = cache.Get(key) as Product;
// Create a Named Tags Dictionary
NamedTagsDictionary productNamedTag = new NamedTagsDictionary();
// Adding Named Tags to the Dictionary where
// Keys are the names of the tags as string type
// Values are the instances of data, of primitive data types.
productNamedTag.Add("FlashSaleDiscount", 0.5);
// Updates the object by adding named tags to the item product
cache.Insert(key, product, productNamedTag);
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection failures
// Operation performed during state transfer
// Operation timeout
}
catch (Exception ex)
{
// Any other generic exception like ArgumentNullException or ArgumentException
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Update Data with Named Tags through CacheItem
Updating named tags through CacheItem requires the item to be first fetched, its named tags to be modified and then re-inserted to the cache using the Insert method.
Following example first fetches the CacheItem
, creates a list with the new named tags and then re-inserts the CacheItem in the cache along with the modified named tag list. Hence, overwrites the value of existing named tags.
Warning
Providing Null
named tag array will throw an ArgumentNullException.
try
{
// Get cache item from cache against given key
string key = "Products:1001";
CacheItem cacheItem = cache.GetCacheItem(key);
// Create a Named Tags Dictionary
NamedTagsDictionary newProductNamedTag = new NamedTagsDictionary();
// Adding Named Tags to the Dictionary where
// Keys are the names of the tags as string type
// Values are the updated instances of data, of primitive data types.
newProductNamedTag.Add("FlashSaleDiscount", 0.7);
// Updates the named tags with the new named tags
// Overrides the value of the existing named tags
cacheItem.NamedTags = newProductNamedTag;
//Re-inserts the cacheItem into cache with modified named tags
cache.Insert(key, cacheItem);
// cacheItem is succssfully added in cache with modified named tags
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation performed during state transfer
// Operation Timeout
}
catch (Exception ex)
{
// Any other generic exception like ArgumentNullException or ArgumentException
}
Recommendation: To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
See Also
Using Tags
SQL Query with NamedTags
SQL Delete with NamedTags
Data Expiration