• Facebook
  • Twitter
  • Youtube
  • LinedIn
  • RSS
  • Docs
  • Comparisons
  • Blogs
  • Download
  • Contact Us
  • Products
  • Solutions
  • Customers
  • Resources
  • Company
  • Pricing
  • Download
Download
  • Client Side API Programming
  • Basic Operations - An Overview
  • Add Data
Show / Hide Table of Contents
  • Programmer's Guide
  • Setting Up Development Environment
    • .NET
      • Client API Prerequisites
      • Server-side API Prerequisites
    • Java
      • Client API Prerequisites
    • Python
      • Client API Prerequisites
    • Node.js
      • Client API Prerequisites
  • Client Side API Programming
    • Error Handling
    • Troubleshooting
    • Cache Keys and Data
    • How to Connect to Cache
    • Basic Operations - An Overview
      • Add Data
      • Update/Insert Data
      • Retrieve Data
      • Remove Data
    • Groups
      • Overview
      • Add/Update Data with Groups
      • Retrieve Data with Groups
      • Remove Data with Group
      • Search Group Data Using SQL
      • Delete Group Data Using SQL
    • Tags
      • Overview
      • Add/Update Data with Tags
      • Retrieve Data with Tags
      • Remove Data with Tags
      • Search Tag Data Using SQL
      • Delete Tag Data Using SQL
    • Named Tags
      • Overview
      • Add/Update Data with Named Tags
      • Remove Data with Named Tags
      • Search Data with Named Tags Using SQL
      • Delete Data with Named Tags Using SQL
    • Expirations
      • Overview
      • Absolute Expiration
      • Sliding Expiration
    • Data Dependency
      • Key Dependency
      • Multi-Cache Dependency
    • Dependency on Database
      • SQL Dependency
      • Oracle Dependency
      • OleDB Dependency
      • CLR Procedures in SQL Server
    • Dependency on External Source
      • File Dependency
      • Custom Dependency
      • Aggregate Dependency
    • Locks
      • Types of Locking
      • Pessimistic Locking
      • Optimistic Locking
    • SQL Query
      • Overview
      • Define Indexes Programmatically
      • Query with ExecuteReader and ExecuteScalar
      • Delete Data with ExecuteNonQuery
      • SQL Reference
    • LINQ Query
      • Overview
      • LINQ Query for Objects
      • LINQ Reference
    • Data Structures
      • Overview
      • List
      • Queue
      • Set
      • Dictionary
      • Counter
      • Invalidation Attributes
      • Searchable Attributes
      • Query on Data Structures
      • Remove from Data Structure
    • Events
      • Overview
      • Cache Level Events
      • Item Level Events
      • Management Level Events
    • Pub/Sub Messaging
      • Overview
      • Pub/Sub Topics
      • Publish Messages to a Topic
      • Subscribe to a Topic
      • Monitoring Pub/Sub Topics
    • Continuous Query
      • Overview
      • Use Continuous Query
    • Stream Processing
      • Add/Update Stream Data
      • Retrieve Stream Data
    • JSON
      • Overview
      • Use JSON Objects
      • Query JSON Data
    • Security API
      • Login with Credentials
    • Management API
    • Error Logging
    • Location Affinity
  • Server-side API Programming
    • Loader and Refresher
      • Overview
      • Implement Loader and Refresher
      • Components of Loader/Refresher
    • Data Source Providers
      • Read-through
        • Implement Read-through
        • Use Read-through
      • Write-through
        • Implement Write-through
        • Use Write-through
        • Use Write-behind
    • Custom Dependency
      • Implement Extensible Dependency
      • Implement Bulk Extensible Dependency
      • Implement Notify Extensible Dependency
    • Bridge Conflict Resolver
    • Entry Processor
      • Overview
      • Implement Entry Processor
    • MapReduce
      • Overview
      • Implement MapReduce
      • Use MapReduce
    • MapReduce Aggregator
      • Overview
      • Implement and Use Aggregator
    • Compact Serialization
  • Client Side Features
    • ASP.NET Core Caching
      • Session Storage
        • Session Provider
        • IDistributedCache
        • Sessions Usage
        • Multi-site Session Provider
        • Session Sharing with ASP.NET
      • SignalR
        • SignalR Core Integration for NCache
      • Response Caching
        • Configure and Use
        • Configure with IDistributedCache
      • Data Caching
        • NCache API
        • IDistributedCache API
      • Data Protection Provider
        • Configure
    • Java Web App Caching
      • Web Sessions
        • Overview
        • Configure App
          • Add Maven Dependencies
          • Deploy Application
        • Multi-site Sessions
    • Node.js App Caching
      • Web Sessions
    • ASP.NET Caching Benefits and Overview
      • ASP.NET Session State Provider Properties
      • Multi-region ASP.NET Session State Provider Configuration
      • Session Sharing between ASP.NET and ASP.NET Core
      • ASP.NET SignalR Backplane
        • NCache Extension for SignalR
      • ASP.NET View State Caching
        • View State Content Optimization Configuration
        • Group View State with Sessions
        • Limit View State Caching
        • Page Level Grouping
      • ASP.NET Output Cache
        • Output Caching Provider Overview
        • Output Cache with Custom Hooks
  • .NET Third Party Integrations
    • Entity Framework (EF) Core
      • Installation
      • Configure
      • EF Core Extension Methods
        • Extension Methods
        • Cache Handle
        • Caching Options
        • Query Deferred API
      • Logging in EF Core
    • Entity Framework EF 6
      • EF Second Level Cache
      • EF Caching Resync Provider
      • EF Caching Configuration File
    • NHibernate
      • Second Level Cache
      • Query Caching
      • Synchronize Database with Cache
    • Debug NCache Providers in Visual Studio
  • Java Third Party Integrations
    • Hibernate
      • Second Level Cache
      • Configure Cacheable Objects and Regions
      • Configure Application
      • Query Caching
    • Spring
      • Overview
      • Use NCache with Spring
        • Configure Generic Provider
        • Configure JCache Spring Caching Provider
        • Configure Caching Declaration
        • Configure Spring Sessions
    • JCache API
      • CRUD Operations
      • Expiration
      • Events
  • Third-Party Wrappers
    • AppFabric to NCache Migration
      • AppFabric API vs. NCache API
      • Configuration Differences Between AppFabric and NCache
      • Migrating from an AppFabric Application to NCache
    • Redis to NCache Migration
      • Redis to NCache Migration
    • Memcached Wrapper
      • Memcached Gateway Approach
      • Memcached Client Plugin for .NET

Add Data to Cache

After successfully connecting to the cache and gaining a valid cache handle, you can add data to the cache. NCache provides the Add method and its overloads to facilitate adding objects to cache for the first time.

Note

This feature is also available in the NCache Community Edition, except for asynchronous operations.

Prerequisites

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • For API details, refer to: ICache, Add, Insert, CacheItem, CacheItemVersion, Count, Contains, AddBulk, AddAsync.
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • For API details, refer to: Cache, add, insert, CacheItem, CacheItemVersion, getCount, addAsync, insertBulk, insertAsync.
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • For API details, refer to: Cache, CacheItem, CacheItemVersion, add, add_bulk, add_async, insert, insert_bulk, insert_async.
  • To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
  • For API details, refer to: Cache, CacheItem, CacheItemVersion, add, addBulk, insert, insertBulk.
  • Install either of the following NuGet packages in your .NET client application:
    • Enterprise: Install-Package Alachisoft.NCache.SDK -Version 4.9.1.0
    • Professional: Install-Package Alachisoft.NCache.Professional.SDK -Version 4.9.1.0
  • Create a new Console Application.
  • Make sure that the data being added is serializable.
  • Add NCache References by locating %NCHOME%\NCache\bin\assembly\4.0 and adding Alachisoft.NCache.Web and Alachisoft.NCache.Runtime as appropriate.
  • Include the Alachisoft.NCache.Web.Caching namespace in your application.
  • To learn more about the NCache Legacy API, please download the NCache 4.9 documents available as a .zip file on the Alachisoft Website.

Add Object to Cache

You can add an object of a custom class to the cache using various overloads of the Add method.

Warning

If the key already exists, "The specified key already exists" exception will be thrown.

The following example adds an object of the Product class and its associated key into the cache.

Tip

One quick way to verify whether an item has been added is to use either of the following properties of the Cache class:

  • Count returns the number of items present in the cache.
  • Contains verifies if a specified key exists in the cache.
  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
// Precondition: Cache is already connected
// Get customer from database
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB(customerKey);

// Get customer from database if not found in cache
if (customer == null)
{
    // Get customer from database
    customer = FetchCustomerFromDB("ALFKI");
    cache.Add(customerKey, customer);
}
// Item added in cache successfully
// Precondition: Cache is already connected
// Get customer from database
String customerKey = "ALFKI";
Customer customer = fetchCustomerFromDB(customerKey);

// Get product from database against given product ID
if (customer == null) {
    // Fetch customer from database
    customer = fetchCustomerFromDB("ALFKI");
    cache.insert(customerKey, customer);
}
// Item added in cache successfully
# Precondition: Cache is already connected

# Get product from database against given product ID
product = fetch_product_from_db(1001)

# Generate a unique cache key for this product
key = "Product:" + product.get_product_id()

# Add Product object to cache
version = cache.add(key, product)

# Item added in cache successfully
// This is an async method
// Precondition: Cache is already connected

// Get product from database against given product ID
product = await this.fetchProductFromDB(1001);

// Generate a unique cache key for this product
var key = "Product:" + product.getProductID();

// Add Product object to cache
var version = await this.cache.add(key, product);

// Item added in cache successfully
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected

// Get customer from database
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB(customerKey);

// Get customer from database if not found in cache
if (customer == null)
{
    // Get customer from database
    customer = FetchCustomerFromDB("ALFKI");
    cache.Add(customerKey, customer);
}
// Item added in cache successfully
Note

To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.

Add An Object With Expiration

You can add data with metadata to the cache by encapsulating it in the NCache CacheItem class.

The following example adds a basic CacheItem containing the Customer object into the cache. Additional properties will be set against the CacheItem in successive chapters.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
// Precondition: Cache is already connected
// Get customer from database if not found in cache
if (customer == null)
{
    string customerKey = $"Customer:ALFKI";
    Customer customer = FetchCustomerFromDB(customerKey);
    // You can use CacheItem object to add metadata along with data to cache
    // CacheItem comprises of certain properties such as Expiration which are explained in successive chapters
    CacheItem customerCacheItem = new CacheItem(customer);
    customerCacheItem.Expiration = new Expiration(ExpirationType.Sliding, TimeSpan.FromMinutes(5));
    cache.Add(customerKey, customerCacheItem);
}
// Precondition: Cache is already connected
// Get customer from database if not found in cache
String customerKey = "ALFKI";
Customer customer = fetchCustomerFromDB(customerKey);

if (customer == null) {
 customer = fetchCustomerFromDB("ALFKI");
}

// You can use CacheItem object to add metadata along with data to cache
// CacheItem comprises of certain properties such as Expiration which are explained in successive chapters
CacheItem customerCacheItem = new CacheItem(customer);
customerCacheItem.setExpiration(new Expiration(ExpirationType.Sliding, TimeSpan.FromMinutes(5)));
cache.add(customerKey, customerCacheItem);
# Precondition: Cache is already connected
# Get customer from database if not found in cache
customer = fetch_customer_from_db(ALFKI)
key = "Customer:" + customer.get_customer_id()

# You can use CacheItem object to add metadata along with data to cache
# CacheItem comprises of certain properties such as Expiration which are explained in successive chapters
cache_item = ncache.CacheItem(customer)
version = cache.add(key, cache_item)
// Precondition: Cache is already connected
// This is an async method
// Get customer from database against given customer ID
customer = await this.fetchCustomerFromDB(ALFKI);
var key = "Customer:" + customer.getCustomerID();

// You can use CacheItem object to add metadata along with data to cache
// CacheItem comprises of certain properties such as Expiration which are explained in successive chapters
var cacheItem = new ncache.CacheItem(customer);
var version = await this.cache.add(key,cacheItem);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
if (customer == null)
{
    // Get customer from database if not found in cache
    string customerKey = $"Customer:ALFKI";
    Customer customer = FetchCustomerFromDB(customerKey);
    // You can use CacheItem object to add metadata along with data to cache
    // CacheItem comprises of certain properties such as Expiration which are explained in successive chapters
    CacheItem customerCacheItem = new CacheItem(customer);
    cache.Add(customerKey, customer, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 5, 0), CacheItemPriority.Default);
}

Add Bulk Items To Cache Data

AddBulk adds an array of CacheItem to the cache with the corresponding cache keys. This method returns a dictionary of all the keys that failed to add, along with the failure reason.

Note

For any keys that fail to add, the failure reason will be returned as an IDictionary.

The following code adds a bulk of product items to the cache. If there are any keys that failed to add, the keys can be handled according to your business needs.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
// Precondition: Cache is already connected
// Create an array of all Customer Keys
String[] keys = new String[]
{
    "Customer:ALFKI", "Customer:ANATR", "Customer:ANTON", "Customer:AROUT", "Customer:BERGS"
};

// Get items from cache
IDictionary<string, CacheItem> itemsFetched = cache.GetCacheItemBulk(keys);

// Fetch items from DB which do not exist in Cache
if (itemsFetched.Count < keys.Length)
{
    // Create dictionary of items to be added to cache
    IDictionary<string, CacheItem> missingItems = new Dictionary<string, CacheItem>();

    foreach (string key in keys)
    {
        if (!itemsFetched.ContainsKey(key))
        {
            Customer customer = FetchCustomerFromDB(key);
            CacheItem cacheItem = new CacheItem(customer);
            missingItems.Add(key, cacheItem);
        }
    }

    // Add bulk items to Cache
    IDictionary<string, Exception> keysFailedToAdd = cache.AddBulk(missingItems);

    if (keysFailedToAdd.Count > 0)
    {
        foreach(KeyValuePair<string,Exception> keyFailedToAdd in keysFailedToAdd)
            Console.WriteLine($"Could not add Item {keyFailedToAdd.Key} in cache due to error : {keyFailedToAdd.Value}");
    }
}
// Precondition: Cache is already connected
List<String> keys = List.of(
        "Customer:ALFKI",
        "Customer:ANATR",
        "Customer:ANTON",
        "Customer:AROUT",
        "Customer:BERGS"
);

// Get items from cache
Map<String, CacheItem> itemsFetched = cache.getCacheItemBulk(keys);

// Fetch items from DB which do not exist in Cache
if (itemsFetched.size() < keys.size()) {
    // Create dictionary of items to be added to cache
    Map<String, CacheItem> missingItems = new HashMap<>();

    for (String key : keys) {
        if (!itemsFetched.containsKey(key)) {
            Customer customer = fetchCustomerFromDB(key);
            CacheItem cacheItem = new CacheItem(customer);
            missingItems.put(key, cacheItem);
        }
    }

    // Add bulk items to Cache
    Map<String, Exception> keysFailedToAdd = cache.addBulk(missingItems);

    if (keysFailedToAdd.size() > 0) {
        for (Map.Entry<String, Exception> keyFailedToAdd : keysFailedToAdd.entrySet()) {
            System.out.println("Could not add Item " + keyFailedToAdd.getKey() + " in cache due to error: " + keyFailedToAdd.getValue());
        }
    }
}
# Precondition: Cache is already connected
# Fetch all products from database
products = fetch_products_from_db()

# Create map of items to be added to cache
dictionary = {}

for product in products:
    key = "Product:" + product.get_product_id()
    cache_item = ncache.CacheItem(product)

    # Add items to dictionary
    dictionary[key] = cache_item

keys_failed_to_add = cache.add_bulk(dictionary)

if len(keys_failed_to_add) > 0:
    for entry in keys_failed_to_add:
        if not keys_failed_to_add[entry]:
            value = False
else:
    # Any other exception
    value = True
// Precondition: Cache is already connected
// This is an async method
// Fetch all products from database
var products = await this.fetchProductFromDB();

// Create map of items to be added to cache
var dictionary = new map();

products.forEach(prod => {
    var key = "Product:" + this.product.getProductID();
    var cacheItem = new ncache.CacheItem(prod);

    // Add items to dictionary
    dictionary.set(key,cacheItem);
});

var keysFailedToAdd = this.cache.addBulk(dictionary);

if(keysFailedToAdd.size() > 0)
{
    keysFailedToAdd.forEach(entry => {
        if(entry.getValue() == false)
        {
            var value = false;
        }
        else
        {
            // Any other exception
        }
    });
}
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Create an array of all customer keys
String[] keys = new String[]
{
    "Customer:ALFKI", "Customer:ANATR", "Customer:ANTON", "Customer:AROUT", "Customer:BERGS"
};

// Get items from cache
IDictionary itemsFetched = cache.GetBulk(keys);

// Fetch items from DB which do not exist in cache
if (itemsFetched.Count < keys.Length)
{
    // Create dictionary of items to be added to cache
    IDictionary<string, CacheItem> missingItems = new Dictionary<string, CacheItem>();

    foreach (string key in keys)
    {
        if (!itemsFetched.Contains(key))
        {
            Customer customer = FetchCustomerFromDB(key);
            if (customer != null)
            {
                CacheItem cacheItem = new CacheItem(customer);
                missingItems.Add(key, cacheItem);
            }
        }
    }

    string[] missingKeys = new string[missingItems.Count];
    CacheItem[] missingCacheItems = new CacheItem[missingItems.Count];
    int index = 0;
    foreach (var keyValuePair in missingItems)
    {
        missingKeys[index] = keyValuePair.Key;
        missingCacheItems[index] = keyValuePair.Value;
        index++;
    }

    // Add bulk items to cache
    IDictionary keysFailedToAdd = cache.AddBulk(missingKeys, missingCacheItems);

    if (keysFailedToAdd.Count > 0)
    {
        foreach (DictionaryEntry entry in keysFailedToAdd)
        {
            Console.WriteLine($"Could not add Item {entry.Key} in cache due to error: {entry.Value}");
        }
    }
}

Add Objects with Asynchronous API

AddAsync adds an item to the cache asynchronously and returns an object of the Task class which can be further used according to the business needs of the client application.

  • .NET
  • Java
  • Python
  • Legacy API
// Precondition: Cache is already connected
if (customer == null)
{
    string customerKey = $"Customer:ALFKI";
    Customer customer = FetchCustomerFromDB(customerKey);

    // Adding item asynchronously. You can also add data by creating a CacheItem object which stores meta data as well
    Task<CacheItemVersion> task = cache.AddAsync(customerKey, customer);

    // This task object can be used as per your business needs
    if (task.IsCompleted)
    {
        // Get CacheItemVersion object from task result
        CacheItemVersion version = task.Result;
        Console.WriteLine($"Item {customer.CustomerID} has been added to cache with verion {version.Version}.");
    }
}
// Precondition: Cache is already connected
String customerKey = "Customer:ALFKI";
Customer customer = fetchCustomerFromDB(customerKey);
cache.addAsync(customerKey, customer).get();
# Precondition: Cache is already connected
# Get product from database
    product = fetch_product_from_db()

    # Generate a unique cache key for this product string
    key = f"Product:1001"

    # Add Product object to cache asynchronously
    async def add_async():
        task = cache.add_async("key", "product")
        value = await task

asyncio.run(add_async())
# This task object can be used as per your business needs
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB(customerKey);

CacheItem cacheItem = new CacheItem(customer);
// Adding item asynchronously. You can also add data by creating a CacheItem object which stores meta data as well
cache.AddAsync(customerKey, cacheItem, DSWriteOption.None, null);
Console.WriteLine($"Item {customer.CustomerID} has been added to cache.");

Using ICache.Add for Distributed Locking

Due to its versatile nature, another wide use of Add operation is in locking the cache if it is being used by multiple applications.

For example, an environment is set such that as soon as any application connects to the cache, it adds a specific key that is known to all applications. And once the application is done using the cache, it removes the key from the cache. If the key is added successfully, it can proceed to use the cache according to its logic. However, if the key already exists, it means the cache is already being used by an application and is "locked".

This is described in steps in the following diagram:

Add Data to Cache

  1. App A and App B add the "WorkStarted" key as soon as the application is started.

  2. The key passed by App A is added to the cache before the one passed by App B.

  3. App B gets a "The specified key already exists" exception. In this scenario, App B will wait for App A to finish its work, i.e., until it can successfully add the "WorkStarted" key.

  4. App A removes the key from the cache once done with its work.

  5. App B adds the key to the cache again.

  6. The key is added by App B successfully, locking the cache for other applications.

Additional Resources

NCache provides the sample application for Basic Operations on GitHub.

See Also

.NET: Alachisoft.NCache.Client namespace.
Java: com.alachisoft.ncache.client namespace.
Python: ncache.client class.
Node.js: Cache class.

In This Article
  • Prerequisites
  • Add Object to Cache
    • Add An Object With Expiration
  • Add Bulk Items To Cache Data
  • Add Objects with Asynchronous API
  • Using ICache.Add for Distributed Locking
  • Additional Resources
  • See Also

Contact Us

PHONE

+1 (214) 764-6933   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • NCache Enterprise
  • NCache Community
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top