Add/Update Data in Cache with Tags
NCache allows the user to create tags and then add items to the cache with tags. The user can also add tag through CacheItem. Moreover, the tags can be updated as well as new tags can be appended to an already existing tag list.
Pre-Requisites for Using 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 Tags
Tags are first created and then items are added to the cache along with these tags using the Add method.
The following example adds an item to the cache along with the tags created; after checking if the item does not exist already. An item customer is added to the cache with the tag array tags.
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 customer from database
Customer customer = FetchCustomerFromDB("ALFKI");
// Create a unique cache key for this customer.
string key = $"Customers:{customer.CustomerID}";
// Specify Tags
Tag[] tags = new Tag[2];
tags[0] = new Tag("East Coast Customers");
tags[1] = new Tag("Important Customers");
// Add Customer object to cache with tags
CacheItemVersion version = cache.Add(key, customer, tags);
// Item added in cache 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.
Tag Data through CacheItem
CacheItem is a custom class provided by NCache which can be used to add data to the cache.
CacheItem
also lets you set additional
specifications associated with an object as property of Tags class.
Warning
- If the key already exists, an exception will be thrown.
- Providing
Null
tag array will throw an ArgumentNullException.
The following example adds a CacheItem
containing the object customer to the cache. It then sets an additional tag property against it by adding the tags tags.
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 customer from database against given customer ID
Customer customer = FetchCustomerFromDB("ALFKI");
// Create a unique cache key for this customer.
string key = $"Customers:{customer.CustomerID}";
// Specify Tags
Tag[] tags = new Tag[2];
tags[0] = new Tag("East Coast Customers");
tags[1] = new Tag("Important Customers");
// Create a new CacheItem
CacheItem cacheItem = new CacheItem(customer);
// Setting the tag property of the cacheItem
cacheItem.Tags = tags;
// Add customer object to 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 Tags to Existing Data
If an item already exists in the cache, tags can be added to that item using the Insert method.
Following are the two scenarios for using the Insert
API.
If no tags exist with the item, the provided tags will be added to the item.
If tags already exist with the item, the already existing tags will be overwritten.
The following example adds new tags to the already existing item customer.
Warning
Providing Null
tag array will throw an ArgumentNullException.
try
{
// Pre-condition: Cache is already connected
// Specify Tags
Tag[] tags = new Tag[2];
tags[0] = new Tag("East Coast Customers");
tags[1] = new Tag("Important Customers");
// Get customer from database against given customer ID
Customer customer = FetchCustomerFromDB("ALFKI");
// Create a unique cache key for this customer.
string key = $"Customers:{customer.CustomerID}";
// Updates the object by adding tags to the item 'customer'
cache.Insert(key, customer, 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.
Update Data with Tags through CacheItem
Updating tags through CacheItem requires the item to be first fetched, its tags to be modified and then re-inserted to the cache using the Insert method.
Following example first fetches the CacheItem
, creates a tag list with the new tags and then re-inserts the CacheItem in the cache along with the modified tag list. Hence, overrides the value of existing tags.
Warning
Providing Null
tag array will throw an ArgumentNullException.
try
{
// Get cache item from cache against given key
string key = "ALFKI";
CacheItem cacheItem = cache.GetCacheItem(key);
// Create new Tag array
Tag[] newTags = new Tag[2];
// Specify Tags
newTags[0] = new Tag("US Customers");
newTags[1] = new Tag("VIP Customers");
// Updates the tags with the new tags
// Overrides the value of the existing tags
cacheItem.Tags = newTags;
//Re-inserts the cacheItem into cache with modified tags
cache.Insert(key, cacheItem);
}
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.
Append Tags to Already Existing Tags
If there is a need to append a new tag to the already present tags or if a tag needs to be removed from the already present tags, the operation would require manipulating the tags array. For this purpose, create a new list with the tags to append and copy that list to the array containing the tags already. This way a new tag would be added to the array containing the tags previously created without affecting them.
Following example appends new tags to already existing tag list tags.
Warning
Providing Null
tag array will throw an ArgumentNullException.
try
{
// Get customer from database against the given key
string key = "ALFKI";
CacheItem cachedCustomer = cache.GetCacheItem(key);
List<Tag> customerTags = new List<Tag>();
// Initialize the list with existing tags
customerTags = new List<Tag>(cachedCustomer.Tags);
// Add new tags to existing list of tags
customerTags.Add(new Tag("VIP Cutsomers"));
customerTags.Add(new Tag("US Customers"));
// Assign newly built tag list to the cached customer object.
cachedCustomer.Tags = customerTags.ToArray();
// Update the modified customer object in
}
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 Groups
Retrieve Data from Cache with Tags
Remove Data from Cache with Tags
Search Data in Cache with SQL and Tags
Delete Data in Cache with SQL and Tags
Named Tags