• Facebook
  • Twitter
  • Youtube
  • LinedIn
  • RSS
  • Docs
  • Comparisons
  • Blogs
  • Download
  • Contact Us
Download
Show / Hide Table of Contents

.NET Client

This section demonstrates how to quickly set up and use an NCache client in a .NET application after a cache has already been created and started. It covers installing the client NuGet package, initializing a cache handle, and performing common operations including basic caching, Tag-based retrieval, SQL queries, and event notifications.

Prerequisites

Before proceeding, ensure your environment meets the following requirements:

  • Existing Cache: A running cache (e.g., demoCache) must already be created on an NCache server.
  • .NET Version: The recommended target framework is .NET 10.0. For all supported .NET versions, refer to Supported .NET Versions.
  • NCache Installation: You must have NCache Enterprise installed on your cache servers. For the client machine, you only need the client libraries.
  • Cache Connectivity: Ensure network access to the cache servers (IP address and port, typically 9800).
  • Data being cached is serializable.
  • Exception handling is in place as described in Handling Failures.

Install Client (Optional)

If your application runs on a machine that does not have a full NCache setup, you can install the NCache Client separately.

NCache provides a Windows Installer (.msi) with which you can install NCache through command line silent mode.

  • Search for Command Prompt on the Windows Start menu. Right-click on the search result Command Prompt, and select Run as Administrator.

  • You can install either Cache Server, Developer/QA, or Remote Client. For instance, for Remote Client mode, set the InstallMode=3 in the following command:

msiexec.exe /I "C:\NCacheSetupPath\ncache.ent.net.x64.msi" INSTALLMODE=3 /qn

Setup .NET Client

Open Visual Studio and go to Tools → NuGet Package Manager → Package Manager Console. Install the NCache SDK package corresponding to your NCache server installation version:

Install-Package Alachisoft.NCache.SDK -Version x.x.x
Note

Please refer to the NCache Downloads page for the latest NCache version.

To add additional NuGet packages for .NET integrations such as Sessions, SignalR, Response Caching, Data Protection Provider, etc., please see Install NuGet Packages for .NET Clients documentation.

Code samples

The following samples demonstrate how to perform core caching operations using the NCache .NET API.

Data Caching

Once connected to the cache, you can start adding application data as key-value pairs. The following example demonstrates how to connect to the cache and add an object:

using Alachisoft.NCache.Client;

// Connect to cache
ICache cache = CacheManager.GetCache("demoCache");

// Create item
var product = new Product(1005, "Laptop", 1500, "Electronics");
var cacheItem = new CacheItem(product);

// Add to cache
cache.Add("1005", cacheItem);
Console.WriteLine("Item 1005 successfully added to demoCache.");

// Dispose cache
cache.Dispose();

[Serializable]
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public double Price { get; set; }
    public string Category { get; set; }

    public Product(int id, string name, double price, string category)
    {
        Id = id;
        Name = name;
        Price = price;
        Category = category;
    }
}

For details on basic cache functionality, refer to the Basic Operations documentation.

Tags

Tags allow you to categorize your data with meaningful keywords, making it easier to retrieve or manage related items in groups. Instead of relying solely on unique keys, you can label items (e.g., "Electronics" or "Sale") and perform operations on all items sharing that label.

The following code associates searchable keywords (Tags) to a CacheItem as metadata before storing it in the cluster. It then uses the SearchService to perform a grouped lookup, retrieving multiple related objects at once without needing their individual keys.

...
using Alachisoft.NCache.Runtime.Caching;

// Connect to NCache
ICache cache = CacheManager.GetCache("demoCache");

var product = new Product(1002, "Phone", 800, "Electronics");

// Wrap the object in CacheItem
var item = new CacheItem(product){
    Tags = new[]{ new Tag("Electronics"), new Tag("Mobile")}
};

// Insert into cache
cache.Insert("1002", item);

// Retrieve by tag
IDictionary<string, Product> results =
    cache.SearchService.GetByTag<Product>(new Tag("Mobile"));

Console.WriteLine($"Items found with tag 'Mobile': {results.Count}");
...

For more information on using tags, please see Tags documentation.

SQL

NCache provides a powerful SQL-like searching mechanism. You can search for objects in the cache based on their attributes using standard query syntax. The following code executes a parameterized SQL-like query on the cache to retrieve objects matching specific criteria (price and category).

...
ICache cache = CacheManager.GetCache("demoCache");

string query = "SELECT $VALUE$ FROM FQN.Product WHERE Price > ? AND Category = ?";

var queryCommand = new QueryCommand(query);

// Add parameters in the same order as the placeholders
queryCommand.Parameters.Add("Price", 500);
queryCommand.Parameters.Add("Category", "Electronics");

// Execute the query
ICacheReader reader = cache.SearchService.ExecuteReader(queryCommand);

while (reader.Read())
{
    string key = reader.GetValue<string>(0);

    Product p = cache.Get<Product>(key);

    if (p != null)
    {
        Console.WriteLine($"Found Product ID: {p.Id}");
    }
}
...

Events

NCache allows your application to receive notifications when specific cache items are modified. Item-level events are useful when you want to monitor a particular key and respond when that item is updated or removed from the cache.

The following example demonstrates how to register Item-level notifications for a specific item and handle the ItemUpdated event:

...
using Alachisoft.NCache.Runtime.Events;

// Connect to cache
ICache cache = CacheManager.GetCache("demoCache");

// Add an item first, because the key must already exist
var product = new Product(1005, "Laptop", 1500, "Electronics");
string key = "Product:1005";
cache.Add(key, new CacheItem(product));

// Create callback
var dataNotificationCallback = new CacheDataNotificationCallback(OnCacheDataModification);

// Register item-level notifications for update operations
cache.MessagingService.RegisterCacheNotification(key, dataNotificationCallback, EventType.ItemUpdated, EventDataFilter.DataWithMetadata);

// Update item to trigger ItemUpdated event
product.Price = 1750;
cache.Insert(key, new CacheItem(product));

Console.WriteLine("Item-level event notifications registered successfully.");

// Callback method that is invoked when a registered cache item is modified
static void OnCacheDataModification(string key, CacheEventArg args)
{
    switch (args.EventType)
    {
        case EventType.ItemUpdated:
            Console.WriteLine($"Item with key '{key}' has been updated in cache '{args.CacheName}'.");

            if (args.Item != null)
            {
                Product updatedProduct = args.Item.GetValue<Product>();
                Console.WriteLine($"Updated product: {updatedProduct.Name}, Price: {updatedProduct.Price}");
            }
            break;
    }
}
...
Important

After running the application or performing cache operations, NCache generates log files that can be used for monitoring and troubleshooting. By default, the log files are generated at the following location: %NCHOME%\log-files. Log file locations may vary if a custom installation directory was selected during NCache setup.

Note

For more details on using NCache, please refer to the Developer's Guide.

See Also

NCache Installation Guide
NCache Developer's Guide
NCache Command Line Interface

Contact Us

PHONE

+1 214-619-2601   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • 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 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top