Use from .NET Application
After successfully configuring NCache, you can start developing the application by embedding NCache API calls. NCache client applications can communicate with the cache servers through InitializeCache
method. This method establishes connection between client and server and returns a cache handle. This cache handle can then be further used for Add, Insert, Get, Remove and other cache operations.
Let's quickly create a console .NET application to demonstrate the use of NCache.
Step 1:
Launch Visual Studio 2010+ for .NET Framework (VS 2017 Preview 2+ for .NET Core)
Step 2:
Create a new Console Application for .NET Framework (or .NET Core)
Step 3:
- For NCache Open Source Edition, install NCache NuGet package on Package Manager Console as following:
Install-Package Alachisoft.NCache.OpenSource.SDK -Version 4.9.1
- For NCache Professional Edition, install NCache NuGet package on Package Manager Console as following:
Install-Package Alachisoft.NCache.Professional.SDK -Version 4.9.1
Step 4:
Select "Add->Class" menu from Solutions to create a new class Product as following:
[Serializable]
public class Product
{
public int ProductID { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public int Price { get; set; }
}
Step 5:
Add the following namespace to your Program.cs file or similar:
using Alachisoft.NCache.Web.Caching;
Step 6:
Copy/paste the following code to your Programs.cs or similar to quickly test NCache.
using System;
using Alachisoft.NCache.Web.Caching;
class TestApp
{
public static void Main(string[] args)
{
// Set the name of the cache your application needs to talk to
string cacheId = "demoClusteredCache";
// Here you get cache handle by initializing cache
Cache cache = NCache.InitializeCache(cacheId);
// Let's create Product class object to be added to the cache
Product product = new Product()
{
ProductID = 1001,
ProductName = "Dell Inspiron",
Category = "Computers",
Price = 600
};
// Create a cache item to be put into the cache.
// You can set expiration, tags etc with cache item. See NCache API reference.
CacheItem cacheItem = new CacheItem(product);
// Cache is a key-value store.
// Every cache item is uniquely identified by its cache key.
string cacheKey = $"Product:{product.ProductID}";
// To put an item into the cache, you can use both Add and Insert methods
cache.Add(cacheKey, cacheItem);
// Let's update the product price
product.Price = 550;
cacheItem.Value = product;
// Insert is used to update the existing cache items
cache.Insert(cacheKey, cacheItem);
// Get cache item from cache
product = cache.Get(cacheKey) as Product;
// You can call Remove or Delete method to remove a cache item from cache
cache.Delete(cacheKey);
}
}
Step 7:
Compile and run your program.
See Also
Create a Cache
Add Local/Remote Clients
Simulate Cache Usage
Monitor Caches in PerfMon
Use NCache for ASP.NET Sessions
NCache Programmer's Guide