Topic: NCache

Alachisoft NCache 4.1
Next page >

NCache

Welcome to NCache version 4.1. NCache is a caching solution that provides high performance and scalability. NCache provides a set of services and API's that incorporates various user needs of caching.
NCache package contains samples, tutorials, and tools designed to help you incorporate NCache in your applications. Package also provides a documentation that includes an extensive class library reference, conceptual overviews and step-by-step illustrations to assist you in understanding NCache more effectively.
In NCache Documentation
Introduction to NCache
Presents a brief introduction to NCache, with an emphasis on new and old features, editions and requirements of NCache.
Installation Guide
The Installation Guide provides you the most comprehensive information about installation, prerequisites and system configuration.
Getting Started
Familiarizes you with the fundamentals of NCache and offers help to use NCache quickly and efficiently.
Configuring NCache
Discusses configuration options that NCache provides for both local and clustered caches. It also helps in configuring NCache through NCache Manager and configuration files.
Developing with NCache
Focuses on what is essential to become skilled at developing with NCache. It includes programmers guide, sample applications, hands on tutorials and extensive help on API reference.
Troubleshooting
Helps in troubleshooting different problems that may arise while using NCache.
Send comments on this topic.
Next page >
Copyright © 2005-2012 Alachisoft. All rights reserved.


Topic: Introduction to NCache

< Previous page Next page >

Introduction to NCache

NCache is a clustered caching solution that makes sharing and managing data in a cluster as simple as on a single server. It accomplishes this by coordinating updates to the data using cluster-wide concurrency control and replicating and distributing data modifications across the cluster using the highest performing clustered protocol available. The primary purpose of NCache is to help improve performance of .NET applications that would otherwise make expensive trips to database systems, web services, mainframes, or other systems across the network.
In This Section
What's New in 4.1?
Updates you with new features in the latest version of NCache.
Dynamic Clustering
Gives an overview of dynamic clustering in NCache.
Caching Topologies
Gives an overview of various topologies.
Feature Highlight
Describes various features that NCache provides.
Support for .NET & ASP.NET Apps
Describes .NET and ASP.NET application support in NCache.
Support for Java & JSP Apps
Describes Java & JSP application support in NCache.
Copyright ©
Gives the copyright statement for NCache.
See Also
Getting Started
Familiarizes you with the fundamentals of NCache and offers help to use NCache quickly and efficiently.
Configuring the Cache
Discusses configuration options that NCache provides for local and clustered caches. It also helps in configuring NCache through NCache Manager and configuration files.
Developing with NCache
Focuses on what is essential to become skilled at developing with NCache. It includes programmers guide, sample applications, hands on tutorials and extensive help on API reference.
Send comments on this topic.
< Previous page Next page >


Topic: What's New in NCache 4.1?

What's New in NCache 4.1?

NCache 4.1 brings many new features and enhances graphical user interface to the next level. Here is a brief overview of what's new in NCache 4.1:
In-proc Client Cache support in Java :
NCache is now providing support for In-proc Client Cache in Java which was not available in previous versions of NCache.
Read-Thru and Write-Thru providers support in Java:
Develop multiple Read-Thru/Write-Thru providers and register it with NCache. You can use a specific provider from each of your java application. You are also facilitated to use NCache Manager to deploy your Read-Thru/Write-Thru handlers even at runtime. Your assemblies are automatically copied to all the cache servers.
Data Sharing between .net and Java:
With Data Sharing you can share cache content among NCache .Net and NCache Java editions. This sharing can be achieved through binary compact serialization. To use this feature user must have both NCache .net and NCache java editions installed.
Class Versioning in same platform:
Using Class Versioning you can share class data among various versions of a class with in a same platform. Here mapping of attributes is done at run time.
Support for Dynamic Compact Serialization in Java :
Use a faster and more compact serialization than regular Java serialization and without writing any custom code for it. NCache generated serialization code at runtime and even lets you serialize objects that are otherwise not serializable.
Support for Named Tags in .NET:
NCache can associate a dictionary of named tags with cache items. Items can be objects or text data. Named Tags helps in indexing the data on the basis of tags and you can query indexed data using tags.
Support for Named Tags in Java:
NCache can associate a dictionary of named tags with cache items. Items can be objects or text data. Named Tags helps in indexing the data on the basis of tags and you can query indexed data using tags.
Cache Startup Option:
Using Cache Startup option if the cache is specified to be a startup cache, it will get started automatically on service startup. No manual start is required for the cache.
Support for Continuous Query in .NET:
NCache provides Continuous Query support for both .Net and Java clients. It notifies about the changes occur in query result set and therefore client applications need not to re-query the data for updates.
Support for Continuous Query in Java:
NCache provides Continuous Query support for both .Net and Java clients. It notifies about the changes occur in query result set and therefore client applications need not to re-query the data for updates.
Bridge (Enhanced):
An enhanced bridge feature is introduced having support for multiple topologies. It performs an asynchronous replication of data from one on-site cache to one/multiple on-site/off-site disaster recovery cache(s) across the WAN.
Support for CacheLoader in Java:
Develop Cache Startup Loader and register it with NCache. Using Cache Startup Loader you can preload the cache with the base data before start using the cache. You are also facilitated to use NCache Manager to deploy your CacheLoader handler even at runtime. Your assemblies are automatically copied to all the cache servers.
Dumpcache Tool for Java:
Java clients can use dumpcache utility to dumps the available cache keys to Console or given output file.
Support for Hibernate in Java:
NCache provides a second level or process level distributed cache for Hibernate. You can plug-in NCache as your cache provider with Hibernate applications.
Support for Spring in Java:
NCache is providing support for Spring framework applications. You can cache spring applications data using NCache to improve the performance of an application.
Bridge Conflict Resolver for .Net:
Bridge Conflict Resolver resolves the conflict occur while replicating the data from bridge to cache.
Bridge Conflict Resolver for Java:
Bridge Conflict Resolver is introduced to resolve the conflict occur between existing operations and operation replicated from bridge to cache.
See Also
Dynamic Clustering | Caching Topologies | Copyright ©


Topic: Self Healing Dynamic Clustering

Self Healing Dynamic Clustering

NCache has a self-healing dynamic clustering capability based on a peer-to-peer cluster architecture. NCache does not use Windows Clustering or any other OS-based clustering but instead creates its own TCP based dynamic cluster of cache servers. The purpose of this dynamic cluster is to provide you 100% uptime by allowing you to add or remove cache servers from the cluster at runtime without stopping the dynamic cluster.
With dynamic clustering you can get the following capabilities:
  • 100% uptime for the cluster due to peer to peer architecture
  • Add or remove cache servers at runtime without stopping the cache
  • Can perform load balancing for client connections to cache servers (at connection time)
  • Clients automatically reconnect to a different cache server if their server goes down
NCache provides a dynamic clustering capability with 100% uptime for the cluster. This is due to a peer to peer architecture of the cluster where there is no single point of failure.
A cache cluster is a collection of one or more cache servers with every server connected to every other server in the cluster. When a cache cluster is formed, it contains a cluster coordinator that manages all membership to the cluster. The coordinator is the oldest server in the cluster (meaning the first server that started). If the coordinator ever goes down, this role passes on to the next senior-most server in the cluster. This removes any single point of failure in cluster membership management.
You can find out more detail on our website for Self Healing Dynamic Clustering .
See Also
Caching Topologies


Topic: Caching Topologies

Caching Topologies

A caching topology is essentially data storage strategy in a clustered cache. NCache provides a rich set of caching topologies to let you choose the one that suits your environment best. The goal of this is to cater from very small two-server caches to very large cache clusters consisting of hundreds of cache servers. Below are the main caching topologies provided to you:
  • Mirrored Cache (2-server active/passive)
  • Replicated Cache
  • Partitioned Cache
  • Partitioned-Replica Cache (Asynchronous and Synchronous)
  • Client Cache (a Local Cache connected to a Clustered Cache)
Each of these caching topologies is explained in more detail below.
Reference Data versus Transactional Data:
Reference data use means you cache something once and read it over and over again. So, there are a lot more reads than writes. On the other hand, transactional data use means that you're updating the data as frequently as you're reading it (or fairly close to it). Originally, cache was considered good only for reference data but distributed caches have proven to be faster and more scalable than databases even for transactional data.
Caching a product catalog where prices change maybe once a day or so is reference use. On the other hand, ASP.NET Session State and JSP Servlet session storage is considered a transactional use.
All topologies are good for reference data but only some topologies are good for transactional data. You need to determine how many updates you'll be doing to figure out which topology is best for you. Below is a list.
Mirrored Cache
A Mirrored Cache is a 2-server active/passive cache cluster. In mirrored cache there is one active and one passive node only and no client can connect with passive unless it is active. Primarily passive node is used to keep asynchronous backup of data. A mirrored cache has no clustering cost, besides it gives data reliability through backup. By default, ImportHashmap flag will be false as in this topology client is not aware of data distribution between servers.
  • Reference data : Good. Max 30000 reads/sec (1k size).
  • Transactional data : Good. Max 20000 writes/sec (1k size).
Replicated Cache
A Replicated Cache consists of two or more cache servers in a cluster (there is no limit for number of nodes however, recommendation is for maximum three). It is suitable for situations where transactional data usage is lesser than reference data usage. Performance can slow down in transactional data because updates are applied synchronously on all the other servers in the cluster. Moreover, performance can diminish when more nodes are added in cluster. By default, ImportHashmap flag will be false.
  • Reference data : Good. 30000 reads/sec per server. Grow linearly by adding servers.
  • Transactional data : Not so good. Max 2500 writes/sec. Drops if you add 3rd server.
Partitioned Cache (no replication):
A Partitioned Cache is intended for larger cache clusters as it is a very scalable caching topology. It is suitable in cases where performance is your major concern but without reliability of data. If any cache server goes down, data will be lost of that node as there is no replication/backup of data. Client gets connected with each server and request is sent to the targeted server only because client is aware of data distribution flanked by servers. By default, ImportHashmap flag will be true as client is data aware.
  • Reference data : Good. 30000 reads/sec per server. Grow linearly by adding servers.
  • Transactional data : Good. 25000 writes/sec per server. Grow linearly by adding servers.
Partition-Replica Cache (with replication):
Partitioned-Replica topology is combination of Partitioned topology and Replicated topology. It gives high performance with Reliability of data through replication and scalability through partitioning. It is suitable in cases where performance is major concern without fear of data loss. Partitioned-Replica provides both sync and async replication whereas, async replication is the default option. Async replication is quick for the reason that user doesn’t have to wait for operation to be done on replica as well. By default, ImportHashmap flag will be true.
  • Reference data : Good. 30000 reads/sec per server. Grow linearly by adding servers.
  • Transactional data : Good. 20000 writes/sec per server. Grow linearly by adding servers.
There is some overlap between Mirrored Cache and Partition-Replica Cache for 2-server clusters because both provide similar performance with replication. But, Mirrored Cache accommodates situations where you only have one dedicated cache server and the mirror server is being shared with other apps. But, if you have a need for 3 or more cache servers, then Partition-Replica Cache is the best choice for transactional use.
Note: It is recommended to create a cache of at least 20% greater size than the actual data size.
Read more detail on our website about Caching Topologies .
See Also
Dynamic Clustering


Topic: Features Highlights

Features Highlights

Below are some features of NCache. Have a look at them:
Light-weight .NET Client
NCache now has a light-weight client that is more scalable and faster than 3.0. This light-weight client uses our own socket level protocol to talk to NCache server (either locally or remotely).
Light-weight Java Client
NCache does not rely on any Java-to-.NET interoperability bridge and instead uses its own socket level protocol to talk to the NCache server (just like the .NET light-weight client). Now you can have your Java applications use NCache as a clustered object cache. This protects your investment in NCache and allows you to keep one cache deployed and used by multiple applications. Java client works the same way as .NET client. The Java client can run on any Java compatible platform.
Failover in Remote Light-weight Clients
Both Java and .NET light-weight clients have failover capability. This means that if the primary server they're connected to goes down, they'll automatically connect to another server in the cluster. And, you can specify the priority of these servers for each client differently. Additionally, when new servers are added or removed at runtime, this information is passed on to the remote clients so they can use them for failover as well.
Security
NCache now provides security with authentication and authorization built into the product. Authentication is done through LDAP. NCache allows you to specify administrators and users. Administrators can manage the cluster while the users can only make runtime API calls to a specific cache.
Now NCache allows you to save data in encrypted form in order to secure your data. For this 3DES Encryption algorithm is used.
Application Connects to Multiple Caches
NCache client applications can now connect to multiple caches simultaneously. This allows you to keep multiple caches for different purposes and share them across applications more effectively.
Multi-key Event Notifications
Applications can register interest into multiple items in the cache to be notified when they're updated or removed. Then, whenever these items are updated or removed, the client application is notified anywhere in the cluster.
Synchronize Items in Multiple Caches
A new cache dependency called CacheSyncDependency is added that allows items in one cache to be dependent on items in another cache. This way, for example, you can have a Local Cache that keeps items frequently used by your application and a Clustered Cache that keeps a larger number of items being shared with other applications. And, your local items are kept synchronized with the clustered cache so you never have any data integrity problems while improving your app performance even further.
Cluster Management Events
NCache fires events whenever a node joins or leaves the cluster or when a client finds that its server has gone down and it now needs to connect with another server. You can write hooks for these events and take appropriate actions when these events occur.
Cache Management API
You can now manage the cache through API (in addition to NCache Manager and command line tools). You can start or stop a cache from an API now.
Multiple Cache Instances on same Server (TCP Port Range)
You can now run multiple cache instances (as InProc) on the same server without any port conflict. Now, you can specify a range of TCP ports to be used for cache clustering instead of only one port previously. This way, multiple instances of the cache can run with each instance using one port.
Callbacks for Async operations
You can now specify a callback for AddAsync, InsertAsync, and RemoveAsync operations. This callback is called when the operation completes either successfully or with a failure.
Performance Improvement to Partitioned Cache with Replicas
NCache has now optimized communication in the cluster for this topology.
Native .NET Clustering
  • NCache developed natively in .NET
  • Truly scalable peer-to-peer multicasting clustering
  • Automatic and transparent node failure recovery
  • On the fly addition and removal of servers
Caching
  • Easy to understand API
  • Same API for Local or Clustered environments
  • Cache configuration through a graphical tool (NCache Manager)
  • Fixed or variable sized cache
  • Time-to-live expiration of cache entries
  • Fixed-time expiration of cache entries
  • Idle-time expiration of cache entries
  • Least-Recently-Used (LRU), Least-Frequently-Used (LFU), and Priority based Eviction Policies
  • Expired Items Resynchronization
  • SQL and OleDB Cache Dependency
  • Support for custom dependencies
  • Event Notifications in Local and Clustered environments
  • In-process and out-of-process cache configurations
  • Heap, raw memory, memory mapped file, and file based storage options.
  • Intelligent relationship management through File and Key based dependencies
  • Read-through and Write-through caching
  • High performance Write-behind caching
  • Clustered Location Transparency
  • Clustered Lock Management
Clustering Options
  • Replicated Cache
  • Partitioned Cache
  • Client Cache
  • Data-less Nodes
  • UDP and TCP based Cluster
HTTP Clustered Session Management
  • Maintain and synchronize session state throughout a server farm
  • Users can now move from server to server on each http request
  • Achieve optimum load-balancing (no more sticky sessions needed)
  • No single-point-of-failure due to sophisticated clustering topologies
  • Built on top of NCache clustering to true in-memory performance
  • Same API as Clustered Session State
GUI Based Cache Configuration
  • NCache Manager is a Windows GUI
  • Create and manage Local Cache or Clustered Cache from it
  • View rich statistics on the entire clustered cache from a single point
  • Change clustering topology without affecting the client application
  • Add or remove nodes from the cluster at run-time
See Also
What's New in NCache 4.1? | Caching Topologies | Copyright ©


Topic: Support for .NET & ASP.NET Apps

Support for .NET & ASP.NET Apps

NCache has been developed completely in .NET with C#. Therefore, unlike other products that are either developed in Java or C/C++ and only provide a .NET client API, NCache is a 100% native .NET product that fits very nicely in your .NET application environments.
You can use NCache from any .NET application including ASP.NET, WCF and web services, Grid Computing applications, and any other server-type applications with high transactions. So, whether you're making client-side API calls to NCache or developing server-side code for Read-thru/Write-thru, rest assured that you will always be in native .NET environment.
NCache provides support for the following:
  • ASP.NET Session State Storage for web farms
  • ASP.NET Content Acceleration: This includes caching View State and Minify and Merge of JavaScript.
  • ADO.NET Entity Framework 4.0 Cache
  • NHibernate L2 Cache
  • EntLib Caching Block Provider
  • .NET 4.0 Cache Provider
Please visit our website for more detail on Support for .NET .
See Also
Support for Java & JSP


Topic: Support for Java/J2EE & JSP Apps

Support for Java/J2EE & JSP Apps

NCache provides 100% native Java API support for Java applications. You can use NCache from any Java applications including JSP Servlet, web services, Grid Computing applications, and any other server-type applications with high transactions.
NCache Java client uses the same proprietary socket-level protocol to talk to the cache server that the .NET client does. So, the performance and scalability from Java is the same as .NET.
NCache provides the following support for Java:
  • 100% Native Java API
  • JSP Servlet Session Storage
  • Windows & Unix Support
  • Java SE and Java EE Support
  • Hibernate and Spring Support
Please visit our website for more details on NCache support for Java .
See Also
Support for .NET & ASP.NET


Topic: Cache Server Backward Compatibility

Cache Server Backward Compatibility

NCache provides backward compatibility protocol for its older clients. NCache 3.8 onward versions will give you the facility to work with your older clients without re-deploying or re-referencing them with upgraded servers. Backward compatibility will be for onward versions only, any client earlier than 3.8 will not be supported by this protocol. With this feature a client should work with both an older and an upgraded version of the server; otherwise with each updates on server, clients are supposed to be upgraded accordingly.
Upgrading a server for new version involves adding new features of NCache while the existing features remains unchanged. For example an upgraded server can only add new features without changing the older ones. In this way it will not break the compatibility with its older clients.


Topic: Copyright ©

Copyright ©

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the written permission of Alachisoft. Alachisoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Alachisoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. 2011 Alachisoft. All rights reserved. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.
See Also
What's New in NCache 4.1? | Dynamic Clustering | Caching Topologies | Copyright ©


Topic: Installation Guide

Installation Guide

The Installation Guide provides you the most comprehensive information about installation, prerequisites and system configuration. It also provides a detailed, step-by-step guide about how to install NCache using command line installer and interactive window installer.
In This Section
Installation Guide for .Net
Describes comprehensive information about installation, prerequisites and system configuration for NCache installation for .Net.
Installation Guide for Java
Presents comprehensive information about installation, prerequisites and system configuration for NCache installation for Java.
See Also
Introduction to NCache
Presents a brief introduction to NCache, with an emphasis on new and old features, editions and requirements of NCache.
Configuring the Cache
Discusses configuration options that NCache provides for local and clustered caches. It also helps in configuring NCache through NCache Manager and configuration files.
Developing with NCache
Focuses on what is essential to become skilled at developing with NCache. It includes programmers guide and extensive help on API reference.


Topic: .Net Installation Guide

.Net Installation Guide

The Installation Guide provides you the most comprehensive information about installation, prerequisites and system configuration. It also provides a detailed, step-by-step guide about how to install NCache using command line installer and interactive window installer.
In This Section
Getting Started
Describes the pre-requisites for NCache installation.
Command Line Install
Describes how NCache provides a command line installation that can either run from a Command Prompt or add to a script files (.bat files).
Network Install with PowerShell
Describes how to manage NCache remote installation and un-installation tasks on your network through a single computer with the help PowerShell scripts.
Interactive Windows Installer
Describes, how to install NCache using interactive Windows Installer.
Evaluation Period Expiration & Extension
Describes the procedure for extending NCache evaluation period.
Activate NCache Purchased License
Describes how to activate NCache license.
See Also
Introduction to NCache
Presents a brief introduction to NCache, with an emphasis on new and old features, editions and requirements of NCache.
Configuring the Cache
Discusses configuration options that NCache provides for local and clustered caches. It also helps in configuring NCache through NCache Manager and configuration files.
Developing with NCache
Focuses on what is essential to become skilled at developing with NCache. It includes programmers guide and extensive help on API reference.


Topic: Getting Started

Getting Started

NCache provides a Windows Installer Package (.msi) to let you easily install NCache. However, before you install NCache, you need to keep the following in mind.
What to Install during Evaluation?
NCache Enterprise: Regardless of which NCache edition you ultimately end up using, you should do your evaluation with NCache Enterprise. This is because you will be able to see all the features that NCache offers in full and then decide whether you need to downgrade to NCache Professional or stay with NCache Enterprise.
Installation Options
Whether you install NCache Enterprise or Professional, you're given the following installation options when you run the .msi file.
  • Cache Server: This is a full install of NCache and contains everything that other two options provide plus cache clustering capability. You must install this on any servers where you're going to host the cache, regardless of whether you have dedicated or shared cache servers.
  • Remote Client: This installs the remote client libraries and client cache on all your web/app servers so you can access the cache across the network. Please note that you need remote client libraries to access the cache across the network.
  • Developer: This installs the NCache API, online help/documentation, and a local stand-alone cache without any clustering capability. Please note that you cannot access a remotely hosted cache from a developer install machine. You can access only a local cache.
Where to Install NCache?
NCache needs to be installed on the following machines:
  • Production, Staging, QA, or Dev Servers: Install NCache Enterprise Edition on the following.
  • Cache servers (dedicated or shared): If you have 4 or more web/app servers in your environment hosting your application, then we recommend a dedicated caching tier of 2 servers. A dedicated cache cluster should have minimum of 2 servers for replication and then a ratio of 5:1 between your web/app servers and the cache servers. For smaller environments, even using your web/app servers as cache servers is fine, as long as your have enough memory available on these machines.
  • NCache remote clients (app or web servers): Any web/app server that is not hosting the cache server but instead will access it remotely across the network is considered an NCache remote client. You need to install the "remote client" portion of NCache on these machines.
  • Developer Workstations: If you're using NCache for object caching, you will be making NCache API calls within your application. Therefore, you need to install NCache "Developer" portion on all the developer machines. A developer install includes all the NCache API's, online help, and a local stand-alone cache. Please note that you cannot access any cache remotely from a developer install .
System Recommendations
  • Windows 2003/2008 Server (64-bit) as Cache Servers: It is highly recommended that you use 64-bit version of Windows 2003 or 2008 server platform for cache servers even if you have 32-bit applications. Having a 64-bit cache server allows you to have more storage capacity since NCache is an in-memory cache.
  • Adequate RAM in cache servers: Each NCache server uses around 40-50MB memory as a .NET process and then puts 15% overhead on whatever you cache. Please keep this in mind while deciding how much memory to have in your cache servers. The total memory you need depends on how much data you plan to store in the cache. If you're storing ASP.NET Session State , then figure out your average session size and maximum number of sessions you'll ever have in the cache. You can do the same for application data caching.
  • Two 1Gbit NIC's in cache servers: If you have two NIC's in cache servers, it allows you to configure NCache so it uses one of the NIC's for cache clustering and the second one for client/server communication. This improves your throughput greatly.
  • Dual-CPU, Multi-core: NCache is a highly multi-threaded application and takes full advantage of extra cores and CPUs. The most common configuration for NCache is a dual-CPU machine where each CPU is either dual-core or quad-core.
  • Disk: NCache does not make heavy use of the disk space so you don't need any extra disk space in your cache server machines.
See Also
Command Line Install | Network Install with PowerShell | Interactive Windows Installer | Evaluation Period Expiration & Extension | Activate NCache Purchased License


Topic: Command Line Install

Command Line Install

NCache provides command line installation also that you can run either from a Command Prompt or can add to your script files (.bat files). To install NCache form Command Prompt you have to use msiexec.exe utility. Below is the syntax for using msiexec.exe to install NCache.
Install NCache
Msiexec.exe
/I <Installation Package Path>
EDITION ="0|2|3"
KEY ="EVAL_KEY_EMAILED_TO_YOU"
USERFIRSTNAME ="John"
USERLASTNAME ="Smith"
COMPANYNAME ="Alachisoft"
EMAILADDRESS ="john@alachisoft.com"
INSTALLDIR ="<Target Dir>"
SETPERMISSION ="0|1"
/qn
# | Switch/Properties | Purpose | Default Value
01 | EDITION | Specifies the installation option. Possible values are • (Cache Server) = 0 • (Developer) = 2 • (Remote Client) = 3 | 0 (Cache Server)
02 | KEY ( required ) | Installation Key Must be provided by you. You will have received this via email from Alachisoft when you downloaded NCache. If not, then visit http://www.alachisoft.com/download.html to register and obtain one. | Empty
03 | USERFIRSTNAME | Your first name | Empty
04 | USERLASTNAME | Your last name | Empty
05 | COMPANYNAME | Your company name | Alachisoft
06 | EMAILADDRESS (required) | Your email address | Empty
07 | INSTALLDIR | Directory where you want to install NCache. Most commonly, this should be "C:\program files\NCache". | Local Directory
08 | SETPERMISSION | NCache requires your permission to configure system permissions for PerfMon with NCache. Possible values are 0 (No) 1 (Yes) | 1 (Yes)
09 | /I <Installation Package Path> (required) | Path where you have kept NCache.clr20.msi file. You must specify this. | Empty
10 | /qn | Quiet mode. If you want to run the install silently without any user intervention, use this switch. | Empty
Below is an example of installing a cache server silently.
msiexec.exe /I "C:\NCacheSetup\NCache.clr20.msi" EDITION=0 KEY=INSTALL_KEY_EMAILED_TO_YOU USERFIRSTNAME="John" USERLASTNAME="Smith" COMPANYNAME="Alachisoft" EMAILADDRESS="john@alachisoft.com" INSTALLDIR="C:\Program Files\NCache" SETPERMISSION="1" /qn
Below is an example of installing NCache on a developer workstation.
msiexec.exe /I "C:\NCacheSetup\NCache.clr20.msi" EDITION=2 KEY=INSTALL_KEY_EMAILED_TO_YOU USERFIRSTNAME="John" USERLASTNAME="Smith" COMPANYNAME="Alachisoft" EMAILADDRESS="john@alachisoft.com" INSTALLDIR="C:\Program Files\NCache" SETPERMISSION="1" /qn
Below is an example of installing a remote client silently.
msiexec.exe /I "C:\NCacheSetup\NCache.clr20.msi" EDITION=3 KEY=INSTALL_KEY_EMAILED_TO_YOU USERFIRSTNAME="John" USERLASTNAME="Smith" COMPANYNAME="Alachisoft" EMAILADDRESS="john@alachisoft.com" INSTALLDIR="C:\Program Files\NCache" SETPERMISSION="1" /qn
Uninstall NCache
To uninstall NCache through command line, use the following syntax:
msiexec.exe> /x <Installation Package Path> /qn
Below is an example:
C:\> msiexec.exe /x "C:\NCacheSetup\NCache.clr20.msi" \qn
See Also
Getting Started | Network Install with PowerShell | Interactive Windows Installer | Evaluation Period Expiration & Extension | Activate NCache Purchased License


Topic: Network Install with PowerShell

Network Install with PowerShell

NCache provides integration with Windows PowerShell so that you can easily automate NCache processes on your network. You can manage NCache remote installation/un-installation tasks on your network through a single computer using PowerShell scripts. NCache also allows you to automate the activation process on all your cache servers and cache clients by using NCache PowerShell scripts. There are few PowerShell scripts that comes with NCache installation and we'll be discussing those in this section.
In This Section
Configuring PowerShell Environment
Describes how to configure environment for PowerShell.
Remote Installation/Uninstallation
Describes how to install/uninstall NCache on remote machines.
Activate NCache
Describes how to Activate NCache license on remote machine.
Troubleshooting problems occurring in Scripts
Describes solutions to common problems when using PowerShell scripts.


Topic: Configuring PowerShell Environment

Configuring PowerShell Environment

In order to run the NCache PowerShell scripts, PowerShell V2 or higher must be installed. Also, you need to enable script execution permissions in PowerShell. Here is how you can enable script execution in PowerShell.
  1. Go to PowerShell Administration console. You may simply go to command prompt and type/> PowerShell
  2. Set the script execution policy to unrestricted so that you can do remote installations. Here is how you can do this PS C:/Users> set-executionpolicy unrestricted
  3. Also, make sure that WinRM listener is configured and running on all remote machines where you'll do the configuration or installation remotely through our PowerShell Scripts. Here is how you can check the configuration status
    C:/Users/qa>winrm get winrm/config
    If the WinRM is listener is not already configured then type the following command to configure it.
    C:/Users/qa>winrm qc
See Also
Remote Installation/Uninstallation | Activate NCache | Troubleshooting problems occurring in Scripts


Topic: Remote Installation/Uninstallation

Remote Installation/Uninstallation

Installing NCache using PowerShell Script
NCache provides a PowerShell script called InstallNCache.ps1 for installing NCache on remote machines. Please refer to the Troubleshooting Install script section if you have any issue in executing this script.
You should find the InstallNCache.ps1 script at the NCache installation path in the integration folder
%INSTALLPATH%/NCache/Integration/PowerShell/InstallNCache.ps1
PS C:/Users> IntallNCache.ps1 /k key /file msi-file-name /file-path complete-file-path-of-msi [option[...]]
Argument | Description
/file file-name | Allows the user to specify the name of the setup file along with the file extension.
/file-path complete-file-path | Allows the user to specify the complete file-path/file-location of the setup file.
/k key | Allows the user to specify a valid license key.
Option | Description
/servers server-names | Allows the user to specify a comma separated list of Server Names or IP Addresses of machines where NCache is going to be installed.
/f first-name | Allows the user to specify first name.
/l last-name | Allows the user to specify last name.
/e edition | Allows the user to specify the NCache installation. Use "0" Cache Server installation, “2” is for Developer and “3” for Remote Client installation. Default is “0”.
/email email-address | Allows the user to specify the email address.
/company company-name | Allows the user to specify the company name.
/install-dir installation-path | Allows the user to specify the path where to install NCache. Default is "C:/Program Files/".
/set-per permissions | Allows the user to specify the permissions for quite mode. Default is "1".
/? | Displays command syntax and options for the utility.
Example of NCache Remote Installation:
In this example we will install NCache Cache Server on three computers (Test1, Test2, and Test3) using the PowerShell script InstallNCache.ps1. It is assumed that the NCache setup file “NCache.clr20.msi” is available on C Drive root and also that NCache is installed on the default path “C:/program files”.
PS C:/Program Files/ncache/integration/PowerShell> ./installNCache.ps1 /e 0 /k 7B1JYKITFRERLEIIE /file “NCache.clr20.msi” /file-path “C:/” /s Test1, Test2, Test3
This will install NCache Cache Server on all remote machines Test1, Test2 and Test3. Please replace the server “Test1, Test2, Test3” with your own server names. Upon successful installation you will see a message with “Return Value : 0”.
Uninstall NCache
NCache provides another PowerShell script called UninstallNCache.ps1 which helps to uninstall NCache from remote machine in silent mode. Please refer to the Troubleshooting Install script section if you have any issue in executing this script.
You should find the UninstallNCache .ps1 script at the NCache installation path in the integration folder
%INSTALLPATH%/NCache/Integration/PowerShell/ UninstallNCache .ps1
PS C:/Users>./UninstallNCache.ps1 ServerName1 ServerName2 ... n
Note: Server names must be separated with by BLANK Space. The names can be computer names or IP address of System.
Example of NCache Remote Un-Installation:
In this example we will uninstall NCache Cache Server from three computers (Test1, Test2, and Test3) using the PowerShell script UninstallNCache.ps1. It is assumed that that NCache is installed on the default path “C:/program files”
PS C:/Program Files/ncache/integration/PowerShell> ./UninstallNCache.ps1 Test1 Test2 Test3
This will uninstall NCache from all Cache servers Test1, Test2 and Test3. Please replace the server “Test1, Test2, Test3” with your own server names. Upon successful un-installation you should see a message with “Return Value : 0 ” Or 1614.
See Also
Configuring PowerShell Environment | Activate NCache | Troubleshooting problems occurring in Scripts


Topic: Activate NCache Purchased License

Activate NCache Purchased License

This PowerShell script lets you activate NCache license on remote machines. It makes your administrative tasks easy when you have many servers to activate because you don't have to manually activate the license on each server.
You should have internet access on all the machines where you want to activate NCache through the PowerShell script. Internally, this script uses command line tool NActivate.exe of NCache. You must have to provide valid admin user id and password that has the permissions to execute commands on remote machine.
Please refer to the Troubleshooting Install script section if you have any issue in executing this script. You should find the UninstallNCache .ps1 script at the NCache installation path in the integration folder:
%INSTALLPATH%/NCache/Integration/PowerShell/ ActivateNCache.ps1
PS C:/Users>./ ActivateNCache.ps1 /k key /f first-name /l last-name /email email-address /uid server-username /pwd server-password [ options[...] ].
Argument | Description
/k key | Allows users to specify a valid license key .
/f first-name | Allows users to specify first name.
/l last-name | Allows users to specify last name .
/email email-address | Allows users to specify email address.
/uid | Specify a valid user name that has permissions to execute the command on remote machine.
/pwd | Specify a valid password.
Option | Description
/servers server-names | Allows the user to specify a comma separated list of names or IPs of the machines on which NCache is to be activated .
/a address | Allows users to specify the company's address
/city city-name | Allows users to specify the edition of NCache. Default is "0".
/s state | Allows users to specify state name
/c country-name | Allows users to specify the country name.
/p phone-number | Allows users to specify the company's phone number.
/z zip-code | Allows users to specify the zip code
/? | Displays command syntax and options for the utility.
Remarks
In the following examples we will activate NCache License key on three machines Test1, Test2, and Test3 using the PowerShell script ActivateNCache.ps1. It is assumed that NCache is installed on the default path “C:/program files”.
Example of Activating NCache License Remotely:
PS C:/Program Files/ncache/integration/PowerShell>./ ActivateNCache.ps1 /k xxxxxxxx-xxxxxx-xxxxxxxx /f Paul /l Jones /email paul.jones@alachisoft.com /servers Test1, Test2, Test3 /uid Administrator /pwd 123pwd
This will activate NCache on three machines Test1, Test2 and Test3. Please replace the server “Test1, Test2, Test3” with your own server names.
See Also
Configuring PowerShell Environment | Remote Installation/Uninstallation | Troubleshooting problems occurring in Scripts


Topic: Interactive Windows Installer

Interactive Windows Installer

Another way you can install NCache is to double click on "NCache.clr20.msi" from the Windows Explorer. This launches the interactive Windows Installer. Below are the screen snapshots of the installation process.
  1. After you click on NCache.clr20.msi, you will see the following as your first screen.
  2. The next screen you will see, asks you to accept the license agreement. Click and check "I accept the license agreement", by this you are making a legal commitment to abide by the Alachisoft Software License Agreement for NCache. You cannot proceed if you don't accept this agreement.
  3. The next screen is quite important. It asks you to choose which edition of NCache you want to install. While installing NCache Enterprise edition you do not necessarily need to have visual studio, whereas, if you are installing NCache developer edition then visual studio (2003/ 2005/ 2008) should also be installed.
  1. The next thing to do is to provide the Installation Key. This is the key which you have received from Alachisoft. If you do not have an INSTALL KEY, please click on "Get Installation Key" button which takes you to Alachisoft web site to register and obtain an INSTALL KEY.
    NOTE: Please note that even when you have purchased NCache and have a license key, you must provide the INSTALL KEY here (and not the purchased license key). You'll get an opportunity later to specify your purchased license key when you activate your licenses.
    Below is the screen showing page of Alachisoft web site where you can register and obtain an INSTALL KEY. You have two options here. If you're already registered, just enter your email address and an INSTALL KEY will be emailed to you. Else, register by specifying information and an INSTALL KEY will be emailed to you.
  2. Below is a page where you need to enter your name, company name, and email address. This information will be displayed as part of NCache to indicate your identity.
  3. By default, NCache is installed in "C:\program files\NCache" folder. However, if you want to change this location, you can specify a different one below.
  4. Below, you can see all the components that will be installed automatically. You can unselect some of the components if you wish. But, it is strongly recommended that you keep everything as default.
  5. At this stage of the installation, the install program asks you whether you want it to automatically configure the permissions for NCache counters to be viewed in Perfmon remotely or you want ASPNET user-id to have the permission to write to the event log. Both of them are important unless you have a specific security reason, select YES here.
  6. After completing step by step process, you will see a final screen indicating successful installation of NCache.
See Also
Getting Started | Command Line Install | Network Install with PowerShell | Evaluation Period Expiration & Extension | Activate NCache Purchased License


Topic: Evaluation Period Expiration & Extension

Evaluation Period Expiration & Extension

By default, when you install NCache, it is installed as an “Evaluation Copy” and is valid for 60 days only. At the end of this period, NCache will stop working.
Indications of NCache Being Expired
You will be able to notice that NCache evaluation period has been expired from the following places:
• NCache API will no longer work. You won't be able to add or fetch items from the cache.
• NCache Manager splash screen will show NCache evaluation period expired.
• NCache Manager window title will show “Expired”.
• NCache Manager HELP -> ABOUT dialog will show NCache has expired.
• You won't be able to add an expired cache server to a cache cluster from NCache Manager.
• You won't be able to start cache on an expired cache server.
Extending Evaluation Period
If any of the above happens, then its time for you to either purchase NCache licenses or if you need an extension to your evaluation period, you can get an “Extension Key” from Alachisoft Sales. Please send an email to sales@alachisoft.com (or to your account manager if you're already in touch with him/her) and ask for an extension key. You will be provided a 30-day extension key.
Once you have obtained the extension key, please run “Run Activate NCache License” program from "%Install Directory%/NCache/bin/NActivate" path. Below is a screenshot for the screen to be displayed. Please select “Extend evaluation period” option and then click Next button .
Once you have clicked Next button, you will see the next screen shown below. Here you have to enter extension key provided to you by Alachisoft Sales and then press Finish button. If this key is valid, you will be prompted with a Success message. If the key is not valid, you will be prompted accordingly.
Please note that a 30-day extension is valid from the original installation date and not from the day you are trying to extend. So, if you have been waiting for 15 extra days after the initial 60 day evaluation period to extend it, you'll only get 15 extra days extension.
See Also
Getting Started | Command Line Install | Network Install with PowerShell | Interactive Windows Installer | Activate NCache Purchased License


Topic: Activate NCache Purchased License

Activate NCache Purchased License

If you have purchased NCache licenses, you can activate them from the same "Activate NCache License" program. Just run it and you'll see the following screen:
Click on the "Activate purchased copy of NCache" and press the Next button. You'll see the following screen.
Please note that if you have installed Enterprise Edition of NCache, you'll only get the "Production License" option here. Similarly, if you have installed Developer Edition, you'll get the "Developer License" option. Just click Next button and you'll see the following screen.
Here you get three different options to choose from. If your computer has Internet access, just select the Online (Recommended) option. It will ask you to enter a license key and will activate NCache license for you immediately.
Online Activation
Online activation is the fastest way to activate but it requires an Internet access. You need to specify the purchased license key below in order to proceed.
When you click Next button, you see the final screen for activating your license.
Just press Activate Now and it will activate NCache license for you immediately.
If for some reason you're unable to activate, it will display an error message. Your license activation can fail for a number of reasons as following:
• Your firewall does not allow HTTP POST from Activation Program to the Alachisoft License Server.
• You do not have Internet access
• Your license key is invalid
• You have already used up the purchased CPUs or nodes. If this happens, then please review your NCache license usage and then contact Alachisoft Sales.
Email and Manual Activation
However, if your computer does not have Internet access (which is the case in many production servers behind the firewall), then select Email option and click Next to see the screen below.
The screen above shows a long encrypted text. First of all, click on Copy button to copy this text to the clipboard. Then, you can paste this in an email and send that email to Alachisoft Support ( support@alachisoft.com ). This is actually an Activation Request Code that you need to obtain an Activation Auth Code. Or, you can directly visit the following URL to obtain this yourself:
http://www.alachisoft.com/admin/ncache/console/emailact.php
Paste the Activate Request Code into the text box on this page and then press Verify.
You will see the following page.
On the above page (not visible in the screenshot due to scrolling), there is an Activate button at the bottom of the page. When you click this button, it will display a page with the Activate "Auth Code" on the following page:
Take the above Activation Auth Code (shown as a long encrypted string toward the end of the page right above the red color message) and copy it to your clipboard. Then, go back to Activate NCache License program and select Manual activation option.
You'll see the following screen.
Just paste the Activation Code here and press Finish button. NCache will be activated on your machine and following screen will be prompted.
See Also
Getting Started | Command Line Install | Network Install with PowerShell | Interactive Windows Installer | Evaluation Period Expiration & Extension


Topic: Command Line Activation

Command Line Activation

NCache can also be activated via command line. This will help the users to automate the process of NCache Activation. The tool NActivate.exe is a console application and can be found inside %INSTALLATION_PATH%/NCache/bin/NActivate folder.
nactivate /k R4179Gba-b1f296-78F6U590 /f Paul /l Jones /e paul@alachisoft.com [option[...]]
Argument | Description
/k key | Specifies the license key got from Alachisoft.
/f first name
Specifies the user's first name.
/l last name
Specifies the user's last name.
/e email address
Specifies the user's email address.
Option | Description
/comp[any] company | Specifies the user's company name.
/a address | Specifies the user's address.
/city city | Specifies the name of city.
/s state | Specifies the name of state.
/c[ountry] country | Specifies the name of country.
/z zip | Specifies the postal or zip code.
/p phone | Specifies the phone number.
/nologo | Suppresses display of the logo banner.
/? | Displays command syntax and options for the utility.
Remarks
You must supply the license key got from Alachisoft.
Examples
The following command activates the NCache on a machine.
nactivate /k R4179Gba-b1f296-78F6U590 /f Paul /l Jones /e paul@alachisoft.com
The following command displays command syntax and options for the utility. Logo banner is displayed as a part.
nactivate /?
The following command displays command syntax and options for the utility suppressing the display of logo banner.
nactivate /? /nologo


Topic: Java Installation Guide

Java Installation Guide

The Installation Guide provides the most comprehensive information about installation, prerequisites and system configuration. It also provides a detailed, step-by-step process guide about how to install NCache using command line installer and interactive window installer.
In This Section
Installation Guide For Windows
Describes comprehensive information about installation, prerequisites and system configuration for NCache installation on Windows.
Installation Guide For Unix
Describes comprehensive information about installation, prerequisites and system configuration for NCache installation on Unix.
See Also
Introduction to NCache
Presents a brief introduction to NCache, with an emphasis on new and old features, editions and requirements of NCache.
Configuring the Cache
Discusses configuration options that NCache provides for local and clustered caches. It also helps in configuring NCache through NCache Manager and configuration files.
Developing with NCache
Focuses on what is essential to become skilled at developing with NCache. It includes programmers guide and extensive help on API reference.


Topic: Installation Guide for Windows

Installation Guide for Windows

The Installation Guide provides you the most comprehensive information about installation, prerequisites and system configuration. It also provides a detailed, step-by-step process guide about how to install NCache using command line installer and interactive window installer.
In This Section
Getting Started
Describes the pre-requisites for NCache installation.
Command Line Install
Describes how NCache provides a command line installation that can either run from a Command Prompt or add to a script files (.bat files).
Interactive Windows Installer
Describes, how to install NCache using interactive Windows Installer.
Evaluation Period Expiration & Extension
Describes the procedure for extending NCache evaluation period.
Activate NCache Purchased License
Describes how to activate NCache license.
See Also
Introduction to NCache
Presents a brief introduction to NCache, with an emphasis on new and old features, editions and requirements of NCache.
Configuring the Cache
Discusses configuration options that NCache provides for local and clustered caches. It also helps in configuring NCache through NCache Manager and configuration files.
Developing with NCache
Focuses on what is essential to become skilled at developing with NCache. It includes programmers guide and extensive help on API reference.


Topic: Getting Started

Getting Started

NCache provides a Windows Installer Package (.msi) to let you easily install NCache. However, before you install NCache, you need to keep the following in mind.
What to Install during Evaluation?
NCache Enterprise: Regardless of which NCache edition you ultimately end up using, you should do your evaluation with NCache Enterprise. This is because you will be able to see all the features that NCache offers in full and then decide whether you need to downgrade to NCache Professional or stay with NCache Enterprise.
Installation Options
Whether you install NCache Enterprise or Professional, you're given the following installation options when you run the .msi file.
  • Cache Server: This is a full install of NCache and contains everything that the other two options provide plus cache clustering capability. You must install this on any servers where you're going to host the cache, regardless of whether you have dedicated or shared cache servers.
  • Remote Client: This installs the remote client libraries and client cache on all your web/app servers so you can access the cache across the network. Please note that you need remote client libraries to access the cache across the network.
  • Developer: This installs the NCache API, online help/documentation, and a local stand-alone cache without any clustering capability. Please note that you cannot access a remotely hosted cache from a developer install machine. You can only access a local cache.
Where to Install NCache?
NCache needs to be installed on the following machines:
  • Production, Staging, QA, or Dev Servers: Install NCache Enterprise Edition on the following.
  • Cache servers (dedicated or shared): If you have 4 or more web/app servers in your environment hosting your application, then we recommend a dedicated caching tier of 2 servers. A dedicated cache cluster should have a minimum of 2 servers for replication and then a ratio of 5:1 between your web/app servers and the cache servers. For smaller environments, even using your web/app servers as cache servers is fine, as long as your have enough memory available on these machines.
  • NCache remote clients (app or web servers): Any web/app server that is not hosting the cache server but instead will access it remotely across the network is considered an NCache remote client. You need to install the "remote client" portion of NCache on these machines.
  • Developer Workstations: If you're using NCache for object caching, you will be making NCache API calls from within your application. Therefore, you need to install NCache "Developer" portion on all the developer machines. A developer install includes all the NCache API's, online help, and a local stand-alone cache. Please note that you cannot access any cache remotely from a developer install .
System Recommendations
  • Windows 2003/2008 Server (64-bit) as Cache Servers: It is highly recommended that you use 64-bit version of Windows 2003 or 2008 server platform for cache servers even if you have 32-bit applications. Having a 64-bit cache server allows you to have more storage capacity since NCache is an in-memory cache.
  • Adequate RAM in cache servers: Each NCache server uses around 40-50MB memory as a .NET process and then puts 15% overhead on whatever you cache. Please keep this in mind when deciding how much memory to have in your cache servers. The total memory you need depends on how much data you plan to store in the cache. If you're storing ASP.NET Session State , then figure out your average session size and maximum number of sessions you'll ever have in the cache. You can do the same for application data caching.
  • Two 1Gbit NIC's in cache servers: If you have two NIC's in cache servers, it allows you to configure NCache so it uses one of the NIC's for cache clustering and the second one for client/server communication. This improves your throughput greatly.
  • Dual-CPU, Multi-core: NCache is a highly multi-threaded application and takes full advantage of extra cores and CPUs. The most common configuration for NCache is a dual-CPU machine where each CPU is either dual-core or quad-core.
  • Disk: NCache does not make heavy use of the disk space so you don't need any extra ordinary disk space in your cache server machines.
See Also
Command Line Install | Interactive Windows Installer | Evaluation Period Expiration & Extension | Activate NCache Purchased License


Topic: Command Line Install

Command Line Install

NCache provides a command line installation that you can either run from a Command Prompt or add to your script files (.bat files). To install NCache form Command Prompt you use the msiexec.exe utility. Below is the syntax for using msiexec.exe to install NCache.
Install NCache
Msiexec.exe
/I <Installation Package Path>
EDITION ="0|2|3"
KEY ="EVAL_KEY_EMAILED_TO_YOU"
USERFIRSTNAME ="John"
USERLASTNAME ="Smith"
COMPANYNAME ="Alachisoft"
EMAILADDRESS ="john@alachisoft.com"
INSTALLDIR ="<Target Dir>"
SETPERMISSION ="0|1"
/qn
# | Switch/Properties | Purpose | Default Value
01 | EDITION | Specifies the installation option. Possible values are • (Cache Server) = 0 • (Developer) = 2 • (Remote Client) = 3 | 0 (Cache Server)
02 | KEY ( required ) | Installation Key: Must be provided by you. You will have received this via email from Alachisoft when you downloaded NCache. If not, then visit http://www.alachisoft.com/download.html to register and obtain one. | Empty
03 | USERFIRSTNAME | Your first name | Empty
04 | USERLASTNAME | Your last name | Empty
05 | COMPANYNAME | Your company name | Alachisoft
06 | EMAILADDRESS (required) | Your email address | Empty
07 | INSTALLDIR | Directory where you want NCache to be installed. Most commonly, this should be "C:\program files\NCache". | Local Directory
08 | SETPERMISSION | NCache requires your permission to configure system permissions for PerfMon with NCache. Possible values are 0 (No) 1 (Yes) | 1 (Yes)
09 | /I <Installation Package Path> (required) | Path where you have kept NCache.clr20.msi file. You must specify this. | Empty
10 | /qn | Quiet mode. If you want to run the install silently without any user intervention, use this switch. | Empty
Below is an example of installing a cache server silently.
msiexec.exe /I "C:\NCacheSetup\NCache.clr20.msi" EDITION=0 KEY=INSTALL_KEY_EMAILED_TO_YOU USERFIRSTNAME="John" USERLASTNAME="Smith" COMPANYNAME="Alachisoft" EMAILADDRESS="john@alachisoft.com" INSTALLDIR="C:\Program Files\NCache" SETPERMISSION="1" /qn
Below is an example of installing NCache on a developer workstation.
msiexec.exe /I "C:\NCacheSetup\NCache.clr20.msi" EDITION=2 KEY=INSTALL_KEY_EMAILED_TO_YOU USERFIRSTNAME="John" USERLASTNAME="Smith" COMPANYNAME="Alachisoft" EMAILADDRESS="john@alachisoft.com" INSTALLDIR="C:\Program Files\NCache" SETPERMISSION="1" /qn
Below is an example of installing a remote client silently.
msiexec.exe /I "C:\NCacheSetup\NCache.clr20.msi" EDITION=3 KEY=INSTALL_KEY_EMAILED_TO_YOU USERFIRSTNAME="John" USERLASTNAME="Smith" COMPANYNAME="Alachisoft" EMAILADDRESS="john@alachisoft.com" INSTALLDIR="C:\Program Files\NCache" SETPERMISSION="1" /qn
Uninstall NCache
To uninstall NCache through command line, use the following syntax:
msiexec.exe> /x <Installation Package Path> /qn
Below is an example:
c:/> msiexec.exe /x "c:/NCacheSetup/NCache.clr20.msi" /qn
See Also
Getting Started | Interactive Windows Installer | Evaluation Period Expiration & Extension | Activate NCache Purchased License


Topic: Interactive Windows Installer

Interactive Windows Installer

Another way you can install NCache is to double click on "NCache.clr20.msi" from the Windows Explorer. This launches the interactive Windows Installer. Following are the screen snapshots of installation process.
  1. After you click on NCache.clr20.msi, you see the following as your first screen.
  2. The next screen is about license agreement. By checking "I accept the license agreement", you are making a legal commitment to abide by the Alachisoft Software License Agreement for NCache. You cannot proceed without accepting this.
  3. The next screen is quite important. It asks you to select which edition of NCache you want to install. While installing NCache Enterprise edition you do not necessarily need to have visual studio, whereas, if you are installing NCache developer edition then visual studio (2003/ 2005/ 2008) should also be installed.
  4. The next thing is to provide the Installation Key. This is the key you have received from Alachisoft. If you do not have INSTALL KEY, then click on "Get Installation Key" button which takes you to Alachisoft web site to register and obtain an INSTALL KEY.
    NOTE: Please note that even when you have purchased NCache and have a license key, you must provide the INSTALL KEY here (and not the purchased license key). You'll get an opportunity later to specify your purchased license key when you activate your licenses.
    Below is the screen showing the page of Alachisoft website where you can register and obtain an INSTALL KEY. You will have two options here. If you're already registered, just enter your email address and an INSTALL KEY will be emailed to you. Otherwise, register by specifying information and an INSTALL KEY will be emailed to you.
  5. Below is a page where you have to enter your name, company name, and email address. This information will be displayed as part of NCache to indicate your identity.
  6. By default, NCache is installed in "C:\program files\NCache" folder. However, if you want to change this location, you can specify a different one below.
  7. Below, you see all the components that will be installed automatically. You can unselect some of the components if you wish. But, it is strongly recommended that keep everything as default.
  8. At this stage of installation, the install program asks you, whether you want it to automatically configure the permissions for NCache counters to be viewed in Perfmon remotely or you want ASPNET user-id to have the permission to write to the event log. Both of are important unless you have a specific security reason, select YES here.
  9. After completing step by step process, you will see final screen indicating successful installation of NCache.
See Also
Getting Started | Command Line Install | Evaluation Period Expiration & Extension | Activate NCache Purchased License


Topic: Evaluation Period Expiration & Extension

Evaluation Period Expiration & Extension

By default, when you install NCache, it is installed as "Evaluation Copy" and remains valid for 60 days. After this period, NCache will stop working.
Indications of NCache Being Expired
You will be able to notice that NCache evaluation period has been expired from the following places:
• NCache API will no longer work. You won't be able to add or fetch items from the cache.
• NCache Manager splash screen will show NCache evaluation period has expired.
• NCache Manager window title will show "Expired"
• NCache Manager HELP -> ABOUT dialog will show NCache as being expired
• You won't be able to add an expired cache server to a cache cluster from NCache Manager
• You won't be able to start cache on an expired cache server
Extending Evaluation Period
If any of the above happens, then its time to either purchase NCache licenses or if you need an extension to your evaluation period, you can obtain an "Extension Key" from Alachisoft Sales. Please send an email to sales@alachisoft.com (or to your account manager if you're already in touch with him/her) and ask for an extension key. You will be provided a 30-day extension key.
Once you have obtained extension key, please run "Run Activate NCache License" program from "%Install Directory%/NCache/bin/NActivate" path. Below is a screen shot of the screen which will be displayed. Please select "Extend evaluation period" option and then click Next button .
Once you click Next button, you will see the screen shown below. Please enter the extension key provided to you by Alachisoft Sales and then press Finish button. If this key is valid, you will be prompted with a Success message. If the key is not valid, you will be prompted accordingly.
Please note that a 30-day extension is valid from the original installation date, not from the day you are trying to extend. So, if you waited for 15 extra days after the initial 60 day evaluation period to extend it, you'll only get 15 extra days extension.
See Also
Getting Started | Command Line Install | Interactive Windows Installer | Activate NCache Purchased License


Topic: Activate NCache Purchased License

Activate NCache Purchased License

If you have purchased NCache licenses, you can activate them from the same "Activate NCache License" program. Just run it and you'll see the following screen:
Click on the "Activate purchased copy of NCache" and press the Next button. You'll see the following screen.
Please note that if you have installed Enterprise Edition of NCache, you'll only get the "Production License" option here. Similarly, if you have installed Developer Edition, you'll get the "Developer License" option. Just click Next button and you'll see the following screen.
Here you will see three different options to select from. If your computer has Internet access, just select the Online (Recommended) option. It will ask you to enter a license key and will activate NCache license for you immediately.
Online Activation
Online activation is the fastest way to activate but it requires an Internet access. You need to specify the purchased license key below in order to proceed.
When you click Next button, you will see the final screen for activating your license.
Just press Activate Now and it will activate NCache license for you immediately.
If for some reason you're unable to activate, it will display an error message. Your license activation can fail for a number of reasons as following:
• Your firewall does not allow HTTP POST from Activation Program to the Alachisoft License Server.
• You do not have Internet access.
• Your license key is invalid.
• You have already used up the purchased CPUs or nodes. If this happens, then please review your NCache license usage and then contact Alachisoft Sales.
Email and Manual Activation
However, if your computer does not have Internet access (which is the case in many production servers behind the firewall), then select Email option and click Next to see the screen below.
The screen above shows a long encrypted text. First of all, click on Copy button to copy this text to the clipboard. Then, you can paste this in an email and send that email to Alachisoft Support ( support@alachisoft.com ). This is actually an Activation Request Code that you need to obtain an Activation Auth Code. Or, you can directly visit the following URL to obtain this yourself:
http://www.alachisoft.com/admin/ncache/console/emailact.php
Paste the Activate Request Code into the text box on this page and then press Verify.
You will see the following page.
On the above page (not visible in the picture due to scrolling), there is an Activate button at the bottom of the page. When you press this button, it will display a page with the Activate "Auth Code" on the following page:
Take the above Activation Auth Code (shown as a long encrypted string toward the end of the page right above the red color message) and copy it to your clipboard. Then, go back to Activate NCache License program and select Manual activation option.
You'll see the following screen.
Just paste the Activation Code here and press Finish button. NCache will be activated on your machine and following message will be prompted.
See Also
Getting Started | Command Line Install | Interactive Windows Installer | Evaluation Period Expiration & Extension


Topic: Installation Guide for Unix

Installation Guide for Unix

The Installation Guide provides you the most comprehensive information about installation, prerequisites and system configuration. It also provides a detailed, step-by-step guide about how to install NCache using command line installer and interactive Unix installer.
In This Section
Install Java Client on Unix
Describes the pre-requisites for NCache installation.
Command Line Installation
Describes how NCache provides a command line installation that can either run from a Command Prompt or add to a script files (.bat files).
What Get Installed?
Gives an overview of the components that are installed along with NCache.
Evaluation Period Expiration & Extension
Describes the procedure for extending NCache evaluation period.
Activate NCache Purchased License
Describes how to activate NCache license.
See Also
Introduction to NCache
Presents a brief introduction to NCache, with an emphasis on new and old features, editions and requirements of NCache.
Configuring the Cache
Discusses configuration options that NCache provides for local and clustered caches. It also helps in configuring NCache through NCache Manager and configuration files.
Developing with NCache
Focuses on what is essential to become skilled at developing with NCache. It includes programmers guide and extensive help on API reference.


Topic: Installing Java Client of NCache on Unix

Installing Java Client of NCache on Unix

Through Java remote client you can connect your java application to NCache Server running on Windows. NCache Java Remote Client for Unix is available as a .tar.gz file. You can download the latest setup from http://www.alachisoft.com/download.html . Before installing NCache Remote Java Client setup, please configure your environment as discussed below.
Pre-Requisites:
  • JRE 1.5 or later is required.
  • You need to have working Java environment where the environment variable JAVA_HOME should be pointing to the installation path of Java. If you don't want to configure the JAVA_HOME for the current user then you can provide the Java installation path in install_env.sh shell script. You'll find this script when you unzip the setup file.
[root@..]# java -version
Above java version command should return proper description of current working environment. Similarly CLASSPATH environment variable should also be configured.
  • You must have 'root' privileges to install this package.
  • You need to have Install Key that you might have received when downloaded NCache Java Remote Client. Install key is identical for Cache Server Installation (on Windows OS) as well as for client (.NET and Java) installation. It is a 17 digit alpha-numeric key.
Java Environment Configurations:
In order to use 'install.sh', you must have JRE 1.5 or later installed. Additionally, you need to have your JAVA_HOME point to the root folder of your JRE. Put this in your .bashrc or other similar startup script files or if you have configured the install_env.sh then you can skip these steps.
Below is an example for .bashrc for Linux:
export JAVA_HOME=/usr/lib/java
(path where you have installed JDK)
/usr/lib/java should normally have the following folders inside it:
- bin
- include
- jre
- lib
And, you need to have your PATH point to $JAVA_HOME/bin like this:
export PATH=$JAVA_HOME/bin:$PATH
On Redhat Linux if you install JDk 1.6.0 through "yum install" , it normally installs JDK in /etc/alternatives/java_sdk_1.6.0 and does not automatically update /usr/lib/java to point to it. If that is the case with you, then you may need to manually create soft-links to the "bin", "include", "jre" , and "lib" folders.
In order to make sure that you have correct java version, you can type the following:
[root@...]# $JAVA_HOME/bin/java -version
Environment Configurations for NCache Java Client:
Following steps must be taken before actually running NCache Java Client.
  • If you don't want to configure the environment variables for running NCache samples or tools then you should modify the shell script ncache_env.sh with JAVA_HOME, NCACHE_ROOT and CLASSPATH variables otherwise follow under mentioned steps. These variables are restricted to the script only and should be pointed to the correct path of Java and NCache installation paths respectively. You can copy the CLASSPATH from the step 3.
  • You need to setup environment variable named
NCACHE_ROOT=NCacheInstallFolder
(default value is '/usr/local/ncache')
you need to have it in your .bash_profile like
export NCACHE_ROOT=/usr/local/ncache
  • You need to have following jar files available under your CLASSPATH to run NCache java client.
CLASSPATH=$NCACHE_ROOT/lib/NCClient.jar:$NCACHE_ROOT/lib/NCActivate.jar:$NCACHE_ROOT/lib/swing-layout-1.0.jar:$CLASSPATH
export CLASSPATH
See Also
Command Line Installation | What Get Installed? | Evaluation Period Expiration & Extension | Activate NCache Purchased License


Topic: Command Line Installation

Command Line Installation

Install Java Client:
Below are the steps required to install NCache Java client:
1. Open the command line terminal.
2. Login as 'root' user.
3. Go to the folder where you have downloaded Java client installation archive (ncache-java-client-setup.tar.gz).
For example: /home/user/desktop/
4. Uncompress the NCache Java client archive
[root@..]# tar -xvfz <ncache-java-client-setup>.tar.gz
The extracted directory (/user/home/desktop/ <ncache-java-client-setup>/ ) will have the following files.
  • A shell script named "install.sh", to install the product.
  • A README file (this file also contains the installation instructions)
  • Original setup files archive ncache380-sp2-client-setup.tar.gz. Archive name is based on java client version. (do not change this manually, it is used by given shell script "install.sh")
  • An INSTALL file that helps you knowing what gets installed after successful run of "install.sh"
  • A shell script named "uninstall.sh" to uninstall the product
5. Go to the extracted directory: [root@..]# cd <ncache-java-client-setup>
6. Next step is to run the installation script "install.sh" present in uncompressed directory (/user/home/desktop/ <ncache-java-client-setup>/ ) You can either give command.
[root@...]# bash install.sh
or
[root@...]# chmod +x install.sh
[root@...]# ./install.sh
You must run the 'install.sh' file using 'sudo ./install.sh' if you are not logged in as 'root' user.
'install.sh' allows following usage pattern to install NCache Java Client
Usage: install.sh -f FIRSTNAME -l LASTNAME -e mail EMAIL -k INSTALLKEY [-d PATH]
install.sh -h (for help)
7. After successful installation it would give you a message "Installation Completed Successfully".
8. Last step is to configure environment variables for NCache Java Client. Environment Configurations for NCache Java Client .
Uninstall Java Client:
In order to uninstall Ncache Java client, uinstall.sh script is provided in downloaded Java Client Installation archive. Run the following command to give executable permissions to the script.
[root@...]# bash uninstall.sh (/user/home/desktop/ <ncache-java-client-setup>/ )
or
[root@...]# chmod +x uninstall.sh
[root@...]# ./uninstall.sh
You must run the 'uninstall.sh' file using 'sudo ./uninstall.sh' if you are not logged in as 'root' user.
When the script is executed it will ask about the NCache installation directory path(default is /usr/local/ncache), provide the path and press enter it will do uninstall confirmation only and will proceed to uninstall.
See Also
Install Java Client on Unix | What Get Installed? | Evaluation Period Expiration & Extension | Activate NCache Purchased License


Topic: What Gets Installed?

What Gets Installed?

When the installation is done, you'll have a directory for NCache on your local machine that contains following (default is /usr/local/ncache):
Configuration Files:
• Client.ncconf
Libraries:
• NClient.jar
• NCActivate.jar
• NCacheSessionProvider.jar
• NCClassBrowser.jar
• installer.jar
• javaReg.properties
• NCRuntime.jar
• NCSerialization.jar
Tools:
• Stress Test tool
• Get Cache Count
• Verify NCache license
• Clear Cache
• Add Test Data
• Dump Cache Tool
Documents:
• NCache Java Client API documentation
• NCache for Java Session
• README
Help:
• NCache Help Collection
• Java API Reference
Samples:
• Java API Test
• Basic API Test
• Guess Game (Java Session)
See Also
Install Java Client on Unix | Command Line Installation | Evaluation Period Expiration & Extension | Activate NCache Purchased License


Topic: Evaluation Period Expiration & Extension

Evaluation Period Expiration & Extension

By default, when you install NCache Client, it is installed as a "Fully working Evaluation Copy" and is valid for 60 days. At the end of the evaluation period, NCache will stop working.
Indications of NCache Being Expired:
You will be able to notice that NCache evaluation period has expired from the following places:
  • NCache API will no longer work. You won't be able to add items to the cache or fetch them.
  • NCache License can be verified by running verifyncachelicense tool. (Path: /user/local/ncache/tools/ )
Extending Evaluation Period:
If any of the above happens, then it is time for you to either purchase NCache license or extend the trial period for further evaluation. You can obtain an "Extension Key" from Alachisoft Sales. Please send an email to sales@alachisoft.com (or to your account manager if you're already in touch with him/her) and ask for an extension key. You will be provided a 30-day extension key.
Once you have the extension key, run the NCActivate program by using either shell script present in bin directory of Java client installation directory:
[root@...]# bash ncactivate.sh (Path: /user/local/ncache/bin/ )
OR
[root@...]# java -jar NCActivate.jar
OR
if your class paths are not configured then
[root@...]# java -cp [Java client installation path]/lib: [Java client installation path]/NCActivate.jar com.alachisoft.ncache.nactivate.ui.Main
Note: [Java client installation path] by default is /usr/local/ncache
You will see following screen on desktop. Please select "Extend evaluation period" option and then click Next button.
Once you click Next button, you will see the screen shown below. Please enter the extension key provided to you by Alachisoft Sales and then press Finish button. If this key is valid, you will be prompted with a Success message. If the key is not valid, you will be prompted accordingly.
Note: A 30-day extension is valid from the original installation date, not from the day you try to extend. So, if you have been waiting for 15 extra days after the initial 60 day evaluation period to extend it, you'll only get 15 extra days extension.
See Also
Install Java Client on Unix | Command Line Installation | What Get Installed? | Activate NCache Purchased License


Topic: Activate NCache Purchased License

Activate NCache Purchased License

If you have purchased NCache license, you can activate it from the same "NCActivate.jar" program. You can Run "NCActivate" program by using either shell script present in bin directory of Java client installation directory:
[root@...]# bash ncactivate.sh (Path: /user/local/ncache/bin/ )
OR
[root@...]# java -jar NCActivate.jar
OR
If your class paths are not configured then:
[root@...]# java -cp [Java client installation path]/lib: [Java client installation path]/NCActivate.jar com.alachisoft.ncache.nactivate.ui.Main
Note: [Java client installation path] by default is /user/local/ncache
Just run it and you'll see the following screen:
Click on the "Activate purchased copy of NCache" and press the Next button. You'll see the following screen.
Please note that if you have installed Enterprise Edition of NCache, you'll only get the "Production License" option here. Similarly, if you have installed Developer Edition, you'll get the "Developer License" option. Just click Next button and you'll see the following screen.
Here you get three different options to choose from. If your computer has Internet access, just select the Online (Recommended) option. It will ask you to enter a license key and will activate NCache license for you immediately.
Online Activation:
Online activation is the fastest way to activate but requires Internet access on your machine. You need to specify the purchased license key below to proceed.
When you click Next button, you'll see the final screen for activating your license. Just press Activate Now and it will activate NCache license for you immediately. If for some reason you're unable to activate, it will display an error message. Your license activation can fail for a number of reasons as following:
  • Your firewall does not allow HTTP POST from Activation Program to the Alachisoft License Server.
  • You do not have Internet access
  • Your license key is invalid
  • You have already used up the purchased CPUs or nodes. If this happens, then please review your NCache license usage and then contact Alachisoft Sales.
Email and Manual Activation:
However, if your computer does not have Internet access (which is the case in many production servers behind the firewall), then select Email option and click Next to see the screen below.
The screen above shows a long encrypted text. First of all, click on Copy button to copy this text to the clipboard. Then, you can paste this in an email and send that email to Alachisoft Support ( support@alachisoft.com ). This is actually an Activation Request Code that you need to obtain an Activation Auth Code. Or, you can directly visit the following URL to obtain this yourself:
http://www.alachisoft.com/admin/customer_console/main.php
From the above page, just click on Activate NCache link which will show you the following page:
Paste the Activate Request Code into the text box on this page and then press Verify. You will see the following page.
On the above page (not visible in the picture due to scrolling), there is an Activate button at the bottom of the page. When you press this button, it will display a page with the Activate Auth Code on the following page:
Take the above Activation Auth Code (shown as a long encrypted string toward the end of the page right above the red color message) and copy it to your clipboard. Then, go back to Activate NCache License program and select Manual activation option. You'll see the following page.
Just paste the Activation Code here and press Finish button. NCache will be activated on this machine.
See Also
Install Java Client on Unix | Command Line Installation | What Get Installed? | Evaluation Period Expiration & Extension


Topic: Getting Started

Getting Started

Familiarizes you with the fundamentals of NCache and offers help to use NCache quickly and efficiently.
In This Section
Getting Started for .NET
Describes most common API's provided by NCache with examples for .NET users.
Getting Started for Java
Describes most common API's provided by NCache with examples for Java users.
See Also
Introduction to NCache
Presents a brief introduction to NCache, with an emphasis on new and old features, editions and requirements of NCache.
Configuring the Cache
Discusses configuration options that NCache provides for local and clustered caches. It also helps in configuring NCache through NCache Manager and configuration files.
Developing with NCache
Focuses on what is essential to become skilled at developing with NCache. It includes programmers guide, sample applications, hands on tutorials and extensive help on API reference.


Topic: Getting Started for .NET

Getting Started for .NET

Familiarizes you with the fundamentals of NCache and offers help to use NCache quickly and efficiently.
In This Section
Quickly Configure and Use NCache
Describes basic steps for smooth installation, configuration and use of NCache.
Quickly Use Cache API in .NET
Describes most common API's provided by NCache with examples for .NET users.
Quick Start Guides for .NET
Provides quick start guides to use .NET features with NCache.
See Also
Introduction to NCache
Presents a brief introduction to NCache, with an emphasis on new and old features, editions and requirements of NCache.
Configuring the Cache
Discusses configuration options that NCache provides for local and clustered caches. It also helps in configuring NCache through NCache Manager and configuration files.
Developing with NCache
Focuses on what is essential to become skilled at developing with NCache. It includes programmers guide, sample applications, hands on tutorials and extensive help on API reference.


Topic: Getting Started Guide

Getting Started Guide

Here are some basic steps you should follow to ensure a smooth installation, configuration, and use of NCache.
NOTE:
Add Reference issue of Visual Studio 2010
If your development environment is Visual Studio 2010, you may not be able to see the NCache .NET assemblies in the "Add Reference" dialog box under ".NET" tab. However, you can add reference to the NCache assemblies by using the "Browse" tab. You can find all these assembly files in [NCache Installed folder]/bin/assembly/
1. Install NCache on Cache Server and Remote Client Machines
Install NCache on all remote client and cache server machines. If you have a separate caching tier, you'll have remote clients. Otherwise, cache will be hosted on your application server.
You can install either 32-bit or 64-version of NCache. 64-bit cache servers work fine with 32-bit clients.
2. Configure Servers for Multiple Network Cards (optional)
If your cache servers (including your app servers if you're hosting cache on them) have multiple network cards, then you must bind NCache to a specific card. You need to specify the following in "Alachisoft.NCache.Service.exe.config" in "NCache/bin/service" folder:
<appSettings>
...
<add key="NCacheServer.BindToClusterIP" value="20.200.20.200" />
<add key="NCacheServer.BindToClientServerIP" value="20.200.20.200" />
...
</appSettings>
NOTE: Anytime you modify "Alachisoft.NCache.Service.exe.config", you must restart NCache Service. You can do this through following commands:
C:/Users/Administrator>net stop ncachesvc
C:/Users/Administrator>net start ncachesvc
You can also bind Client/Server communication to a different network card than the Clustering network card, if you have multiple network cards. Or, you can bind both to the same card (as shown above).
3. Open Firewall TCP Port for Clients (optional)
If there is a firewall between your remote clients and the cache servers, then you must open a TCP port (default 9800) for the remote clients to talk to the cache servers. If you want to change this from 9800 to another port, then you must make changes in all remote client and all cache server machines. On the remote clients, you need to change the "port" value in "client.ncconf" as following:
<configuration>
<ncache-server port = "9800" client-request-timeout = "90" connection-retries = "1" retry-interval = "0" connection-timeout = "5"/>
</configuration>
And, you need to change the "NCacheServer.Port" value in "Alachisoft.NCache.Service.exe.config" file located in "NCache/bin/service" folder on all cache servers as following:
<appSettings>
...
<add key="NCacheServer.Port" value="9800" />
...
</appSettings>
NOTE: Anytime you modify "Alachisoft.NCache.Service.exe.config", you must restart NCache Service (as described above).
All remote clients by default talk to NCache servers on TCP port 9800. So, if there is a firewall between the remote clients and the cache server, then you must open TCP port 9800 in your firewall.
4. Open Firewall TCP Port for Cache Cluster (optional)
If you have a situation where there is a firewall between the cache servers and the cluster must be formed across this firewall, then you must open at least two TCP ports (bi-directional) in this firewall. This port is the Cluster Port specified by you while creating a new clustered cache. For example:
Cluster Port: 7800
Port Range: 1
Open ports 7800. If Port Range is 2, then open 7800 and 7801.
5. Create New Clustered Cache
Run NCache Manager from ONLY ONE location (preferably from one of your cache servers), and create a new clustered cache. You can choose to create one of the following types of caches:
  1. Mirrored Cache
  2. Partitioned Cache
  3. Partitioned Cache with Replicas (recommended)
  4. Replicated Cache
For starters, we recommend to create a Replicated Cache. Later on, you can decide whether a different caching topology meets your requirements better or not. For now, we want to go through the entire process quickly.
6. Test Cache Cluster from Statistics Window
Once you have created a clustered cache, you should test to make it sure that it works fine. Here are the steps to test the cluster from within NCache Manager.
  1. Start the cache
  2. View Statistics of the cache (right-click menu)
  3. Press Add button on top of the Statistics window. It should add "10" dummy items to the cache. And, the "Count" counter should reflect this. If you have a Replicated Cache, then all cache servers should show the same "Count" value and if Count value is same, then cluster is working fine.
7. Remote Client Machines
NCache provides remote client management through NCache Manager. By right click on the Client Nodes, context menu will appear having "Add Node" option as shown in figure. Using this option you can add and configure a single or multiple client nodes in a clustered cache.
8. Ensure All Objects are Serializable
Whether you're using NCache for ASP.NET Sessions or for object caching, you must ensure that all .NET objects are serializable. This is true even for those .NET objects which are being stored in your Session. Here is how to ensure that:
[Serializable]
class Product
{
...
}
9. Modify "web.config" for ASP.NET Sessions
If you're using NCache for ASP.NET Sessions, you need to modify your "web.config". For .NET 1.1, you need to specify an HttpModule (see online help and "samples" for example). And, for .NET 2.0 or later, you need to add a custom Session State Provider (SSP) to your "web.config" as following:
<compilation defaultLanguage ="C#" debug="true" >
<assemblies>
<add assembly="Alachisoft.NCache.SessionStoreProvider,
Version=4.1.0.0,Culture=neutral,
PublicKeyToken=CFF5926ED6A53769"/>
</assemblies>
</compilation>
Please make sure that "Version" above reflects the correct version of NCache.
<sessionState cookieless = "false" regenerateExpiredSessionId = "true" mode = "Custom" customProvider = "NCacheSessionProvider" timeout = "20">
<providers>
<add name = "NCacheSessionProvider" type = "Alachisoft.NCache.Web.SessionState.NSessionStoreProvider" sessionAppId = "NCacheTest" cacheName = "myTestCache" writeExceptionsToEventLog = "false"/>
</providers>
</sessionState>
Please read online help for more details on each of the above properties. For now, just make sure that cacheName="myTestCache" reflects name of the cache you've created.
10. Configure Visual Studio Project for Object Caching
If you're using NCache for ASP.NET Sessions only, then you do not need to do anything here. However, if you're using NCache for object caching where you'll be making NCache API calls, then you need to do the following in your Visual Studio project and also your C# or VB.NET source code.
  1. Reference "Alachisoft.NCache.Web" assembly in your project
  2. Use "using Alachisoft.NCache.Web.Caching;" in your C# files and its equivalent in your VB.NET files.
You can test NCache using the following code example:
Cache cache = NCache.InitializeCache("myCache");
cache.Add("Customer:David:1001","Data");
cache.Get("Customer:David:1001");
cache.Dispose();
11. Run Application and Monitor from NCache Manager
You're now ready to run your application. Once you do, you can watch the cache performance from the Statistics window in NCache Manager. Below is an example:


Topic: Quickly use Cache API in .NET

Quickly use Cache API in .NET

In this section, you will learn to utilize NCache API designed to provide a super rich set of caching features that facilitate you to store/retrieve data for faster access.
In This Section
Initialize Cache
Describes initializing a cache to start working with it.
Adding Items
Explains adding items to the cache.
Finding items
Explains using Cache API to find items from the cache.
Removing Items
Gives procedure to remove items from the cache.
Deleting Items
Gives procedure to delete items from the cache.
Dispose Cache
Illustrates procedure of disposing cache once you are done using it.
Start Cache
Describes starting cache from your application through API.
Stop Cache
Instructs you about stopping cache using Cache API.
See Also
Configuring with NCache Manager
Explains the configuring cache through GUI provided with NCache Manager.
Programmers Guide
Gives a guide for programmers to utilize high performance features provided with NCache.


Topic: Initialize Cache

Initialize Cache

After you have configured the cache, embed NCache API calls in your application to use it. The first thing you need to do is to initialize the cache. Include the following namespace in your project:
using Alachisoft.NCache.Web.Caching;
The code for initializing the cache is as follows:
// Initialize the cache.
Cache _cache = NCache.InitializeCache("myCache");
Initializing Cache in ASP.NET Applications
If you're developing ASP.NET application, the best place to put InitializeCache call is in your Application_Start() functions in Global.asax.cs file. Additionally, instead of hard-coding, we recommend keeping the cache-name in Web.Config and then accessing it from your code. This way, if you will be required to change your cache name at any stage, you won't have to recompile the code.
// Pick up the cache-name from Web.Config
public override void Init()
{
string cacheName = ConfigurationSettings.AppSettings["CacheName"];
Cache _cache = NCache.InitializeCache(cacheName);
}
And, in your Web.Config, you can specify cache name as follows:
<appSettings>
<add key = "CacheName" value = "myCache"/>
</appSettings>
See Also
Adding Items | Finding items | Removing Items | Dispose Cache | Start Cache | Stop Cache


Topic: Start Cache

Start Cache

You need to include following namespace in your application to start the cache using Cache API.
using Alachisoft.NCache.Web.Management;
Starting a local cache
//start the local cache
CacheManager.StartCache("CacheID","Server_Name");
Starting a remote cache
//start the remote cache
CacheManager.StartCache("CacheID","Server_Name");
See Also
Initialize Cache | Adding Items | Finding items | Removing Items | Dispose Cache | Stop Cache


Topic: Adding Items

Adding Items

Once you have a valid cache handle, you can do the "Add" operations. The Add operation has many overloads and the basic overload takes two parameters "key" as string and "value" as object. The value must be a .NET serializable object otherwise NCache will throw a serialization exception if .net serialization or NCache compact serialization is not being used.
Include the following namespace in your project:
using Alachisoft.NCache.Web.Caching;
Using Add Method
An "Add" method will add item to the cache only if that item does not already exist in the cache. Otherwise, it will throw an exception.
  1. Create a new Class named 'Customer' in your already created Test Application.
  2. Insert the following code in the 'Customer' class.
    [Serializable]
    class Customer
    {
    ...
    }
  3. Now insert the following code in the 'Main' of the project:
    static void Main( string [] args)
    {
    Cache _cache = NCache.InitializeCache("myCache");
    _cache.Clear();
    Customer customer = new Customer ();
    customer.name = "David" ;
    customer.customerID = 1001;
    customer.City = "London" ;
    customer.ContactNumber = "+44-xxx-xxxx-xxxx" ;
    customer.IsOrderInProcess = true ;
    // Add Item to Cache
    _cache.Add( "Customer:David:1001", customer);
    Object object_Customer = _cache.Get("Customer:David:1001");
    Customer customerInformation = ( Customer )object_Customer;
    Console.WriteLine("Customer ID: " + customerInformation.customerID);
    Console.WriteLine("Name: " + customerInformation.name);
    Console.WriteLine("City: " + customerInformation.City);
    Console.WriteLine("Contact Number: " + customerInformation.ContactNumber);
    Console.WriteLine("Order placed: " + customerInformation.IsOrderInProcess);
    }
  4. Start the Local Cache 'myCache'.
  5. Run the project.
Using Insert Method
Additionally, you can use "Insert" method to either add or update the item in the cache. Insert method adds item only if it does not already exist in the cache. Otherwise, it updates the item.
  1. Create a new Class named 'Customer' in your already created Test Application.
  2. Insert the following code in the 'Customer' class.
    [Serializable]
    class Customer
    {
    ...
    }
  3. Now insert the following code in the 'Main' of the project:
    static void Main( string [] args){
    Cache _cache = NCache.InitializeCache("myCache");
    _cache.Clear();
    Customer customer = new Customer ();
    customer.name = "David" ;
    customer.customerID = 1001;
    customer.City = "London" ;
    customer.ContactNumber = "+44-xxx-xxxx-xxxx" ;
    customer.IsOrderInProcess = true ;
    // Insert Item to Cache
    _cache.Insert("Customer:David:1001", customer);
    Object objectCustomer = _cache.Get("Customer:David:1001");
    Customer customerInformation = (Customer)objectCustomer;
    Console.WriteLine("Customer ID: " + customerInformation.customerID);
    Console.WriteLine("Name: " + customerInformation.name);
    Console.WriteLine("City: " + customerInformation.City);
    Console.WriteLine("Contact Number: " + customerInformation.ContactNumber);
    Console.WriteLine("Order placed: " + customerInformation.IsOrderInProcess);
    }
  4. Start the Local Cache 'myCache'.
  5. Run the project.
See Also
Initialize Cache | Finding items | Removing Items | Dispose Cache | Start Cache | Stop Cache


Topic: Removing Items

Removing Items

You can remove items from the cache from anywhere in your application using Remove and RemoveAsync methods. Include the following namespace in your project:
using Alachisoft.NCache.Web.Caching;
Using Remove Method
  1. Create a new Class named 'Customer' in your already created Test Application.
  2. Insert the following code in the 'Customer' class.
    [Serializable]
    class Customer
    {
    ...
    }
  3. Now insert the following code in the 'Main' of the project:
    Cache _cache = NCache.InitializeCache("myCache");
    _cache.Clear();
    Customer customer = new Customer ();
    customer.name = "David" ;
    customer.customerID = 1001;
    customer.City = "London" ;
    customer.ContactNumber = "+44-xxx-xxxx-xxxx" ;
    customer.IsOrderInProcess = true ;
    // Add Item to Cache
    _cache.Add("Customer:David:1001" , customer);
    // Removes key from Cache and returns the attached object with it
    Object removedObject = _cache.Remove("Customer:David:1001");
    Customer customerInformation = (Customer)removedObject;
    Console.WriteLine("Customer ID: " + customerInformation.customerID);
    Console.WriteLine("Name: " + customerInformation.name);
    Console.WriteLine("City: " + customerInformation.City);
    Console.WriteLine("Contact Number: " + customerInformation.ContactNumber);
    Console.WriteLine("Order placed: " + customerInformation.IsOrderInProcess);
  4. Start the Local Cache 'myCache'.
  5. Run the project.
See Also
Initialize Cache | Adding Items | Finding items | Dispose Cache | Start Cache | Stop Cache


Topic: Deleting Items

Deleting Items

Once you have a valid cache handle, you can perform "Delete" operations on cache. This operation has many overloads and the basic overload takes only one parameter i.e. "key" as string.
Include the following namespace in your project:
using Alachisoft.NCache.Web.Caching;
Using Delete Method
A "Delete" method will delete item from the cache only if that item already exist in the cache. Exception will be thrown if the method is unable to delete the key from the cache.
  1. Create a new Class named 'Customer' in your already created Test Application.
  2. Insert the following code in the 'Customer' class.
    [Serializable]
    class Customer
    {
    ...
    }
  3. Now insert the following code in the 'Main' of the project:
    static void Main( string [] args)
    {
    Cache _cache = NCache.InitializeCache("myCache");
    _cache.Clear();
    Customer customer = new Customer ();
    customer.name = "David" ;
    customer.customerID = 1001;
    customer.City = "London" ;
    customer.ContactNumber = "+44-xxx-xxxx-xxxx" ;
    customer.IsOrderInProcess = true ;
    // Add Item to the Cache
    _cache.Add("Customer:David:1001", customer);
    // Delete the above Item from the Cache
    _cache.Delete("Customer:David:1001");
    }
  4. Start the Local Cache 'myCache'.
  5. Run the project.
See Also
Initialize Cache | Finding items | Removing Items | Dispose Cache | Start Cache | Stop Cache


Topic: Finding Items

Finding Items

Items can be retrieved from cache either by using Get method or the cache indexer. Both methods are explained below with examples.
Include the following namespace in your project:
using Alachisoft.NCache.Web.Caching;
Using Get Method
Here is how items can be retrieved fom the cache.
Cache _cache = NCache.Caches["myCache"];
// Returns null if item not found
object myObject = _cache.Get("Customer:David:1001");
if (myObject == null)
{
// Item not found
}
Using Cache["key"]
Here is another way to retrieve items from the cache.
Cache _cache = NCache.Caches["myCache"];
// Returns null if item not found
object myObject = _cache["Customer:David:1001"];
if (myObject == null)
{
// Item not found
}
Using Contains Method
You can also check whether an item exists in the cache or not.
Cache _cache = NCache.Caches["myCache"];
// Returns true or false
if (_cache.Contains("Customer:David:1001") == false)
{
// Item found
}
See Also
Initialize Cache | Adding Items | Removing Items | Dispose Cache | Start Cache | Stop Cache


Topic: Dispose Cache

Dispose Cache

After you are done using cache, you can dispose it. Include the following namespace in your project:
using Alachisoft.NCache.Web.Caching;
The code for disposing the cache is as follows:
Cache _cache = NCache.Caches["myCache"];
// Dispose the cache
_cache.Dispose();
Disposing the cache in ASP.NET Applications
If you're developing ASP.NET application, the best place to put Dispose() call is in your HttpApplication's Dispose() method. This method is called when the instance of your HttpApplication is destroyed.
public virtual void Dispose()
{
Cache _cache = NCache.Caches["myCache"];
// Dispose the cache
_cache.Dispose();
}
See Also
Initialize Cache | Adding Items | Finding items | Removing Items | Start Cache | Stop Cache


Topic: Stop Cache

Stop Cache

To stop a cache using Cache API, you need to include the following namespace in your application.
using Alachisoft.NCache.Web.Management;
Stopping a local cache
//stop the local cache
CacheManager.StopCache("CacheID","Server_Name");
Stopping a remote cache
//stop the remote cache
CacheManager.StopCache("CacheID","Server_Name");
See Also
Initialize Cache | Adding Items | Finding items | Removing Items | Dispose Cache | Start Cache


Topic: Quick Start Guide for .NET

Quick Start Guide for .NET

In this section, you will see quick start guides to use NCache.
In This Section
Store ASP.NET 1.1 Sessions
Gives quick steps to use Session State Module.
Store ASP.NET 2.0+ Sessions
Presents a step by step guide to use Session State Store Provider.
Use as ASP.NET Output Cache
Lets you start quickly with Output Caching.
Use as NHibernate L2 Cache
Instructions to setup NCache to work seamlessly with NHibernate.
Use with EntLib Caching Block
Shows how you can benefit from distributed and OutProc cache of NCache with CAB.
Use with .NET 4.0 Cache
Lets you get start with .NET 4.0 cache provider.
Use Dynamic Compact Serialization
Lets you get start with Compact Serialization.
Use App Fabric/Velocity Wrapper
Shows how you can move your Velocity based app to NCache without any code change.
See Also
Quickly Configure and Use NCache
Describes basic steps for smooth installation, configuration and use of NCache.
Cache API
Gives an overview of NCache API with code examples.


Topic: Store ASP .NET 1.1 Sessions

Quick Start with Session State HTTP Module

NCache Session State Module allows you to transparently save and retrieve ASP.NET session-state objects within a webfarm. As compared to ASP.NET Session State Module which is centralized in nature, NCache Session State Module is truly distributed. It benefits from clustered caching and thus, implicitly avoids single point of failure. Also, when running cache as InProc, no extra cost is involved in retrieving session-state objects. The steps below ensure that you easily start using clustered session HTTP Module in your ASP.NET applications.
Step 1: Configure the Cache
Step 2: Edit Web.Config or Machine.Config
Step 3: Start/Restart ASP.NET Application


Topic: Step 1: Configure the Cache

Step 1: Configure the Cache

To use Session State HTTP Module in your application, follow the steps mentioned below. You can either choose to create a Local Cache that resides only on your computer or a Clustered Cache involving multiple computers. For now, we'll create a clustered cache.
  • Launch NCache Manager from Start->Programs->NCache->NCache Manager.
  • Create a new project.
  • Create a new cluster . Select following options from the New Cluster Wizard:
  • Cluster Name: myQSReplicatedCache
  • Cluster Type: Replicated
  • Operation Timeout: 60 sec's (default)
  • Statistics Replication Interval: 600 sec (default)
  • Member Nodes: At least one node.
  • Cluster Port: Any available port
  • Maximum Size: 250MB (default)
  • Eviction: Priority Based (default)
  • Default Priority: Normal
  • Eviction Percentage: 5 (default) (In case of sessions, we recommend to turn off eviction)
  • Clean Interval (sec's.): 15(default)
  • Start the cluster.
  • Verify that cluster is running. For this, determine cache behavior by adding and removing objects from Statistics Window .
  • Clear the cluster to make it ready for your application.
Specifying InProc or OutProc Access Mode
Please note that this cluster has been configured to be used as OutProc. You can verify this by looking at the 'Isolation Level' property on the Main tab of the Cluster details window. If you want to change it to InProc, do the following:
  • Stop the cluster.
  • Go to Main tab .
  • Change Isolation Level to 'Low'. This sets it for InProc. 'High' means OutProc.
  • Apply the changes to the cluster . You will notice that you no longer have the 'myReplicatedCache node->Start' menu enabled. This is because the cluster is now supposed to start as part of your application process.
See Also
Edit Web.Config or Machine.Config | Start/Restart ASP.NET Application


Topic: Step 2: Edit web.config or machine.config

Step 2: Edit web.config or machine.config

After you have configured the cache and have named it 'myQSReplicatedCache', you now need to configure your ASP.NET application to use the Clustered Session HTTP Module that is provided with NCache installation. To do so, you must edit web.config file.
Please follow these steps for enabling NCache Session State Module to transparently save and retrieve ASP.NET session-state objects.
  1. Edit your application's web.config file to add <appSettings> entry under <configuration> section.
    <appSettings>
    <add key = "CacheName" value = "myQSReplicatedCache "/>
    <add key = "sessionAppId " value = " 1234 "/>
    <add key = "exceptionsEnabled " value = " true "/>
    <add key = "enableLogs " value = " false " />
    <add key = "enableDetailLogs " value = " false "/>
    <add key = "clearASPSession " value = " false "/>
    <add key = "writeExceptionsToEventLog " value = " false "/>
    </appSettings>
    For detailed description of different key-value pairs specified above, please see Using NCache Session State Module .
  2. Add <httpmodules> entry under <system.web> section in web.config.
    <httpModules>
    <add name = "NCacheWebSessionState" type = "Alachisoft.NCache.Web.SessionState.NSessionStateModule,
    Alachisoft.NCache.SessionState, Version=x.x.x.x, Culture=neutral, PublicKeyToken=cff5926ed6a53769"/>
    </httpModules>
    Note: Replace version “x.x.x.x” with the actual NCache version that you have.
  1. Add <machinekey> entry under <system.web > section in the web.config. It is required to generate ASP.NET session IDs in the same manner on all nodes.
    <machineKey validationKey = "A01D6E0D1A5D2A22E0854CA612FE5C5EC4AECF24" decryptionKey = "ACD8EBF87C4C8937" validation = "SHA1"/>
Enable Location Affinity for HttpModule
1. Add following section in web.config.
<configSections>
<section name = "ncache" type = "Alachisoft.NCache.Web.SessionStateManagement.NCacheSection,
Alachisoft.NCache.SessionStateManagement, Version=x.x.x.x, Culture=neutral, PublicKeyToken=CFF5926ED6A53769"/>
</configSections>
<ncache>
<sessionLocation >
<primaryCache id = "myQSReplicatedCache" sid-prefix = "abcd"/>
<secondaryCache id = "myQSReplicatedCache2" sid-prefix = "pqrs"/>
<secondaryCache id = "myQSReplicatedCache3" sid-prefix = "wxyz"/>
</sessionLocation>
</ncache>
For detailed description of different key-value pairs specified above, please see Using Location Affinity for Sessions .
Note:
  • Replace version “x.x.x.x” with the actual NCache version that you have.
  • The sid-prefix is a unique identifier that is appended by custom session-ID manager in the beginning of session-ID. sid-prefix length must be equal to 4.
  • When Location Affinity is enabled, "CacheName" specified in <appSettings> section of web.config will be ignored.
2. Enable custom session-ID manager using the sessionIDManagerType attribute of the sessionState element in web.config.
<sessionState mode = "InProc" cookieless = "true" timeout = "20" sessionIDManagerType = "Alachisoft.NCache.Web.SessionStateManagement.CustomSessionIdManager, Alachisoft.NCache.SessionStateManagement"/>
Note:
  • Custom session-ID manager is only supported for .NET 2.0 and later. Thus, for any applications build with earlier versions of .NET, Custom session-ID manager is not required.
See Also
Configure the Cache | Start/Restart ASP.NET Application


Topic: Step 3: Start/Restart ASP.NET Application

Step 3: Start/Restart ASP.NET Application

Now that you have configured a Replicated Cluster through NCache Manager and have edited web.config to add NCache Clustered Session HTTP Module, you're ready to start or restart your ASP.NET application. To restart your ASP.NET application, unload App domain first. This can be done by saving web.config.
See Also
Configure the Cache | Edit Web.Config or Machine.Config


Topic: Store ASP .NET 2.0+ Sessions

Using Session State Store Provider

NCache Session State Provider is a custom SessionStateStoreProviderBase implementation for an ASP.NET application. This implementation reads and writes ASP.NET session data from and to the cache. This allows you to transparently save and retrieve ASP.NET session-state objects within a webfarm NCache also provides the Session State Module which can be used for applications that are intended to run on older .NET frameworks like 1.1.
The steps below are to ensure that you quickly start using Custom Session Store Provider with ease.
Step 1: Configure the Cache
Step 2: Edit Web.Config or Machine.Config
Step 3: Start/Restart ASP.NET App


Topic: Step 1: Configure the Cache

Step 1: Configure the Cache

To use Session State Store Provider in your application, follow the steps written below. You can either choose to create a Local Cache that resides only on your computer or a Clustered Cache involving multiple computers. For now, we'll create a clustered cache.
  • Launch NCache Manager from Start->Programs->NCache->NCache Manager.
  • Create a new project.
  • Create a new cluster . Select following options from the New Cluster Wizard:
  • Cluster Name: myQSReplicatedCache
  • Cluster Type: Replicated
  • Operation Timeout: 60 sec's (default)
  • Statistics Replication Interval: 600 sec (default)
  • Member Nodes: At least one node
  • Cluster Port: Any available port
  • Maximum Size: 250MB (default)
  • Eviction: Priority Based (default)
  • Default Priority: Normal
  • Eviction Percentage: 5 (default) (In case of sessions, we recommend to turn off eviction)
  • Clean Interval (sec's.): 15 (default)
  • Start the cluster.
  • Verify that cluster is running. For this, determine cache behavior by adding and removing objects from Statistics Window .
  • Clear the cluster to make it ready for your application.
Specifying InProc or OutProc Access Mode
Please note that this cluster has been configured to be used as OutProc. You can verify this by looking at the 'Isolation Level' property on the Main tab of the Cluster details window. If you want to change it to InProc, do the following:
  • Stop the cluster.
  • Go to Main tab .
  • Change Isolation Level to 'Low'. This sets it for InProc. 'High' means OutProc.
  • Apply the changes to the cluster . You will notice that you no longer have the 'myCache node->Start' menu enabled. This is because the cluster is now supposed to start as part of your application process.
See Also
Edit Web.Config or Machine.Config | Start/Restart ASP.NET App


Topic: Step 2: Edit web.config or machine.config

Step 2: Edit web.config or machine.config

After you have configured the cache and have named it "myQSReplicatedCache", you now need to configure your ASP.NET application to use the Custom Session Store Provider that is provided with NCache installation. To do so, you must edit web.config file.
Please follow these steps for enabling NCache Session Store Provider to transparently save and retrieve ASP.NET session state:
  • Edit your application's web.config file and modify the <sessionState> section as given below.
    <assemblies>
    <add assembly = "Alachisoft.NCache.SessionStoreProvider, Version=x.x.x.x, Culture=neutral, PublicKeyToken=CFF5926ED6A53769"/>
    </assemblies>
    <sessionState cookieless = "false" regenerateExpiredSessionId = "true" mode = "Custom" customProvider = "NCacheSessionProvider" timeout = "10">
    <providers>
    <add name = "NCacheSessionProvider" type = "Alachisoft.NCache.Web.SessionState.NSessionStoreProvider"
    sessionAppId = "1234" cacheName = "myQSReplicatedCache" writeExceptionsToEventLog = "false"
    enableLogs = "false" enableDetailLogs = "false" exceptionsEnabled = "false"/>
    </providers>
    </sessionState>
    For detailed description of different key-value pairs specified above, please see Using Session State Store Provider .
  • Add <machinekey> entry under <system.web> section of web.config. It is required, so that ASP.NET session IDs are generated in the same manner on all nodes. You can use genmackeys utility available with NCache installation to generate the keys.
    <machineKey validationKey = "A01D6E0D1A5D2A22E0854CA612FE5C5EC4AECF24" decryptionKey = "ACD8EBF87C4C8937"
    validation = "SHA1"/>
Enable Location Affinity for SessionStoreProvider
  • Add following section in web.config.
    <configSections>
    <section name = "ncache" type = "Alachisoft.NCache.Web.SessionStateManagement.NCacheSection,
    Alachisoft.NCache.SessionStateManagement, Version=x.x.x.x, Culture=neutral, PublicKeyToken=CFF5926ED6A53769"/>
    </configSections>
    <ncache >
    <sessionLocation >
    <primaryCache id = "myQSReplicatedCache" sid-prefix = "abcd"/>
    <secondaryCache id = "myQSReplicatedCache2" sid-prefix = "pqrs"/>
    <secondaryCache id = "myQSReplicatedCache3" sid-prefix = "wxyz"/>
    </sessionLocation>
    </ncache>
    For detailed description of different key-value pairs specified above, please see Using Location Affinity for Sessions .
    Note:
  • Replace version “x.x.x.x” with the actual NCache version that you have.
  • The sid-prefix is a unique identifier that is appended by custom session-ID manager in the beginning of session-ID. sid-prefix length must be equal to 4.
  • When Location Affinity is enabled, "CacheName" specified in <providers> section of web.config will be ignored.
  • Enable custom session-ID manager using the sessionIDManagerType attribute of the sessionState element in web.config.
    <sessionState cookieless = "false" regenerateExpiredSessionId = "true" mode = "Custom"customProvider = "NCacheSessionProvider" timeout = "60" sessionIDManagerType = "Alachisoft.NCache.Web.SessionStateManagement.CustomSessionIdManager, Alachisoft.NCache.SessionStateManagement">
See Also
Configure the Cache | Start/Restart ASP.NET App


Topic: Step 3: Start/Restart ASP.NET Application

Step 3: Start/Restart ASP.NET Application

Now that you have configured a clustered cache through NCache Manager and have edited web.config to add NCache Session Store Provider, you're ready to start or restart your ASP.NET application. To restart your ASP.NET application, unload App domain first. This can be done by saving web.config.
See Also
Configure the Cache | Edit Web.Config or Machine.Config


Topic: Use as ASP.NET Output Cache

Quick Start with Output Caching

NOTE: This feature is not available in NCache Express and Professional edition.
NCache provides extremely fast and reliable output caching feature for ASP.NET applications running in web farm environment, where regular output caching fails. Once a page is rendered by any of the web server in the web farm, it is available to the all other servers due to cluster cache created by NCache. Your cached pages are highly available because clustered cache allows no single point of failure. The steps below are to ensure that you quickly start using Output Caching.
Step 1: Configure the Cache
Step 2: Edit Web.Config or Machine.Config
Step 3: Start/Restart ASP.NET Application


Topic: Step 1: Configure the Cache

Step 1: Configure the Cache

NOTE: This feature is not available in NCache Express and Professional edition.
To use Output Cache in your web application, follow the steps mentioned below. You can either choose to create a Local Cache that resides only on your computer or a Clustered Cache involving multiple computers. For now, we'll create a clustered cache.
  • Launch NCache Manager from Start->Programs->NCache->NCache Manager.
  • Create a new project.
  • Select following options from the New Cluster Wizard:
  • Cluster Name: myQSPartitionedCache
  • Cluster Type: Partitioned
  • Operation Timeout: 60 sec's (default)
  • Statistics Replication Interval: 600 sec (default)
  • Member Nodes: At least one node.
  • Cluster Port: Create a new cluster Any available port
  • Maximum Size: 250MB (default)
  • Eviction: Priority Based (default)
  • Default Priority: Normal
  • Eviction Percentage: 5 (default) (In case of session it is recommended that turn off eviction)
  • Clean Interval (sec's.): 15 (default)
  • Start the cluster.
  • Verify that cluster is running. For this, determine cache behavior by adding and removing objects from Statistics Window .
  • Clear the cluster to make it ready for your application.
Specifying InProc or OutProc Access Mode
Please note that this cluster has been configured to be used as OutProc. You can verify this by looking at the 'Isolation Level' property on the Main tab of the Cluster details window. If you want to change it to InProc, do the following:
  • Stop the cluster.
  • Go to Main tab .
  • Change Isolation Level to 'Low'. This sets it for InProc. 'High' means OutProc.
  • Apply the changes to the cluster .
You will notice that you no longer have the 'myPartitionedCache node->Start' menu enabled. This is because the cluster is now supposed to start as part of your application process.
See Also
Edit Web.Config or Machine.Config | Start/Restart ASP.NET Application


Topic: Step 2: Edit Web.Config or Machine.Config

Step 2: Edit Web.Config or Machine.Config

NOTE: This feature is not available in NCache Express and Professional edition.
After you have configured the cache and have named it "myQSPartitionedCache", you now need to configure your ASP.NET application to use the Output Cache Module that is provided with NCache installation. To do so, you must edit web.config file.
Please follow these steps for enabling NCache Output Caching Module to transparently save and retrieve rendered pages.
  1. Register NOutputCache as httpmodule inside <system.web> in web.config file.
    <httpModules>
    <add name = "Alachisoft.NCache.Web.NOutputCache" type = "Alachisoft.NCache.Web.NOutputCache.NOutputCache,
    Alachisoft.NCache.OutputCache, Version=x.x.x.x, Culture=neutral, PublicKeyToken=cff5926ed6a53769"/>
    </httpModules>
    Note: Replace version “x.x.x.x” with the actual NCache version that you have.
  2. Register 'ncache' configuration section in the <configSections> of the web.config as follows:
    <configSections>
    <section name = "ncache" type = "Alachisoft.NCache.Web.NOutputCache.NCacheSection, Alachisoft.NCache.OutputCache, Version=x.x.x.x, Culture=neutral, PublicKeyToken=cff5926ed6a53769"/>
    </configSections>
  3. Then add actual <ncache> section in <configuration> section of web.config holding information of pages to be cached.
    <ncache>
    <outputCacheSettings cacheName = "myQSPartitionedCache" clientCacheName = "" exceptionsEnabled = "true" enableLogs = "false" enableClientCacheSync = "false">
    <outputCachePages>
    <add name = "/NOutputCacheSample/main.aspx" enabled = "true" requestType = "post" duration = "20" varyByParam = "cbxCustomerName" varyByHeader = "Connection" varyByCustom = "browser"/>
    </outputCachePages>
    </outputCacheSettings>
    </ncache>
    For detailed description of different key-value pairs specified above, please see Using Output Cache .
See Also
Configure the Cache | Start/Restart ASP.NET Application


Topic: Step 3: Start/Restart ASP.NET Application

Step 3: Start/Restart ASP.NET Application

NOTE: This feature is not available in NCache Express and Professional edition.
Now that you have configured a cache through NCache Manager and have edited web.config to add NCache Output Caching, you're ready to start or restart your ASP.NET application. To restart your ASP.NET application, kill your ASP.NET process through Task Manager first.
See Also
Configure the Cache | Edit Web.Config or Machine.Config


Topic: Use as NHibernate L2 Cache

Quick Start with NHibernate

NCache provides a second level or process level distributed cache for NHibernate by implementing ICacheProvider and ICache interfaces. You can plug-in NCache to your existing NHibernate application without any code change. Just change your NHibernate configuration file to plug-in NCache as your cache provider and you're all set to start using distributed caching.
This section allows you to get start with NHibernate.
Step 1: Configure the Cache
Step 2: Register NCache with NHibernate
Step 3: Enable DBCacheDependency in NHibernate
Step 4: Run your NHibernate based Application


Topic: Step 1: Configure the Cache

Step 1: Configure the Cache

Create a Clustered Cache named 'myQSReplicatedCache' as follows:
  • Launch NCache Manager from Start->Programs->NCache->NCache Manager.
  • Create a new project.
  • Create a new cluster . Select following options from the New Cluster Wizard:
  • Cluster name: myQSReplicatedCache
  • Cluster Type: Replicated
  • Operation Timeout: 60 sec's (default)
  • Statistics Replication Interval: 600 sec (default)
  • Member Nodes: At least your current computer and maybe others if you want.
  • Cluster Port: 8714
  • Cache Name: Provide a unique identifier for the cache.
  • Maximum Size: 250MB (default)
  • Eviction: Priority based
  • Default Priority: Normal
  • Eviction Percentage: 5 (default)(In case of sessions it is recommended that turn off eviction)
  • Clean Interval (sec's.): 15 (default)
  • Start cluster.
  • Verify that cluster is running. For this, determine cache behavior by adding and removing objects from Statistics Window .
  • Clear cluster to make it ready for your application.
Specifying InProc or OutProc Access Mode
Please note that this cluster has been configured to be used as OutProc. You can verify this by looking at the 'Isolation Level' property on the Main tab of the Cluster details window. If you want to change it to InProc, do the following:
  • Stop cluster
  • Go to Main tab
  • Change Isolation Level to 'Low'. This sets it for InProc. 'High' means OutProc.
  • Apply changes to the cluster . You will notice that you no longer have the 'myQSReplicatedCache node->Start' menu enabled. This is because the cluster is now supposed to start as part of your application process.
See Also
Register NCache with NHibernate | Enable DBCacheDependency in NHibernate | Run your NHibernate based Application


Topic: Step 2: Register NCache with NHibernate

Step 2: Register NCache with NHibernate

To register NCache with NHibernate, edit app.config or web.config as follows:
  1. Register 'nhibernate' and 'ncache' configuration sections in the <configSections> of the web.config or app.config as follows:
    <configSections>
    <section name = "hibernate-configuration" type = "NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
    <section name = "ncache" type = "Alachisoft.NCache.Integrations.NHibernate.Cache.NCacheSection,
    Alachisoft.NCache.Integrations.NHibernate.Cache"/>
    </configSections>
  2. Define section details for <nhibernate> as follows:
    <hibernate-configuration xmlns = "urn:nhibernate-configuration-2.2">
    <session-factory>
    <property name = "cache.provider_class" > Alachisoft.NCache.Integrations.NHibernate.Cache.NCacheProvider, Alachisoft.NCache.Integrations.NHibernate.Cache </property>
    </session-factory>
    </hibernate-configuration>
  3. Define section details for <ncache> as follows:
    <ncache>
    <region name = "default">
    <add key = "cacheName " value =" mycache"/>
    <add key = "enableCacheException" value = "false"/>
    <class name = "nhibernator.BLL.Customer">
    <add key = "priority" value = "1"/>
    <add key = "useAsync" value = "false"/>
    <add key = "relativeExpiration" value = "180"/> or <add key = "staticExpiration" value = "100"/>
    </class>
    </region>
    </ncache>
Note:
  • Calling new Configuration() only reads the <nhibernate> section.
  • Calling no-parameter version of cfg.Configure() configures NHibernate from app.config if it contains <nhibernate-configuration>, otherwise hibernate.cfg.xml is used.
See Also
Configure the Cache | Enable DBCacheDependency in NHibernate | Run your NHibernate based Application


Topic: Step 3: Enable DBCacheDependency in NHibernate

Step 3: Enable DBCacheDependency in NHibernate

To enable Database Cache Dependency in nhibernate items, you need to define <ncache> configuration section in the application's configuration file (it could be app.config file if its a desktop application or web.config file if its a web application) and enable database notifications in the database.
To enable DBCacheDependency in NHibernate, do the following:
  1. Provide dbSync type in <ncache> section as follows:
    <ncache>
    <region name = "default">
    <add key = "cacheName" value = "mycache"/>
    <add key = "enableCacheException " value = "false"/>
    <class name = "nhibernator.BLL.Customer">
    <cacheKey format = "[pk]:Customer:CustomerID"/>
    <sqlDependency sql = "select ContactName from dbo.Customers where CustomerID =?"/>
    </class>
    </region>
    <region name = "Order">
    <add key = "cacheName" value = "CC"/>
    <add key = "enableCacheException" value = "false"/>
    <class name = "nhibernator.BLL.Product">
    <cacheKey format = " [pk]:Product:ProductID"/>
    <sqlDependency sql = " select ProductName from dbo.Product where ProductID =?"/>
    </class>
    </region>
    </ncache>
    The value for dbSync type is either "sqlDependency" or "dbDependency". sqlDependency is a mechanism for synchronizing your cache with SQL Server 2005 database through .NET events. dbDependency allows you to synchronize your cache with any OLEDB compliant database through a configurable polling interval. If you specify "sqlDependency" value, then you must also specify the <sqlDependency sql="..."/> tag for individual classes in <class> section. You specify a "select" SQL statement to identify a row in SQL Server 2005 database that corresponds to this cached item. Then, whenever that row is updated or removed, this cached item is also removed.
  2. Enable database notifications on the database except when you are using SQL Server 2005. For further details see Enabling Database Notifications for SQL Server , Enabling Database Notifications for Oracle and Enabling Database Notifications for DB2 .
See Also
Configure the Cache | Register NCache with NHibernate | Run your NHibernate based Application


Topic: Step 4: Run your NHibernate based Application

Step 4: Run your NHibernate based Application

Before running your application make sure that the cache is running if it is configured as OutProc cache. You may see the statistics of the cache through statistics window.
See Also
Configure the Cache | Register NCache with NHibernate | Enable DBCacheDependency in NHibernate


Topic: Use with EntLib Caching Block

Using NCache with Enterprise Library 4.1 Caching Application Block (CAB)

Caching Application Block (CAB) is part of Enterprise Library from Microsoft. By default, it provides a stand-alone InProc cache. However, if you want to use NCache as a distributed cache for your application that is already using CAB, you can do so without any code change. You only have to make some changes in app.config.
This quick start allows you to get start with using NCache with Caching Application Block.
Step 1: Configure the Cache
Step 2: Register NCache with CAB
Step 3: Run your CAB based Application
See Also
Using NCache with NHibernate
Provides step by step guide along with sample code to use NHibernate with NCache.


Topic: Step 1: Configure the Cache

Step 1: Configure the Cache

Create a Clustered Cache named 'myQSReplicatedCache' as follows:
  • Launch NCache Manager from Start->Programs->NCache->NCache Manager.
  • Create a new project.
  • Create a new cluster . Select following options from the New Cluster Wizard:
  • Cluster name: myQSReplicatedCache
  • Cluster Type: Replicated
  • Operation Timeout: 60 sec's (default)
  • Statistics Replication Interval: 600 sec (default)
  • Member Nodes: At least your current computer and maybe others if you want.
  • Cluster Port: 8714
  • Cache Name: Provide a unique identifier for the cache.
  • Maximum Size: 250MB (default)
  • Eviction: Priority based
  • Default Priority: Normal
  • Eviction Percentage: 5 (default) (In case of session it is recommended that turn off eviction)
  • Clean Interval (sec's.): 15 (default)
  • Start the cluster.
  • Verify that cluster is running. For this, determine cache behavior by adding and removing objects from Statistics Window .
  • Clear the cluster to make it ready for your application.
Specifying InProc or OutProc Access Mode
Please note that this cluster has been configured to be used as OutProc. You can verify this by looking at the 'Isolation Level' property on the Main tab of the Cluster details window. If you want to change it to InProc, do the following:
  • Stop the cluster.
  • Go to Main tab .
  • Change Isolation Level to 'Low'. This sets it for InProc. 'High' means OutProc.
  • Apply the changes to the cluster . You will notice that you no longer have the 'myQSReplicatedCache node->Start' menu enabled. This is because the cluster is now supposed to start as part of your application process.
See Also
Register NCache with CAB | Run your CAB based Application


Topic: Step 2: Register NCache with CAB

Register NCache with EntLib 5.0 CAB using Configuration Console

Following are the steps to register NCache as Custom Cache Manager:
  1. Include Enterprise Librarys Caching.dll, Common.dll, ObjectBuilder2.dll, Unity.dll and Alachisoft's CacheManager.dll references to project.
  2. Add new Caching Application Block through Enterprise Library Configuration Console.
  3. Add a new Custom Cache Manager.
  4. Select NCache CacheManager assembly as a Custom Cache Manager Provider type. You can also specify Custom Cache Manager's name here as shown in the figure.
    You can find "Alachisoft.NCache.EnterpriseLibrary.Caching.CacheManager.dll" file at "%InstallDir%/NCache/bin/assembly/clr20".
  5. Add a key CacheId, and a cache id as value that acts as your primary cache under enterprise library's Caching Application Block.
  6. Add a key CacheExceptions, and its value (true/false) for enabling caching exceptions thrown to client application
  7. Assign Default Cache Manager value to be the cache manager you just have created.
  8. Save the configurations as App.config in your project folder and add it in your project.
  9. Your sample configuration, dealing with NCache as a custom cache manager would look like this.
    Note: Your object must be tagged as serializable while using NCache as your primary store.
See Also
Configure the Cache | Run your CAB based Application


Topic: Step 3: Run your CAB based Application

Step 3: Run your CAB based Application

Before running your application make sure that the cache is running if it is configured as OutProc cache. You can also take a look into a pre-configured sample application that uses NCache as primary Cache Manager.
See Also
Configure the Cache | Register NCache with CAB


Topic: Use with .Net 4.0 Cache

Quick Start with .Net 4.0 Cache Provider

This quick start allows you to get start with NCache using .Net 4.0 Provider.
Step 1: Configure the Cache
Step 2: Configure .Net Provider


Topic: Step 1: Configure the Cache

Step 1: Configure the Cache

Create a Clustered Cache named 'myCache' as follows:
  • Launch NCache Manager from Start->Programs->NCache->NCache Manager.
  • Create a new project.
  • Create a new cluster . Select following options from the New Cluster Wizard:
  • Cluster name: myCache
  • Cluster Type: Replicated
  • Operation Timeout: 60 sec's (default)
  • Statistics Replication Interval: 600 sec (default)
  • Member Nodes: At least your current computer and maybe others if you want.
  • Cluster Port: 8714
  • Cache Name: Provide a unique identifier for the cache.
  • Maximum Size: 250MB (default)
  • Eviction: Priority based
  • Default Priority: Normal
  • Eviction Percentage: 5 (default) (In case of sessions it is recommended that turn off eviction)
  • Clean Interval (sec's.): 15 (default)
  • Start the cluster.
  • Verify that cluster is running. For this, determine cache behavior by adding and removing objects from Statistics Window .
  • Clear the cluster to make it ready for your application.
Specifying InProc or OutProc Access Mode
Please note that this cluster has been configured to be used as OutProc. You can verify this by looking at the 'Isolation Level' property on the Main tab of the Cluster details window. If you want to change it to InProc, do the following:
  • Stop the cluster.
  • Go to Main tab .
  • Change Isolation Level to 'Low'. This sets it for InProc. 'High' means OutProc.
  • Apply changes to the cluster . You will notice that you no longer have the 'myCache node->Start' menu enabled. This is because the cluster is now supposed to start as part of your application process.
See Also
Configure .Net Provider


Topic: Step 2: Configure .Net 4.0 Provider

Quick Start with .NET 4.0 Cache Provider

Following steps need to be followed for using cache provides in your application:
  • Create an application inside Visual Studio.NET.
  • Add following references to your application from "Installed Directory/NCache/integration/DotNet4.0 Cache Provider" path:
    "Alachisoft.NCache.ObjectCacheProvider"
  • Include the following namespace in your project.
    using Alachisoft.NCache.ObjectCacheProvider;
  • Initialize your CacheProvider and pass your cache name to the provider as shown below:
    private ObjectCache _cache;
    private string _cacheId = "myCache" ;
    _cache = new CacheProvider(_cacheId);
  • Now you can perform all cache related operations on your cache using CacheProvider commands.
See Also
Configure the Cache


Topic: Use Dynamic Compact Serialization

Quick Start with Compact Serialization

NOTE: This feature is not available in NCache Express and Professional edition.
This quick start allows you to get start with NCache using Compact Serializable Objects.
Step 1: Register your Compact types with NCache
Step 2: Run your Application


Topic: Step 1: Register Compact Types with NCache

Step 1: Register Compact Types with NCache

NOTE: This feature is not available in NCache Express and Professional edition.
Configure the Cache
Create a Local Cache named "myCache" as follows:
  • Run NCache Manager.
  • Create a new project.
  • Create a new cache . Select following options from New Cache Wizard:
  • Cache Node: It may be the current computer and may be some other if you want.
  • Cache name: myCache
  • Operation Timeout: 60 sec's (default)
  • Statistics Replication Interval: 600 sec (default)
  • Cluster Port: 8714
  • Maximum Size: 250 MB (default)
  • Eviction Policy: Priority based
  • Default Priority: Normal
  • Eviction Percentage: 5 (default) (In case of session it is recommended that turn off eviction)
  • Clean interval (sec.): 15
  • Start the cache.
  • Verify that cache is running. For this, determine cache behavior by adding and removing objects from Statistics Window .
  • Clear the cache to make it ready for your application.
Registering Compact Serializable Types
You can register types one by one through 'add types' button. Perform following steps to register types with the configured cache:
  • Stop the Cache if it is running.
  • Click on the 'Compact Serialization' tab which will open up the following screen.
  • Click 'Add Types' button. A 'Select Compact Classes' dialog box will appear.
  • Browse for the assembly file that contains the compact types by clicking 'Browse' button as shown in the figure.
  • Select the classes you want to register with the cache from the loaded classes list.
  • Press 'Add Class' button to add classes in selected classes list.
  • Click 'Ok'.
  • Newly added types will start appearing in the list box under the 'Compact Serialization' tab having Compact Type and Platform information.
  • 'Remove' will delete the selected type from the registered types list.
  • This shows all the added types. Now arguments can be added with generic types by clicking on 'Add <T>' button.
Registering Generic Compact Types Through Generic Type Handler
There is another way for registering generic compact types through Generic Type Handler. With Generic Type Handler user can add all the Generic types at once by implementing our interface. This is time saving, convenient and gives you option of re-usability. Here is a sample code for this.
public class CustomGenericType<T,K,V>
{
}
public class SetGenerics: IGenericTypeProvider
{
Type[] types = new Type[6];
#region IGenericTypeProvider Members
Type[] IGenericTypeProvider.GetGenericTypes()
{
types[0]=typeof(Dictionary<string, Customer>);
types[1]=typeof(List<int>);
types[2]=typeof(CustomGenericType<Employee, Product, Customer>);
types[3]=typeof(CustomGenericType<Employee, Product, int>);
types[4]=typeof(CustomGenericType<Employee, string, byte>);
types[5]=typeof(CustomGenericType<string, Customer, bool>);
return types;
}
#endregion
}
For registering types follow steps given below.
  • Click on 'Generic Type Handler' button. A 'Select Compact Classes' dialog box will appear.
  • Browse for the assembly file that contains the compact types by clicking the 'Browse' button as shown in the figure.
  • Click 'Ok' button.
  • Apply changes to the cache .
Specifying InProc or OutProc Access Mode
Please note that this cache has been configured to be used as OutProc. You can verify this by looking at the 'Isolation Level' property on the Main tab of the Cache details window. If you want to change Isolation Level, do the following:
  • Stop the cache .
  • Go to the Main tab .
  • Change Isolation Level to 'Low'. This sets it for InProc. 'High' means OutProc.
  • Apply configuration changes to the cache . You will notice that you no longer have the 'myCSCache node->Start' menu enabled. This is because, the cache is now supposed to start as part of your application process.
See Also
Run your Application


Topic: Step 2: Run Your Application

Step 2: Run Your Application

NOTE: This feature is not available in NCache Express and Professional edition.
Before running your application, make it sure that you have deployed the assembly containing compact types. Also, make sure compact types are registered with the cache and cache is running if it is configured as OutProc cache. You may see the statistics of the cache through statistics window.
See Also
Register Compact Types with NCache


Topic: Use App Fabric/Velocity Wrapper API

Quick Start with MS Velocity Wrapper API

NCache facilitates users of MS Velocity to use NCache with least code change manner. User just need to refer NCache based velocity API and re-reference project dependencies. Rest of the work is preserved and would work without any problem.
This section allows you to get start with NHibernate.
Step 1: Configure the Cache
Step 2: Using Velocity Wrapper API
Step 3: Run your Application with NCache based Distributed Caching
Using Regions through NCache Velocity Wrapper API


Topic: Step 1: Configure the Cache

Step 1: Configure the Cache

Create a Clustered Cache named 'myQSReplicatedCache' as follows:
  • Launch NCache Manager from Start->Programs->NCache->NCache Manager.
  • Create a new project.
  • Create a new cluster . Select following options from the New Cluster Wizard:
  • Cluster name: myQSReplicatedCache
  • Cluster Type: Replicated
  • Operation Timeout: 60 secs (default)
  • Statistics Replication Interval: 600 sec (default)
  • Member Nodes: At least your current computer and maybe others if you want.
  • Cluster Port: 8714
  • Cache Name: Provide a unique identifier for the cache.
  • Maximum Size: 250MB (default)
  • Eviction: Priority based
  • Default Priority: Normal
  • Eviction Percentage: 5 (default) (In case of sessions it is recommended that turn off eviction)
  • Clean Interval (secs.): 15 (default)
  • Start the cluster.
  • Verify that cluster is running. For this, determine cache behavior by adding and removing objects from Statistics Window .
  • Clear the cluster to make it ready for your application.
Specifying InProc or OutProc Access Mode
Please note that this cluster has been configured to be used as OutProc. You can verify this by looking at the 'Isolation Level' property on the Main tab of the Cluster details window. If you want to change it to InProc, do the following:
  • Stop the cluster.
  • Go to Main tab .
  • Change Isolation Level to 'Low'. This sets it for InProc. 'High' means OutProc.
  • Apply changes to the cluster . You will notice that you no longer have the 'myQSReplicatedCache node->Start' menu enabled. This is because the cluster is now supposed to start as part of your application process.
See Also
Using Velocity Wrapper API | Run your Application with NCache based caching


Topic: Step 2: Using MS Velocity Wrapper API

Step 2: Using MS Velocity Wrapper API

To enable your existing velocity based app to use NCache, you need to make slight changes in your application. These changes are minimal and not a true code change, rather re-referencing your application to use NCache's Wrapper namespace. NCache supports regions in a different way.
  1. Remove reference to using System.Data.Caching; from your code file.
  2. Add reference to VelocityWrapper assembly named Alachisoft.NCache.Data.Caching.dll placed at %InstallDir%/NCache/bin/assembly/
  3. Add reference to Alachisoft.NCache.Web.dll, present in GAC.
  4. Add the following namespaces:
    using Alachisoft.NCache.Data.Caching;
    using Alachisoft.NCache.Web.Caching;
  5. Give fully qualified name of Cache to resolve ambiguity between Alachisoft.NCache.Web.Caching.Cache vs Alachisoft.NCache.Data.Caching.Cache classes.
Note:
  • For using regions you need to perform few extra steps
  • For defining a cache user need to first create a cache using NCacheManager.
See Also
Configure the Cache | Run your Application | How to use Regions


Topic: Step 3: Run your Application with NCache based Distributed Caching

Step 3: Run your Application with NCache based Distributed Caching

Before running your application make sure that the cache is running. You may see the statistics of the cache through statistics window. You can also take a look into a pre-configured sample application that uses NCache Velocity Wrapper API.
See Also
Configure the Cache | Using Velocity Wrapper API


Topic: Using Regions through NCache Velocity Wrapper API

Using Regions through NCache Velocity Wrapper API

NCache supports regions by creating cache for each region. Here are all the steps to create regions using NCache Velocity Wrapper API.
  1. Open NCache Manager, create a cache with name defaultCache (this is compulsory).
  2. Then create as many caches, as the number of regions you require.
  3. Open the application you are using to make regions, include app.config into your application, then add the keys for the regions using following syntax:
    <configSections>
    <appSettings>
    <add key = "RegionA" value = "CacheA"/>
    <add key = "RegionB" value = "CacheB"/>
    </appSettings>
    </configSections>
  4. Then call CreateRegion method of NCache API to create regions.
See Also
Configure the Cache | Run your Application


Topic: Getting Started for Java

Getting Started for Java

Familiarizes you with the fundamentals of NCache and offers help to use NCache quickly and efficiently.
In This Section
Quickly Configure and Use NCache
Describes basic steps for smooth installation, configuration and use of NCache.
Quickly Use Cache API in JAVA
Describes most common API's provided by NCache with examples for Java users.
Quick Start Guides for JAVA
Provides quick start guides to use java features with NCache.
See Also
Introduction to NCache
Presents a brief introduction to NCache, with an emphasis on new and old features, editions and requirements of NCache.
Configuring the Cache
Discusses configuration options that NCache provides for local and clustered caches. It also helps in configuring NCache through NCache Manager and configuration files.
Developing with NCache
Focuses on what is essential to become skilled at developing with NCache. It includes programmers guide, sample applications, hands on tutorials and extensive help on API reference.


Topic: Getting Started Guide

Getting Started Guide

Here are some basic steps you should follow to ensure a smooth installation, configuration, and use of NCache.
1. Install NCache on Cache Server and Remote Client Machines
Install NCache on all remote client and cache server machines. If you have a separate caching tier, you'll have remote clients. Otherwise, cache will be hosted on your application server.
You can install either 32-bit or 64-version of NCache. 64-bit cache servers work fine with 32-bit clients.
2. Configure Servers for Multiple Network Cards (optional)
If your cache servers (including your app servers if you're hosting cache on them) have multiple network cards, then you must bind NCache to a specific card. You need to specify the following in "Alachisoft.NCache.Service.exe.config" in "NCache/bin/service" folder:
<appSettings>
...
<add key="NCacheServer.BindToClusterIP" value="20.200.20.200" />
<add key="NCacheServer.BindToClientServerIP" value="20.200.20.200" />
...
</appSettings>
NOTE: Anytime you modify "Alachisoft.NCache.Service.exe.config", you must restart NCache Service. You can do this through following commands:
C:/Users/Administrator>net stop ncachesvc
C:/Users/Administrator>net start ncachesvc
You can also bind Client/Server communication to a different network card than the Clustering network card, if you have multiple network cards. Or, you can bind both to the same card (as shown above).
3. Open Firewall TCP Port for Clients (optional)
If there is a firewall between your remote clients and the cache servers, then you must open a TCP port (default 9800) for the remote clients to talk to the cache servers. If you want to change this from 9800 to another port, then you must make changes in all remote client and all cache server machines. On the remote clients, you need to change the "port" value in "client.ncconf" as following:
<configuration>
<ncache-server port = "9800" client-request-timeout = "90" connection-retries = "1" retry-interval = "0" connection-timeout = "5"/>
</configuration>
And, you need to change the "NCacheServer.Port" value in "Alachisoft.NCache.Service.exe.config" file located in "NCache/bin/service" folder on all cache servers as following:
<appSettings>
...
<add key="NCacheServer.Port" value="9800" />
...
</appSettings>
NOTE: Anytime you modify "Alachisoft.NCache.Service.exe.config", you must restart NCache Service (as described above).
All remote clients by default talk to NCache servers on TCP port 9800. So, if there is a firewall between the remote clients and the cache server, then you must open TCP port 9800 in your firewall.
4. Open Firewall TCP Port for Cache Cluster (optional)
If you have a situation where there is a firewall between the cache servers and the cluster must be formed across this firewall, then you must open at least two TCP ports (bi-directional) in this firewall. This port is the Cluster Port specified by you while creating a new clustered cache. For example:
Cluster Port: 7800
Port Range: 1
Open ports 7800. If Port Range is 2, then open 7800 and 7801.
5. Create New Clustered Cache
Run NCache Manager from ONLY ONE location (preferably from one of your cache servers), and create a new clustered cache. You can choose to create one of the following type of caches:
  1. Mirrored Cache
  2. Partitioned Cache
  3. Partitioned Cache with Replicas (recommended)
  4. Replicated Cache
For starters, we recommend to create a Replicated Cache. Later on, you can decide whether a different caching topology meets your requirements better or not. For now, we want to go through the entire process quickly.
6. Test Cache Cluster from Statistics Window
Once you have created a clustered cache, you need to test to make it sure that it works fine. Here are the steps to test the cluster from within NCache Manager.
  1. Start the cache
  2. View Statistics of the cache (right-click menu)
  3. Press Add button on top of the Statistics window. It should add "10" dummy items to the cache. And, the "Count" counter should reflect this. If you have a Replicated Cache, then all cache servers should show the same "Count" value. If that happens, then your cluster is working fine.
7. Remote Client Machines
NCache provides remote client management through NCache Manager. By right click on Client Nodes, context menu will appear having "Add Node" option as shown in figure. By using this option you can add and configure single or multiple client nodes in a clustered cache.
8. Ensure All Objects are Serializable
Whether you're using NCache for Java Sessions or for object caching, you must ensure that all Java objects are serializable. This is true even for those Java objects that you're storing in your Session. Here is how to ensure that:
import java.io.Serializable;
public class Customers implements Serializable
{
...
}
9. Defining Filters for Java Session Module
To ensure the correct caching of sessions, you must apply this filter as the first filter in your deployment descriptor. Filters are executed in the order they are defined in deployment descriptor.
Deployment descriptor is XML file named 'web.xml' located in the WEB-INF directory under the application root directory. The class file containing the filter implementation is 'com.alachisoft.ncache.web.sessionstate.NSessionStoreProvider '.
To create a filter, you must define it first under the <filter> tag and then provide a URL mapping for the filter using <filter-mapping> tag. The following filter configuration means that the filter will be applied to all the URLs in a web application.
<filter>
<filter-name> NCacheSessionProvider </filter-name>
<filter-class> com.alachisoft.ncache.web.sessionstate.NSessionStoreProvider </filter-class>
</filter>
<filter-mapping>
<filter-name> NCacheSessionProvider </filter-name>
<url-pattern> /* </url-pattern>
</filter-mapping>
NCache Session filter can be configured with a number of initialization parameters. The following are the required parameters.
<init-param>
<description> Name of running cache that will be used to persist session state.</description>
<param-name> cacheName </param-name>
<param-value> mycache </param-value>
</init-param>
<init-param>
<description> configPath is used to load the client.ncconf </description>
<param-name> configPath </param-name>
<param-value> %INSTALL_PATH%/config/ </param-value>
</init-param>
%INSTALL_PATH% is the location where NCache is installed.
Following is example of how the deployment descriptor should look like after defining the filter.
<session-config>
<session-timeout> 30 </session-timeout>
</session-config>
<filter>
<filter-name> NCacheSessionProvider </filter-name>
<filter-class> com.alachisoft.ncache.web.sessionstate.NSessionStoreProvider</filter-class>
<init-param>
<description> Name of running cache that will be used to persist session state.</description>
<param-name> cacheName </param-name>
<param-value> mycache </param-value>
</init-param>
<init-param>
<description> configPath is used to load the client.ncconf </description>
<param-name> configPath </param-name>
<param-value> C:/Program Files/NCache/config/ </param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name> NCacheSessionProvider </filter-name>
<url-pattern> /* </url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file> index.jsp </welcome-file>
</welcome-file-list>
</web-app>
10. Deploying application
For deployment details kindly visit Deployment page.
11. Configure Java Project for Object Caching
If you're using NCache for Java Sessions only, then you do not need to do anything here. However, if you're using NCache for object caching where you'll be making NCache API calls, then you need to do the following in your Java project.
1. Reference following files in your project:
  • NCActivate.jar
• NCClient.jar
• NCacheSessionProvider.jar
• NCRuntime.jar
• NCSerialization.jar
• javassist.jar
2. Incude "javaReg.Properties" file into the CLASSPATH of your project.
3. Use import com.alachisoft.ncache.web.caching.*; in your project.
You can test NCache using the following code example:
Cache _cache = NCache.initializeCache("myCache");
_cache.add("Customer:David:1001", customer);
_cache.get("Customer:David:1001");
_cache.Dispose();
12. Run Application and Monitor from NCache Manager
You're now ready to run your application. Once you do, you can watch the cache performance from the Statistics window in NCache Manager. Below is an example:


Topic: Quickly use Cache API in Java

Quickly use Cache API in Java

In this section, you will learn to utilize NCache API designed to provide a super rich set of caching features that facilitate you to store/retrieve data for faster access.
In This Section
Initialize Cache
Describes initializing a cache to start working with it.
Adding Items
Explains adding items to the cache.
Finding items
Explains using Cache API to find items from the cache.
Removing Items
Gives procedure to remove items from the cache.
Deleting Items
Gives procedure to delete items from the cache.
Dispose Cache
Illustrates procedure of disposing cache once you are done using it.
See Also
Configuring with NCache Manager
Explains the configuring cache through GUI provided with NCache Manager.
Programmers Guide
Gives a guide for programmers to utilize high performance features provided with NCache.


Topic: Initialize Cache

Initialize Cache

After you have configured the cache, embed NCache API calls in your application to use it. The first thing you need to do is to initialize the cache. The code for initializing the cache is as follows:
import com.alachisoft.ncache.web.caching.*;
Cache _cache = NCache.initializeCache("myCache");
See Also
Adding Items | Finding items | Removing Items | Dispose Cache


Topic: Adding Items

Adding Items

Once you have a valid cache handle, you can do the "Add" operations. The Add operation has many overloads and the basic overload takes two parameters, "key" as string and "value" as object. The value must be a Java serializable object otherwise NCache will throw a serialization exception.
Using Add Method
Here is how you can add items to the cache. An "Add" method will add item to the cache only if that item does not already exist in the cache. Otherwise, it will throw an exception.
  1. Include the following import statement in your project:
    import com.alachisoft.ncache.web.caching.*;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    import java.io.Serializable;
    public class Customer implements Serializable
    {
    ....
    }
  4. Now insert the following code in the ' Main ' of the project.
    Cache _cache = NCache.initializeCache("myCache");
    _cache.clear();
    Customer customer = new Customer();
    customer.name = "David";
    customer.customerID = 1001;
    customer.setCity("London");
    customer.setContactNumber("+44-xxx-xxxx-xxxx");
    customer.setOrderInProcess(true);
    // Add Item to Cache
    _cache.add("Customer:David:1001", customer);
    Object object_Customer = _cache.get("Customer:David:1001");
    Customer customerInformation = (Customer)object_Customer;
    System.out.println("Customer ID: " + customerInformation.customerID);
    System.out.println("Name: " + customerInformation.name);
    System.out.println("City: " + customerInformation.getCity());
    System.out.println("Contact Number: " + customerInformation.getContactNumber());
    System.out.println("Order placed: " + customerInformation.isOrderInProcess());
  5. Start the Local Cache 'myCache'.
  6. Run the project.
Using Insert Method
Additionally, you can use Insert() to either add or update the item in the cache. Insert() adds the item if it does not already exist in the cache. Otherwise, it updates the item.
  1. Include the following import statement in your project:
    import com.alachisoft.ncache.web.caching.*;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    import java.io.Serializable;
    public class Customer implements Serializable
    {
    ....
    }
  4. Now insert the following code in the 'Main' of the project.
    Cache _cache = NCache.initializeCache("myCache");
    _cache.clear();
    Customer customer = new Customer();
    customer.name = "David";
    customer.customerID = 1001;
    customer.setCity("London");
    customer.setContactNumber("+44-xxx-xxxx-xxxx");
    customer.setOrderInProcess(true);
    // Insert Item to Cache
    _cache.insert("Customer:David:1001", customer);
    Object object_Customer = _cache.get("Customer:David:1001");
    Customer customerInformation = (Customer)object_Customer;
    System.out.println("Customer ID: " + customerInformation.customerID);
    System.out.println("Name: " + customerInformation.name);
    System.out.println("City: " + customerInformation.getCity());
    System.out.println("Contact Number: " + customerInformation.getContactNumber());
    System.out.println("Order placed: " + customerInformation.isOrderInProcess());
  5. Start the Local Cache 'myCache'.
  6. Run the project.
See Also
Initialize Cache | Finding items | Removing Items | Dispose Cache


Topic: Finding Items

Finding Items

Items can be retrieved from the cache either by using Get method or cache indexer. Both methods are explained below with examples. Include the following import statement in your project:
import com.alachisoft.ncache.web.caching.*;
Using Get Method
Here is how you can retrieve items from the cache.
Cache _cache = NCache.initializeCache("myCache");
//returns null if item not found
Object myObject = _cache.get("Customer:David:1001");
if(myObject == null)
{
//item not found
}
Using Contains Method
You can also check whether an item exists in the cache or not.
Cache _cache = NCache.initializeCache("myCache");
//Returns true or false
if(_cache.contains("Customer:David:1001"))
{
//item found
}
See Also
Initialize Cache | Adding Items | Removing Items | Dispose Cache


Topic: Removing Items

Removing Items

You can remove items from the cache from anywhere in your application using Remove and RemoveAsync methods.
  1. Include the following import statement in your project:
    import com.alachisoft.ncache.web.caching.*;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    import java.io.Serializable;
    public class Customer implements Serializable
    {
    ....
    }
  4. Now insert the following code in the 'Main' of the project.
    For Remove Method:
    Cache _cache = NCache.initializeCache("myCache");
    _cache.clear();
    Customer customer = new Customer();
    customer.name = "David";
    customer.customerID = 1001;
    customer.setCity("London");
    customer.setContactNumber("+44-xxx-xxxx-xxxx");
    customer.setOrderInProcess(true);
    _cache.add("Customer:David:1001", customer);
    // Removes object from Cache and returns back the object which was just deleted
    Object removedObject = _cache.remove("Customer:David:1001");
    Customer customerInformation = (Customer)removedObject;
    System.out.println("Customer ID: " + customerInformation.customerID);
    System.out.println("Name: " + customerInformation.name);
    System.out.println("City: " + customerInformation.getCity());
    System.out.println("Contact Number: " + customerInformation.getContactNumber());
    System.out.println("Order placed: " + customerInformation.isOrderInProcess());
    For Remove Item only if it is Latest:
    There are cases where we want to remove the cache item from the Cache only if we have the latest version with us, i.e. not updated by any other instance of the client application. For this specific reason remove overload provided with CacheItemVersion can be used.
    Cache _cache = NCache.initializeCache("myCache");
    _cache.clear();
    Customer customer = new Customer();
    customer.name = "David";
    customer.customerID = 1001;
    customer.setCity("London");
    customer.setContactNumber("+44-xxx-xxxx-xxxx");
    customer.setOrderInProcess(true);
    _cache.add("Customer:David:1001", customer);
    // GetCacheItem Cache Item
    CacheItem cItem = _cache.getCacheItem("Customer:David:1001");
    // Your code ...
    // Remove CacheItem only if you have the latest copy otherwise don't
    Object removedObject = _cache.remove("Customer:David:1001", cItem.getVersion());
    Customer customerInformation = (Customer)removedObject;
    System.out.println("Customer ID: " + customerInformation.customerID);
    System.out.println("Name: " + customerInformation.name);
    System.out.println("City: " + customerInformation.getCity());
    System.out.println("Contact Number: " + customerInformation.getContactNumber());
    System.out.println("Order placed: " + customerInformation.isOrderInProcess());
  5. Start the Local Cache 'myCache'.
  6. Run the project.
See Also
Initialize Cache | Adding Items | Finding items | Dispose Cache


Topic: Deleting Items

Deleting Items

Once you have a valid cache handle, you can do the "Delete" operations on a cache. This operation has many overloads and the basic overload takes only one parameter i.e. "key" as string.
Using Delete Method
A "Delete" method will delete item(s) from the cache only if item(s) already exist in the cache. Exception will be thrown if the method is unable to delete the key from the cache.
  1. Include the following import statements in your project:
    import com.alachisoft.ncache.web.caching.*;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    import java.io.Serializable;
    public class Customer implements Serializable
    {
    …
    }
  4. Now insert the following code in the 'Main' of the project.
    Cache _cache = NCache.initializeCache("myCache");
    _cache.clear();
    Customer customer = new Customer();
    customer.name = "David";
    customer.customerID = 1001;
    customer.setCity("London");
    customer.setContactNumber("+44-xxx-xxxx-xxxx");
    customer.setOrderInProcess(true);
    // Add Item to Cache
    _cache.add("Customer:David:1001", customer);
    // Delete the above Item from the Cache
    _cache.delete("Customer:David:1001");
  5. Start the Local Cache 'myCache'.
  6. Run the project.
See Also
Initialize Cache | Finding items | Removing Items | Dispose Cache


Topic: Dispose Cache

Dispose Cache

After you are done using the cache, you can dispose it. The code for disposing the cache is as follows:
import com.alachisoft.ncache.web.caching.*;
Cache _cache = NCache.initializeCache("myCache");
// Dispose the Cache
_cache.dispose();
See Also
Initialize Cache | Adding Items | Finding items | Removing Items


Topic: Quick Start Guide for Java

Quick Start Guide for Java

In this section, you will see quick start guide to use NCache.
In This Section
Store JSP Sessions
Gives quick steps for storing JSP Sessions.
Use as Hibernate L2 Cache
Instructions to setup NCache to work seamlessly with Hibernate.
Use NCache with Spring
Shows how you can integrate NCache with Spring application.
Use Dynamic Compact Serialization
Lets you get start with Dynamic Compact Serialization.
See Also
Quickly Configure and Use NCache
Describes basic steps for smooth installation, configuration and use of NCache.
Cache API
Gives an overview of NCache API with code examples.


Topic: Store JSP Sessions

Store JSP Sessions

NCache provides no-code change option for Java applications for storing sessions in NCache distributed caching. Here are the steps that you need to follow to configure your Java application for using NCache as a distributed session store. In order to use NCache java session module, you must be running a Servlet 2.3 compatible container (web server). You only need to reference few libraries and add a filter in web.xml of your application so that all the requests will comes to your application through NCache filter.
The steps below are to ensure that you quickly start using Java Session Store Provider with ease.
Step 1: Configure the Cache
Step 2: Add Libraries to your application
Step 3: Define Filter
Step 4: Test your Application


Topic: Step 1: Configure the Cache

Step 1: Configure the Cache

To use JSP Sessions in your application, follow the steps mentioned below. You can either choose to create a Local Cache that resides only on your computer or a Clustered Cache involving multiple computers. For now, we'll create a clustered cache.
  • Launch NCache Manager from Start->Programs->NCache->NCache Manager.
  • Create a new project.
  • Create a new cluster . Select following options from the New Cluster Wizard:
  • Cluster Name: myQSReplicatedCache
  • Cluster Type: Replicated
  • Operation Timeout: 60 sec's (default)
  • Statistics Replication Interval: 600 sec (default)
  • Member Nodes: At least one node
  • Cluster Port: Any available port
  • Maximum Size: 250MB (default)
  • Eviction: Priority Based (default)
  • Default Priority: Normal
  • Eviction Percentage: 5 (default) (In case of sessions, we recommend to turn off eviction)
  • Clean Interval (sec's.): 15 (default)
  • Start the cluster.
  • Verify that cluster is running. For this, determine cache behavior by adding and removing objects from Statistics Window .
  • Clear the cluster to make it ready for your application.
See Also
Add Libraries to your application | Define Filter | Test your Application


Topic: Step 2: Adding Libraries

Step 2: Adding Libraries

You need to add the following libraries into the lib folder of your application's WEB-INF. You can find these Java libraries at following path:
On Linux: %INSTALL_PATH%/ncache/lib/
On Windows: %INSTALL_PATH%/NCache/java/lib/
  • NCacheSessionProvider.jar (The HTTP module implementation for session caching using NCache)
  • NCActivate.jar (The NCache java client library to validate licensing information)
  • NCClient.jar (The NCache java client library that actually implements NCache communication protocol)
  • NCSerialization.jar (The NCache java client library that actually implements dynamic compact serialization and object sharing operations)
Add the following to ‘classes' folder in WEB-INF of your web application:
  • javaReg.properties (The file containing licensing information. You can place this file under ‘classes' directory of your web application).
See Also
Configure the Cache


Topic: Step 3: Defining Filter

Step 3: Defining Filter

  1. After adding the required libraries to your application, you first need to add the filter in the deployment descriptor of your web application. The class file containing the filter implementation is: com.alachisoft.ncache.web.sessionstate.NSessionStoreProvide
  2. To create a filter, you must define it first under the tag <filter> and then provide a URL mapping for the filter <filter-mapping>.
    <filter>
    <filter-name> NCacheSessionProvider </filter-name>
    <filter-class> com.alachisoft.ncache.web.sessionstate.NSessionStoreProvider</filter-class>
    </filter>
    <filter-mapping>
    <filter-name> NCacheSessionProvider </filter-name>
    <url-pattern> /* </url-pattern>
    </filter-mapping>
  3. After creating filter you need to initialize parameters to the filter. NCache Session filter can be configured with a number of initialization parameters.
    <init-param>
    <param-name> cacheName </param-name>
    <param-value> myCache </param-value>
    </init-param>
    <init-param>
    <param-name>configPath </param-name>
    <param-value>usr/local/NCache/Config/</param-value>
    </init-param>
See Also
Configure the Cache


Topic: Step 4: Test your Application

Step 4: Test your Application

Now, you're ready to test your Java web application with NCache. Go to the browser and run your application now you should be able to see item count increasing in NCache Manager Statistics.
See Also
Configure the Cache


Topic: Use Hibernate L2 Cache

Quick Start with Hibernate

NCache provides a second level or process level distributed cache for Hibernate by implementing CacheProvider and Cache interfaces. You can plug-in NCache to your existing Hibernate application without any code change. Just change your Hibernate configuration file to plug-in NCache as your cache provider and you're all set to start using distributed caching.
This section allows you to get start with Hibernate.
Step 1: Configure the Cache
Step 2: Register NCache with Hibernate
Step 3: Run your Hibernate based Application


Topic: Step 1: Configure the Cache

Step 1: Configure the Cache

Create a Clustered Cache named 'myQSReplicatedCache' as follows:
  • Launch NCache Manager from Start->Programs->NCache->NCache Manager.
  • Create a new project.
  • Create a new cluster . Select following options from the New Cluster Wizard:
  • Cluster name: myQSReplicatedCache
  • Cluster Type: Replicated
  • Operation Timeout: 60 sec's (default)
  • Statistics Replication Interval: 600 sec (default)
  • Member Nodes: At least your current computer and maybe others if you want.
  • Cluster Port: 8714
  • Cache Name: Provide a unique identifier for the cache.
  • Maximum Size: 250MB (default)
  • Eviction: Priority based
  • Default Priority: Normal
  • Eviction Percentage: 5 (default) (In case of sessions it is recommended that turn off eviction)
  • Clean Interval (sec's.): 15 (default)
  • Start the cluster.
  • Verify that cluster is running. For this, determine cache behavior by adding and removing objects from Statistics Window .
  • Clear the cluster to make it ready for your application.
See Also
Register NCache with Hibernate | Run your Hibernate based Application


Topic: Step 2: Register NCache with Hibernate

Step 2: Register NCache with Hibernate

Follow these steps to use NCache with Hibernate.
  1. Register 'hibernate' and 'ncache' configuration sections in the <configSections> of the web.config or app.config as follows:
    <configSections>
    <section name = "hibernate-configuration" type = "Hibernate.Cfg.ConfigurationSectionHandler, Hibernate"/>
    <section name = "ncache" type = "Alachisoft.NCache.Integrations.Hibernate.Cache.NCacheSection, Alachisoft.NCache.Integrations.Hibernate.Cache"/>
    </configSections>
  2. Define section details for <hibernate> as follows:
    <hibernate-configuration xmlns = "urn:hibernate-configuration-2.2">
    <session-factory>
    <property name = "cache.provider_class"> Alachisoft.NCache.Integrations.Hibernate.Cache.NCacheProvider, Alachisoft.NCache.Integrations.Hibernate.Cache </property>
    </session-factory>
    </hibernate-configuration>
  3. Define section details for <ncache> as follows:
<ncache>
<region name = "default">
<add key = "cacheName" value = "mycache"/>
<add key = "enableCacheException" value = "false"/>
<class name = "hibernator.BLL.Customer">
<add key = "priority" value = "1"/>
<add key = "useAsync" value = "false"/>
<add key = "relativeExpiration" value = "180"/> or <add key = "staticExpiration" value = "100"/>
</class>
</region>
</ncache>
The above example of app.config or web.config contains following options for you to configure. Each of them is explained below as well.
  • hibernate.cache.provider_class: This option lets you specify that NCache is your second level cache provider. You need to mention two classes that implement Hibernate.Cache.CacheProvider and Hibernate.Cache.Cache interfaces respectively. This is how Hibernate knows how to call this second level cache.
  • The "region" attribute of the NCache determines the Cache in which the particular entity will be cached.
  • cacheName: This option is included inside the <ncache> tag and lets you specify name of the cache that you have configured through NCache Manager. All caches in NCache are named and this name allows NCache provider to connect to the right cache.
  • enableCacheException: This flag allows you to turn on exception handling which by default is turned off. This will throw an exception which you'll have to catch in your java application.
  • class: This lets you specify options specific to a java class. All the options below are class-specific. Class name must be the same as specified in the mapping file of the class (.hbm.xml file).
  • priority: The priority you want to use for items cached. The possible values are from 1 to 6.
  • useAsync: This is a flag that tells the provider whether to use the standard synchronized "Add" and "Insert" or the asynchronous "AddAsync" and "InsertAsync" operations. The asynchronous operations immediately return control back to the client and queues up the operation in a background queue. Then, a background thread executes the command.
  • relativeExpiration: This value is specified as number of seconds. It indicates the idle-time expiration for your items, meaning how long your item can stay without being accessed.
Note:
  • Calling new Configuration() only reads the <hibernate> section.
  • Calling no-parameter version of cfg.Configure() configures Hibernate from app.config if it contains <hibernate-configuration>, otherwise hibernate.cfg.xml is used.
See Also
Configure the Cache | Run your Hibernate based Application


Topic: Step 3: Run your Hibernate based Application

Step 3: Run your Hibernate based Application

Before running your application make sure that the cache is running if it is configured as OutProc cache. You may see the statistics of the cache through statistics window.
See Also
Configure the Cache | Register NCache with Hibernate


Topic: Use NCache with Spring

Quick Start with Spring

NCache is providing support for Spring framework applications. Now users can cache spring applications data using NCache to improve performance of an application. Just few changes are required in deployment descriptor file (which comes with your spring application) to plug-in NCache as your cache provider and you're all set to start using distributed caching.
This section allows you to get start with Spring application.
Step 1: Configure the Cache
Step 2: Register NCache with Spring
Step 3: Run your Spring Application


Topic: Step 1: Configure the Cache

Step 1: Configure the Cache

Create a Clustered Cache named 'myQSReplicatedCache' as follows:
  • Launch NCache Manager from Start->Programs->NCache->NCache Manager.
  • Create a new project.
  • Create a new cluster . Select following options from the New Cluster Wizard:
  • Cluster name: myQSReplicatedCache
  • Cluster Type: Replicated
  • Operation Timeout: 60 sec's (default)
  • Statistics Replication Interval: 600 sec (default)
  • Member Nodes: At least your current computer and maybe others if you want.
  • Cluster Port: 8714
  • Cache Name: Provide a unique identifier for the cache.
  • Maximum Size: 250MB (default)
  • Eviction: Priority based
  • Default Priority: Normal
  • Eviction Percentage: 5 (default) (In case of sessions it is recommended that turn off eviction)
  • Clean Interval (sec's.): 15 (default)
  • Start the cluster.
  • Verify that cluster is running. For this, determine cache behavior by adding and removing objects from Statistics Window .
  • Clear the cluster to make it ready for your application.
See Also
Register NCache with Spring | Run your Spring Application


Topic: Step 2: Register NCache with Spring

Step 2: Register NCache with Spring

Following are the steps required to enable NCache in Spring application:
Step 1: Add Library:
Add "NCacheSpringAnnotation.jar" library to your Spring application. This .jar file is placed at the following path:
"Installeddirectory:/NCache/integration/java/spring".
After adding the library, changes are required in 2 different files:
Step 2: Spring Deployment Descriptor Configurations:
Spring Deployment Descriptor already exist in a spring application, following changes are required to be made in this file:
1. In order to inject NCache Spring Provider, you need to add the following two highlighted attributes in the existing schema:
  • Add xmlns:ncache attribute with its value in the schema.
  • Concatenate the NCache location in xsi:schemaLocation with the already existing location fields, as shown below:
[Modified Schema]
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:ncache="http://www.alachisoft.com/ncache/annotations/spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.alachisoft.com/ncache/annotations/spring http://www.alachisoft.com/ncache/annotations/spring/ncache-spring-1.0.xsd">
2. In Spring Deployment Descriptor, add the following element:
<ncache:annotation-driven>
<ncache:cache id="ID-1" name="mycache"/>
<ncache:cache id="ID-2" name="myreplicatedcache"/>
</ncache:annotation-driven>
"NCache:annotation-driven" tag provides the facility to add number of caches to be used with Spring framework application.
Step 3: Application Level Changes:
NCache is providing number of annotation to perform various cache related tasks. You only need to add those annotations on the top of your methods to perform those tasks.
1. Cacheable:
The purpose of this annotation is to cache the data return by the method with a specific key. Before caching the data, @cacheable generates a method specific key according to the given specifications and cache the data against that key. Here users are supposed to specify the cache id where he/she is interested to cache the data of the method. This annotation is applicable to the methods of a class.
For example:
@Cacheable
(
cacheID="ID-1"
)
public Collection<Message> findAllMessages()
{
Collection<Message> values = messages.values();
Set<Message> messages = new HashSet<Message>();
synchronized (messages) {
Iterator<Message> iterator = values.iterator();
while (iterator.hasNext()) {
messages.add(iterator.next());
}
}
return Collections.unmodifiableCollection(messages);
}

2. Triggers Remove:
As mentioned above, a specific key is required to cache the data of the method. This annotation follows the same procedure for removing the data of a method by generating a similar key with which it is added. The purpose of @triggersremove annotation is to remove the data of a method from the cache by matching the key with the cached keys. To remove data from the cache you need to specify the following attributes:
  • CacheID: Specify the cache id from where the data is to be removed.
  • When: It will specify either data is removed before or after the execution of a method. It take two different values i.e. When.AFTER_METHOD_INVOCATION and When.BEFORE_METHOD_INVOCATION.
  • RemoveAll: If value of this attribute is "False", it will only remove data of a specific key. If value is "True", it will clear the cache and remove all class related data from the cache.
This annotation is applicable to the methods of a class.
For example:
@TriggersRemove
(
cacheID="ID-1",
when = When.BEFORE_METHOD_INVOCATION,
removeAll = false
)
public void updateMessage(long id, String to, String body)
{
Message message = new Message();
message.setId(id);
message.setTo(to);
message.setBody(body);
messages.remove(id);
messages.put(id, message);
}
Note:
You can cache values of two different methods of a class in two different caches.
Two similar annotations can't be used on top of same method.
You can not run @TriggersRemove for two caches on top of the same method.
See Also
Configure the Cache | Run your Spring Application


Topic: Step 3: Run your Spring Application

Step 3: Run your Spring Application

Before running your application make sure that the cache is running if it is configured as OutProc cache. You may see the statistics of the cache through statistics window.
See Also
Configure the Cache | Register NCache with Spring


Topic: Use Dynamic Compact Serialization

Quick Start with Compact Serialization

This quick start allows you to get start with NCache using your Compact Serializable Objects.
Step 1: Register your Compact types with NCache
Step 2: Run your Application


Topic: Step 1: Register Compact Types with NCache

Step 1: Register Compact Types with NCache

Configure the Cache
Create a Local Cache named "myCache" as follows:
  • Run NCache Manager.
  • Create a new project.
  • Create a new cache . Select following options from the New Cache Wizard:
  • Cache Node: It may be the current computer and may be some other if you want.
  • Cache name: myCache
  • Operation Timeout: 60 sec's (default)
  • Statistics Replication Interval: 600 sec (default)
  • Cluster Port: 8714
  • Maximum Size: 250 MB (default)
  • Eviction Policy: Priority based
  • Default Priority: Normal
  • Eviction Percentage: 5 (default) (In case of session it is recommended that turn off eviction)
  • Clean interval (sec.): 15
  • Start the cache.
  • Verify that cache is running. For this, determine cache behavior by adding and removing objects from Statistics Window .
  • Clear the cache to make it ready for your application.
Registering the Compact Serializable Types
Perform the following steps to register your types with the configured cache:
  • Stop the Cache if it is running.
  • Click on the 'Compact Serialization' tab which will open up the following screen.
  • Click 'Add Types' button. A 'Select Compact Classes' dialog will appear.
  • Browse for the assembly file that contains the compact types by clicking 'Browse' button as shown in the figure.
  • Select the classes you want to register with the cache from the loaded classes list.
  • Press 'Add Class' button to add the classes in selected classes list.
  • Click 'Ok'.
  • Newly added types will start appearing in the list box under the 'Compact Serialization' tab having Compact Type and Platform information.
  • 'Remove' will delete the selected type from the registered types list.
  • Apply changes to the cache .
See Also
Run your Application


Topic: Step 2: Run Your Application

Step 2: Run Your Application

Before running your application, make it sure that you have deployed the assembly containing compact types. Also, make sure compact types are registered with the cache and cache is running if it is configured as OutProc cache. You may see the statistics of the cache through statistics window.
See Also
Register Compact Types with NCache


Topic: Configuring NCache

Configuring NCache

This section of the documentation discusses configuration options that NCache provides for local and clustered caches. It helps you configure cache through NCache Manager and configuration files.
In This Section
Configuration Files
Discusses configuration files provided with NCache for both client and server end configurations.
Configuring with NCache Manager
Describes configuring local and clustered caches and their operations through NCache Manager.
Cache Server Configuration
This section explains various cache server configurations.
Configuring with Command Line Tools
This section discusses various command line tools which are categorized in various groups according to the different options available in NCache Management tree.
NCache Monitor for Cache Clusters
Explains NCache Monitor tool designed for monitoring cluster performance.
Command Line Tools
This section explains various command line utilities provided by NCache.
See Also
Introduction to NCache
Provides information regarding features and editions of NCache. It also focuses on hardware and software requirements to use NCache.
Getting Started
Familiarizes you with the fundamentals of NCache and offers help to use NCache quickly and efficiently.
Developing with NCache
Focuses on what is essential to become skilled at developing with NCache. It includes programmers guide, sample applications, hands on tutorials and extensive help on API reference.


Topic: Configuration Files

Configuration Files

This section discusses various configuration files provided by NCache for both client end and server end.
In This Section
Overview
Explains various configuration files and their use.
Client Side Configurations
Describes client side configuration files required for the connection establishment with cache server.
Server Side Configurations
Describes server side configuration files required for cache, security and bridge configurations.


Topic: Overview

Overview

This section of the documentation discusses configuration files that NCache provides for client end and server end. This section helps you to understand how to configure these configuration files. All config files are installed with NCache and is located at " %Install Directory%/NCache/config". Five different config files are installed with NCache which are used to configure the client and server end, i.e.
Client End:
  • Client Configuration File (Client.ncconf)
  • EFCaching Configuration File (Efcaching.ncconf)
Server End:
  • Cache Configuration File (Config.ncconf)
  • Bridge Configuration File (Bridge.ncconf)
  • Security Configuration File (Security.ncconf)
Client configuration file is used by NCache client API to get initial information for establishing connection with server. Modules that need to read the configurations first try to find client.ncconf in application folder. If it doesn't fins client.ncconf in application folder, it then reads the configuration from installation folder. EFCaching configuration file contains information regarding Entity Framework provider which helps in integrating NCache with Entity Framework application.
Cache configuration file contains information regarding all registered caches/clusters. It is used to configure all levels of caches. Modules that need to read the configurations first try to find config.ncconf in application folder. If it doesn't find config.ncconf in application folder, it then reads the configuration from installation folder.
Bridge configuration file contains information regarding all registered bridges. The configuration of all created bridges are store in a single bridge.ncconf file. User can change the configuration of a bridge either from settings of the bridge in NCache Manger or from bridge.ncconf file.
Security configuration file keeps security information that is used by a server node for calling clients. Alachisoft.NCache.NCSecurity.dll at server node is required to provide security services to all clients. Whatever information is required by this assembly, for managing security related issues, is present in security.ncconf file.
See Also
Client Config | Efcaching Config | Cache Config | Security Config | Bridge Config


Topic: Configuring Clients

Configuring Clients

This section is intended to help you in configuring .Net and Java Clients. It also gives you an overview of client configuration file (client.ncconf) required for the connection establishment with cache server and EFCaching configuration file for enabling EFCaching with NCache.
In This Section
Client Config
Describes configuring NCache light-weight Clients through client.ncconf file.
EF Caching Config
Describes configuring EFCaching with NCache through efcaching.ncconf file.


Topic: Client Config

Client Config

Client configuration file is used by NCache client API to get initial information for establishing connection with server. It is located at "%Install Directory%/NCache/config". Modules that need to read the configurations, first try to find client.ncconf in application folder. If client.ncconf is not found in application folder, it then reads the configuration from installation folder.
Client configuration file is used by client to connect to out-proc caches. Light weight client also uses this configuration file to connect to the remote caches. This file is automatically generated each time a new cache/cluster is created or cache/cluster configuration settings are applied. Additionally security information can be provided for each cache in this file.
Client configuration file is explained below:
<configuration>
<ncache-server port="9800" client-request-timeout="90" connection-retries="5" retry-connection-delay="0" retry-interval="1" connection-timeout="5" />
<cache id ="myreplicatedcache" client-cache-id="" client-cache-syncmode="optimistic" load-balance="true">
<server name="server-1"/>
</cache>
<cache id ="mypartitionedcache" client-cache-id="" client-cache-syncmode="optimistic"load-balance="true">
<server name="server-2"/>
</cache>
</configuration>
Client-request-Timeout:
Client-request-timeout is the period for which client API waits for a response for a command from the server. After this period is elapsed an "OperationFailedException" is thrown.
Connection-retries:
connection-retries are the number of retries the client makes on the whole list of servers mentioned in the client.ncconf at the time of connection establishment. It is the same for connection break scenario.
Retry-interval
retry-interval is the time client API waits before going through another iteration of connection-retries.
Connection-timeout:
connection-timeout is the period threads wait before throwing OperationFailedException during connection-break, while one thread tries to establish connection with cache server. If the connection is successfully established, all threads complete their respective operations. Otherwise, all threads throw OperationFailedException.
Retry-connection-delay:
If connection with cache server is dropped then client try to reconnect with the server and retry connection delay flag introduce the delay between each retry. Flag is specified in seconds.
See Also
Client Nodes


Topic: EFCaching Config

EFCaching Config

NOTE: This feature is not available in NCache Express and Professional edition.
EFCaching configuration file contains information regarding Entity Framework provider. It is installed with NCache and is located at "%Install Directory%/NCache/config". efcaching.ncconf is used for enabling NCache in Entity Framework applications. The configurations are stored in an efcaching.ncconf file.
EFCaching configuration file is explained below:
  • Provider Configuration contains cache and caching policy related information. Below are the changes required in efcaching.ncconf.
    <configuration>
    <app-config app-id = "PersonNameApp" mode = "analysis|caching">
  • App-id: Is an identifier for an application. The configuration can contain multiple configuration settings for different applications. App-id for efcaching.ncconf should be same as in application otherwise it will prompt an error.
  • Mode: Can either be "analysis" or "caching". (Hot Applyable)
  • Default = 'caching'
  • "Analysis" mode is used for monitoring the number of times each query executes and then it generates a report. Report contains the Query text and the call count for each query. This report can be used in Custom policy. No caching is done at this mode.
    <analysis-policy log-path = "" analysis-time = "60" cache-enable-threshold = "5" default-expiration-type = "absolute|sliding" default-expiration-time = "180" dbsyncdependency = "true"/>
  • Log-path: Path at which analysis log files will be generated.
Default = < install-dir > /log-files/efcaching-analysis-logs/
  • Analysis-time: Time for which the analysis will run.
  • Default = 60 min
  • Cache-enable-threshold: Caching will automatically be enabled for queries whose call-count exceeds this threshold.
  • Default = 5
  • Default-expiration-type: Default expiration type for analyzed queries.
  • Default = absolute
  • Default-expiration-time: Default expiration time for analyzed queries.
  • Default = 180 sec (3 min)
  • dbsyncdependency: Determine whether to enable database-dependency or not.
  • Default = "true"
  • For "Caching" mode, wrapping provider will cache the results of all the specified queries. Caching mode works on either cacheall policy or custom policy. Both policies have their own specifications. Whenever update is detected (either UPDATE, INSERT or DELETE) in a respective database, the provider invalidates affected cache entries by evicting all cached queries which were dependent on any of the updated tables.
<cache-policy default-policy = "cacheall|custom" database = "none|oracle10i2|sqlserver" cache-id = "mycache" enabled = "true">
  • Default-policy: The default policy for caching. (Hot Applyable)
  • Default = 'cacheall'
  • Database: Database information is collected to create database sync dependency. (Hot Applyable)
  • Default = 'none'
  • Cache-id:
  • Default = 'mycache'
  • Enabled: Determine whether the policy is in effect or not. (Hot Applyable)
  • Default = 'true'
  • For cacheall policy, it caches all the queries and their results.
    <cacheall-policy expiration-type = "absolute|sliding" expiration-time = "1800" dbsyncdependency = "true"/>
  • Expiration-type: Type of expiration, it can be 'sliding' or 'absolute'.
  • Default = 'absolute'.
  • Expiration-time: Default = 180 sec (3 min)
dbsyncdependency: Determine whether to enable the database-dependency or not.
  • Default = 'true'
  • For custom policy, it includes user-configurable list of queries that should be cached with their results. When custom policy is selected, only those queries results will be cached for which the caching is enabled. You can also specify custom caching policy for all queries.
    <custom-policy>
    <query query-text = "" ["SELECT FROM Products"] | stored-procedure-name = "" ] caching = "true" expiration-type = "absolute"| sliding = "" expiration-time = "180" dbsyncdependency = "true"/>
    </custom-policy>
    </cache-policy>
    </app-config>
    </configuration>
  • Query-text: Text of the query whose result is to be cached OR name of a stored procedure whose output is to be cached.
  • Caching: Determines whether caching is enabled for this query or not.
  • Default = 'true'
  • Expiration-type: Type of expiration, it can be 'absolute' or 'sliding'.
  • Default = 'absolute'.
  • Expiration-time: Default = 180 sec (3 min)
  • dbsyncdependency: Determine whether to enable database-dependency for analyzed queries.
  • Default = " true"
  • Incase of stored procedures, query text will be the name of a stored procedure, and there will be no default policy or database sync dependency. User can cache stored procedures result with expiration only, no database dependency is needed here.
See Also
EF Caching Integration | EF Caching Application Plugin | EF Caching Modes


Topic: Server Side

Server Side

This section will help you in configuring .Net and Java Servers. Three types of configuration files are present at server side, which are:
In This Section
Cache Config
Explains config.ncconf file that contains information regarding all registered caches/clusters.
Security Config
Helps enabling NCache security as well as to manage Node and API level security through security.ncconf file.
Bridge Config
Explains bridge.ncconf file that contains information regarding bridges.


Topic: Cache Config

Cache Config

Cache configuration file contains information regarding all registered caches/clusters. It is installed with NCache and is located at "%Install Directory%/NCache/config". Modules that need to read the configurations first try to find config.ncconf in application folder i.e. along side web.config. If config.ncconf is not found in application folder, it then reads the configuration from installation folder.
config.ncconf file is explained below:
<!--
Configuration file (config.ncconf) contains the details of all the registered caches. All caches configurations are enclosed in <configuration></configuration> tag. Whereas each cache detail is enclosed in <cache-config></cache-config>.
-->
<cache-config name="cachepor" inproc="False" config-id="0" last-modified="" type="local-cache" auto-start ="True|False">
Name: Is the cache identifier. Cache will be known by whatever name you will specify here. This is the same name as you specify while initializing cache.
Inproc: Determine whether the cache will run as in-proc (in your application process) or out-proc (in NCache Service process). If set to "False" cache will run as out-proc or if set to "True" then cache will run as in-proc.
Config-id: Is used to determine whether the configuration is modified or not.
Last-modifed: Contains information related to last modification in cache configuration.
Type: Specifies whether the cache is clustered or local cache. This attribute can any of the following:
  • "clustered-cache" means the cache is any of the clustered cache type. i.e; Partition of Replica, Replicated, Partitioned and Mirror.
  • "local-cache" means the cache is a stand-alone cache.
  • "client-cache" means the cache a Local Cache connected to a Clustered Cache.
Auto-Start: This xml tag specifies the auto start status of cache.
<log enabled="True" trace-errors="True" trace-notices="False" trace-warnings="False" trace-debug="False"/>
NCache maintains a log file to write traces for information and debugging purpose. NCache is providing different type of traces as shown in the above xml tag. Using these tags user can enable\disable the various traces. By default only “Error” trace is enabled, rest of the traces are disabled. Error trace does not affect the cache performance but for other traces we recommend not to enable them in a production environment as they affect the performance of NCache. Here log files for each cache will be created at "%Install Directory%/NCache/log-files" location which contains information related to the enabled traces.
<perf-counters enabled="True"/>
Using this xml tag you can enable/disable the publishing of data as perfmon counters:
Enabled: If this attribute is set to "True" NCache will updated the published perfmon counters. If set to "False" then Ncache will not update any of the published perfmon counter.
<replication-strategy synchronous="False"/>
In case of Partition of Replica the you will find this tag in cache configuration. Replication strategy defines how data is replicated to backup node.
Synchronous: This attribute can be set to True/False. If set to "False" then data operation will be replicated asynchronously on the backup node. If set to "True" then data operation will be replicated synchronously on the backup node.
<compression enabled="False" threshold="500kb"/>
This xml tag specifies whether the items greater then specified threshold should be compressed/decompressed at client side.
Enabled: To enable compression set this attribute to "True" otherwise set it to "False"
Threshold: Item greater than the value specified in threshold attribute will only be compressed/decompressed at client side if compression is enabled.
As per above mentioned compression tag example only item greater than 100kb of size will be compressed/decompressed at client side.
<notifications item-remove="False" item-add="False" item-update="False" cache-clear="False"/>
Notification xml tag specifies the registered event with Cache.
Item-add: This attribute can be set to "True" or "False". If set to "True" will notify when an item is added to the cache and similarly if set to "False" no notification will be fired if item is added in cache.
Item-remove: This attribute can be set to "True" or "False". If set to "True" will notify when an item is removed from the cache and similarly if set to "False" no notification will be fired if item is removed in cache.
Item-update: This attribute can be set to "True" or "False". If set to "True" will notify when an item is updated in the cache and similarly if set to "False" no notification will be fired if item is updated in cache.
Item-clear: This attribute can be set to "True" or "False". If set to "True" will notify when cache is cleared and similarly if set to "False" no notification will be fired if the cache is cleared.
<cleanup interval="15sec"/>
Cleanup xml tag specify the periodic interval after which item for expiration will be checked:
Interval: attribute specify the periodic clean up interval. If set to "15sec" this means the expiration check will be performed after every 15sec.
<storage type="heap" cache-size="250mb"/>
Storage xml tag specifies the storage related details for cache:
Type: this attribute can only be set to "heap" as currently ncache only supports heap based storage.
Cache-size: this attribute specifies the upper limit of cache size in MB.
<eviction-policy enabled="True" default-priority="normal" policy="priority" eviction-ratio="5%"/>
This xml tag specifies whether to perform the eviction or not. If eviction is enabled then cache will remove the existing item to accommodate new ones. Exiting items will be removed based on eviction strategy.
Enabled: To enable eviction set this attribute to "True" otherwise set it to "False"
Policy: attribute the eviction policy to be used. Eviction policy can be one of the following:
  • Lru (Least recently used)
  • Lfu (Least frequently used)
  • Priority based
Default-priority: specifies default priority that is associated with an item if no priority is specified for that item. This attribute can be set to following:
  • High
  • Above-normal
  • Normal
  • Below-normal
  • Low
This is only applicable in case of priority based eviction.
Eviction-ratio: specifies how much percentage of data should be evicted when eviction is performed.
<cluster topology="partition-replica" op-timeout="60sec" stats-repl-interval="60sec" use-heart-beat="False">
This xml tag is used for specifying the in-cluster communication details, it also contains a sub tag, channel, which further defines the communication details of the cluster:
Please Note, this tag will not be present in Local Cache.
Topology: Specifies which topology does the cluster follow, it can be either one of the following as provided by NCache
  • Partition Replica Topology
  • Replicated Topology
  • Partitioned Topology
  • Mirror Topology
Op-timeout: (Operation Time Out) Determines the timeout of a connection among the servers if a server in the cluster fails to respond
Stats-repl-interval: (Statistics Replication Interval) the interval provided to the cluster at which to synchronize their information among its servers
Use-heart-beat: Heart Beat is used to monitor the connectivity between nodes
Active-mirror-node: in Mirror topology, only two server nodes are allowed, of which one is active i.e. the one which handles all the request made by the client, here the ip of the active node is provided
<channel tcp-port="8011" port-range="2" connection-retries="0" connection-retry-interval="0secs" initial-hosts="sanfransisco[8011],sanramon[8011]" num-initial-hosts="2"/>
Channel xml tag specifies the details of port connectivity and and other communication options among the cluster servers:
Tcp-port: connection is channeled through a TCP port, this value defines the port which it occupies
Port-range: when initializing, if the port provided is taken by some other application then it will try to establish its connection on port incremented by 1, for this the range is provided i.e. to what range should it search for an available TCP port
Connection-retries: if connection among the node(s) is failed, then this defines how many retries should be done to consider it a permanent faliure
Connection-retry-interval: the interval between connection retries is defined in this value
Initial-hosts: Specifies the server IPs making up the cluster and with their starting port number
Num-initial-hosts: (Number of Initial Hosts) specifies the number of Server Nodes
<alerts>
<email-notification email-notification-enabled="False" sender="" smtp-server="" smtp-port="0" ssl="False" authentication="False" sender-login="" sender-password=""/>
<alerts-types cache-stop="False" cache-start="False" node-left="False" node-joined="False" state-transfer-started="False" state-transfer-stop="False" state-transfer-error="False" cache-size="False"/>
</alerts>
If Event notifications through email is required then information for its setup is configured here:
Email-notification: contains all the information related to the email address
Email-notification-enabled: enables notification through email
Sender : specify the email account from whom the email notifications are sent
Smtp -server: specify the gateway to send email notifications
Smtp -port: The port number used to forward emails
SSL : (Secure Socket Layer) To enable SSL security
Authentication : If any authentication is required, this is to be True
Sender-login : if Authentication is required, specify the login name
Sender-password : Authentication password is entered here
Alert-Types: Specifies at which event an automated email is to be generated
Cache-stop : if the cache is stopped at any moment
Cache-start : at start of cache, email notification is generated
Node-left : when a server node leaves the cluster or if a server node is inaccessible for any reason, email notification will be sent if this is enabled
Node-joined : At joining of any server node
State-Transfer - started : To notify whenever a state transfer is occurred which happens when Load balancing is performed
Cache-size : whenever cache size is changed (Hot Apply-able)
<sql-dependency use-default="False"/>
This xml tag specifies the queuing and service SQL notification architecture.
Use-default: The attribute can be set to True/False. If the attribute is set to "True" then default SQL Dependency service and queue will be created at run time. If the attribute is set to "False" then the custom define SQL Dependency service and queue will be created and used by NCache.
See Also
Configuring Security | Configuring NCache Clients


Topic: Configuring Security

Configuring Security

NOTE: This feature is not available in NCache Express and Professional edition.
Every Server node keeps security information that it has to provide to calling clients. Alachisoft.NCache.NCSecurity.dll at server node is required to provide security services to all clients. Whatever information is required by this assembly, for managing security related issues, is present in security.ncconf file. security.ncconf file helps enabling NCache security as well as to manage Node and API level security. You will find security.ncconf file at "%Install Directory%/NCache/config".
Security.ncconf file is explained below:
<!-- Security Configuration file for NCache 4.1 and later versions -->
<cache-security>
<!-- Change the value true/false to enable or disable security
feature in NCache -->
<enabled>false</enabled>
<!-- LDAP path is required to log-on to domain. -->
<ldap>LDAP://Pdc-america</ldap>
<!-- Following users are Administrators and are allowed to add 'THIS' node
into their clusters and also allowed to perform Cache operations at
API level for all Caches. -->
<ncache-administrators>
<uid>Administrator</uid>
</ncache-administrators>
</cache-security>
  • <enabled> tells users if security is enabled or not (true/false)
  • <ldap> specifies ldap path for active directory server provider. It is the domain controller. NCache uses Microsoft Active Directory Service for authentication of user. User should exist under given domain in LDAP. For more information, see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/adsi/adsi/ldap_adspath.asp
  • <ncache-administrators> keeps list of users having rights on all node-based and API-based operations.
See Also
Performing cache operations in secured environment | Admin level Security | User Level Security | Browsing Domain Users | Configuring API security for client node


Topic: Configuring Bridge

Configuring Bridge

NOTE: This feature is not available in NCache Express and Professional edition.
Bridge configuration file contains information regarding all registered bridges. It is installed with NCache and is located at "%Install Directory%/NCache/config". bridge.ncconf is used whenever you add an existing bridge in NCache Manager. All bridge related configurations are stored in a single bridge.ncconf file. User can change the configuration of a bridge either from NCache Manger or from bridge.ncconf file.
Bridge.ncconf file is explained below:
<bridge-config id="b1799_AP" bridge-nodes="20.200.20.35,20.200.20.32" num-bridge-nodes="2" bridge-active="20.200.20.35" bridge-port="10029" opt-timeout="60" src-cache="" topology="active-passive" replicator-virtual-queue-size="10MB">
Bridge-config Id: Is the bridge identifier. Bridge cache will be known by whatever name you will specify here. This is the same name as you specify while initializing bridge.
Bridge-nodes: IP's of Server nodes involved in making up of this bridge.
Num-bridge-nodes: Number of servers involved in making up of the bridge node.
Bridge-active: This represents the active node in the bridge.
Bridge-port: Port number on which the bridge is hosted.
Opt-timeout: (Operation Timeout) Timeout time after which the bridge will consider itself disconnected from the connected cache(es).
Topology: Specifies which topology does the bridge follow, it can be either one of the following as provided by NCache:
  • Active-Active Topology
  • Active-Passive Topology
  • Hub-Spoke Topology
  • Star Topology
Replicator-virtual-queue-size: It is the size of a virtual queue for the replicator that replicates data from bridge to target cache.
<log enabled="True" trace-errors="True" trace-notices="False" trace-warnings="False" trace-debug="False"/>
NCache maintains a log file to write traces for information and debugging purpose. NCache is providing different type of traces as shown in the above xml tag. Using these tags user can enable\disable the various traces. By default only “Error” trace is enabled, rest of the traces are disabled. Error trace does not affect the cache performance but for other traces we recommend not to enable them in a production environment as they affect the performance of NCache. Here log files for each cache will be created at "%Install Directory%/NCache/log-files" location which contains information related to the enabled traces.
<queue optimized="False" size="500"/>
Size: Specifies the upper limit of queue size in MB. The amount of items in queue is limited by the maximum queue size and amount of free memory.
<perf-counter enabled="True"/>
Perf-counter: It is used to enable Performance counters.
<cache cache-id="replicated cache" status="active|passive" servers-list="20.200.20.35, 20.200.20.20" bulk-operation-size="500" enable-compression="False" connection-retry-interval="3" clear-target-cache="True" heart-beat-enabled="True" replicator-virtual-queue-size="10MB"/>
</bridge-config>
Cache-Id: Is the cache identifier.
Status: Is the status of the cache connected to the bridge. It can either be an active or passive depending on the selected topology.
Servers-List: Server nodes comprising up of the cache clusters.
Bulk-operation-size: Specify an upper limit on the size of the bundled operation that is to be replicated on target cache.
Enable-compression: To enable compression while sending operations on its Target Cache.
Connect-retry-interval: Specifies interval between the two consecutive retries to connect with target cache, if not already connected.
Clear-target-cache: If "true" it will clear the target cache on bridge service startup.
Replicator-virtual-queue-size: It is the size of a virtual queue for the replicator that replicates data from bridge to target cache.
See Also
Performing cache operations in secured environment | Admin level Security | User Level Security | Browsing Domain Users


Topic: Configuring with NCache Manager

Configuring with NCache Manager

This section is about GUI based cache configuration. NCache Manager application provides facility to create clustered and local caches through its rich and user friendly interface. Using NCache Manager application, you can add or remove nodes from the cluster at runtime and can perform various other cache operations. It provides a number of configuration options to configure caches explicitly. NCache Manager allows you to see rich statistics of the entire clustered cache from a single point.
In This Section
GUI Tool Overview
Gives you an overview of NCache Manager.
What's stored in a Project?
Explains all operations that NCache project stores.
Using NCache Manager from multiple locations
Explains how NCache Manager can be access from multiple locations.
Clustered Cache Operation
Explains all operations that NCache offers to perform on clustered caches.
Remote Client Operations
Explains all operations that NCache offers to perform on remote clients.
Client Cache Operations
Shows client cache operations provided by NCache.
Local Cache Operations
Shows local cache operations provided by NCache.
Register Server-Side Code
Explains how to register server side code.
Bridge Topology Operations
Explains all operations that NCache offers to perform on a bridge.
Security
This section explains security related configurations.
Configuration Options
This section discusses various configuration options provided by NCache for both local and clustered caches.


Topic: GUI Tool Overview

GUI Tool Overview

This section is about GUI based cache configuration. NCache Manager application provides you the facility to create clustered and local caches through its rich and user friendly interface. Using NCache Manager application, you can add or remove nodes from the cluster at runtime and can perform various other cache operations. It gives configuration options to configure caches explicitly. NCache Manager allows you to see rich statistics of the entire clustered cache from a single point.
NCache Manager is a central management system. User can administer all server nodes and client nodes activities from a single point. It also provides you the facility to monitor the performance counters of various caches. Moreover, NCache manager gives you an option to set security credentials for both server nodes and client nodes.
You can launch NCache Manager application from Start->Programs->NCache->NCache Manager menu option. The detail is given in next sections. The following screenshot gives you a complete look of NCache Manager.
See Also
Clustered Cache Operation | Remote Client Operations | Client Cache Operations | Local Cache Operations | Bridge Topology Operations | Security


Topic: What's stored in a Project?

What's stored in a Project?

NCache Manager allows you to create a project where you can manage clusters/caches either registered locally or remotely. It can also save all the configuration related information locally in the project file. Project file opens in NCache Manager and loads the same view you saved as a project. Below is a example of project having Clustered Cache, Client Cache, Client Node, Local Cache and a Bridge having a bridge node.
For the above view of NCache Manager the following Project file is created:
<!-- Project file for NCache 4.1 and later versions -->
Cluster Section:
Cluster tab contains cluster related information which is created in this project and it also include all those clusters which are added in a bridge. This project contains two clusters named as ClusteredCache and MirroredCache (added in a bridge) as shown below:
<clusters>
<cache-config name="ClusteredCache" inproc="False" config-id="0" last-modified="" type="clustered-cache" auto-start="False">
<log enabled="True" trace-errors="True" trace-notices="False" trace-warnings="False" trace-debug="False"/>
<perf-counters enabled="True"/>
<conflict-resolver enabled="False" assembly-name="" class-name="" deserialize="False"/>
<replication-strategy synchronous="False"/>
<client-nodes client-cache-id="clientCache3">
<node client-cache-status="disabled" name="20.200.20.57"/>
</client-nodes>
<compression enabled="False" threshold="100kb"/>
<notifications item-remove="False" item-add="False" item-update="False" cache-clear="False"/>
<bridge id="BridgeCache" servers="20.200.20.57" port="9900" status="active" is-target-cache="False"/>
<cleanup interval="15sec"/>
<storage type="heap" cache-size="250mb"/>
<eviction-policy enabled="False" default-priority="normal" policy="lru" eviction-ratio="5%"/>
<cluster topology="partitioned-replicas-server" op-timeout="60sec" stats-repl-interval="600sec" use-heart-beat="False" active-mirror-node="">
<channel tcp-port="7802" port-range="2" connection-retries="10" connection-retry-interval="2secs" initial-hosts="20.200.20.57[7802]" num-initial-hosts="0"/>
</cluster>
<alerts>
<email-notification email-notification-enabled="False" sender="" smtp-server="" smtp-port="0" ssl="False" authentication="False" sender-login="" sender-password=""/>
<alerts-types cache-stop="False" cache-start="False" node-left="False" node-joined="False" state-transfer-started="False" state-transfer-stop="False" state-transfer-error="False" cache-size="False"/>
</alerts>
</cache-config>
<cache-config name="MirroredCache" inproc="False" config-id="0" last-modified="" type="clustered-cache" auto-start="False">
<log enabled="True" trace-errors="True" trace-notices="False" trace-warnings="False" trace-debug="False"/>
<perf-counters enabled="True"/>
<conflict-resolver enabled="False" assembly-name="" class-name="" deserialize="False"/>
<compression enabled="False" threshold="100kb"/>
<notifications item-remove="False" item-add="False" item-update="False" cache-clear="False"/>
<bridge id="BridgeCache" servers="20.200.20.57" port="9900" status="passive" is-target-cache="True"/>
<cleanup interval="15sec"/>
<storage type="heap" cache-size="250mb"/>
<eviction-policy enabled="False" default-priority="normal" policy="lru" eviction-ratio="5%"/>
<cluster topology="mirror-server" op-timeout="60sec" stats-repl-interval="600sec" use-heart-beat="False" active-mirror-node="20.200.20.57">
<channel tcp-port="7811" port-range="1" connection-retries="10" connection-retry-interval="2secs" initial-hosts="20.200.20.57[7811],20.200.20.41[7811]" num-initial-hosts="0"/>
</cluster>
</cache-config>
</clusters>
Local Cache Section:
Local-Cache tab contains information of two types of caches created in this project that is Client Cache and Local Cache. This project contains only one client cache named as clientCache3 and one local cache named as LocalCache as shown below:
<local-caches>
<node id="20.200.20.57">
<!-- Client Cache -->
<cache-config name="clientCache3" inproc="False" config-id="0" last-modified="" type="client-cache" auto-start="False">
<log enabled="True" trace-errors="True" trace-notices="False" trace-warnings="False" trace-debug="False"/>
<perf-counters enabled="True"/>
<compression enabled="False" threshold="100kb"/>
<notifications item-remove="False" item-add="False" item-update="False" cache-clear="False"/>
<cleanup interval="15sec"/>
<storage type="heap" cache-size="250mb"/>
<eviction-policy enabled="True" default-priority="normal" policy="lru" eviction-ratio="5%"/>
</cache-config>
<!-- Local Cache -->
<cache-config name="LocalCache" inproc="False" config-id="0" last-modified="" type="local-cache" auto-start="False">
<log enabled="True" trace-errors="True" trace-notices="False" trace-warnings="False" trace-debug="False"/>
<perf-counters enabled="True"/>
<compression enabled="False" threshold="100kb"/>
<cache-loader retries="0" retry-interval="0" enabled="True">
<provider provider-name="" assembly-name="" class-name="" full-name="" default-provider="False" async-mode="False"/>
</cache-loader>
<notifications item-remove="False" item-add="False" item-update="False" cache-clear="False"/>
<cleanup interval="15sec"/>
<storage type="heap" cache-size="250mb"/>
<eviction-policy enabled="True" default-priority="normal" policy="lru" eviction-ratio="5%"/>
</cache-config>
</node>
</local-caches>
Bridge Section:
Bridge tab contains information related to all bridges created in this project. This project contains only one bridge named as BridgeCache having a bridge-node named as Test, as shown below:
<bridges>
<bridge-config id="BridgeCache" bridge-nodes="20.200.20.57" num-bridge-nodes="1" bridge-active="Test1" bridge-port="10002" opt-timeout="60" src-cache="" topology="active-passive" replicator-virtual-queue-size="10MB">
<queue optimized="False" size="500"/>
<perf-counter enabled="True"/>
<cache cache-id="ClusteredCache" status="active" servers-list="20.200.20.57,20.200.20.35" remote-replication-interval="100" bulk-operation-size="500" enable-compression="False" connection-retry-interval="3" clear-target-cache="True" heart-beat-enabled="True" replicator-virtual-queue-size="10MB"/>
<cache cache-id="MirroredCache" status="passive" servers-list="20.200.20.57,20.200.20.41" remote-replication-interval="100" bulk-operation-size="500" enable-compression="False" connection-retry-interval="3" clear-target-cache="True" heart-beat-enabled="True" replicator-virtual-queue-size="10MB"/>
</bridge-config>
</bridges>
Client Node Section:
Client-node tab contains information related to all client nodes added to the cluster. Here only one client node is added to a cluster having an id 20.200.20.57 as shown below:
<client-nodes>
<node id="20.200.20.57" bind-ip="20.200.20.57">
<configuration>
<ncache-server connection-retries="5" retry-interval="1" client-request-timeout="90" connection-timeout="5" port="9800"/>
<cache id="clusteredcache" client-cache-id="clientCache3" client-cache-syncmode="optimistic" default-readthru-provider="" default-writethru-provider="" load-balance="True">
<server name="20.200.20.57"/>
</cache>
</configuration>
</node>
</client-nodes>
See Also
Clustered Cache Operation | Remote Client Operations | Client Cache Operations | Local Cache Operations | Bridge Topology Operations | Security


Topic: Using NCache Manager from multiple locations

Using NCache Manager from multiple locations

NCache provides you the facility to manage clustered cache from remote locations using NCache Manager. On one hand where NCache brings flexibility and ease for administrators to manage clustered cache from multiple locations, it can some times lead to a situation where inconsistency arises among different machines, i.e.
  1. Inconsistent cache configuration on different cache servers participating in a clustered cache e.g. different "cache size" set by different administrators for a same clustered cache.
  2. Latest cache configuration overwritten by old one e.g. a "priority settings" changed by one server node can not be updated to others.
NCache helps you to avoid the above problem and provides you the ease to access a clustered cache from remote locations. Any modifications made from one server node must be reflected to all server nodes. To reflect the changes made from one node to all other nodes, you need to follow the steps given below:
  1. For any change in cache settings, administrator has to Apply Configuration in order to register that change on all server nodes.
  2. Other server nodes which are accessing the same Clustered Cache must "Refresh" the settings before performing any change in cluster settings.
See Also
Clustered Cache Operation | Remote Client Operations | Client Cache Operations | Local Cache Operations | Bridge Topology Operations | Security


Topic: Clustered Cache Operations

Clustered Cache Operations

This section discusses various operations that can be performed on clusters through NCache Manager.
In This Section
Create a New Clustered Cache
Describes creating a new cluster.
Add Existing Clustered Cache
Explains adding an existing cluster in your project.
Remove a Cache Cluster
Explains procedure of removing a cluster from your project.
Add Node to Cache Cluster
Explains adding a server node to a cluster.
Remove Node from Cache Cluster
Explains removing a server node from a cluster.
Start/Stop a Cache Cluster
Explains starting/stoping a cache cluster.
Restart a Cache Cluster
Explains restart a cache cluster.
Start/Stop a Cache Server
Explains starting/stoping a cache server.
Change Cache Config in NCache Mgr
Describes applying configuration changes to a cluster when it is running.
View Statistics
Briefs how you can see statistics of a running cluster.
Refresh
Tells how and when to refresh a cluster.
Clear Cache Content
Tells how you can clear all contents of a cluster.
Start NCache Service
Explains starting NCache Service on a node.
Stop NCache Service
Describes stopping NCache Service on the node.
Restart NCache Service
Describes restarting NCache Service on the node.
Balance Data Load
Describes balancing data load on a node manually.
Select Network Interface Card
Explains procedure of selecting a network interface card for the server node.
Make Active Node
Explains procedure of making a passive node active in the mirror cache.
Clustered Cache Settings
Explains cluster cache settings.
See Also
Local Cache Operations
Discusses various operations can be performed on local caches.
Client Cache Operations
Discusses variety of operations that can be performed on client cache.


Topic: Create New Clustered Cache

Create New Clustered Cache

A clustered cache can be Mirrored, Partitioned, Partitioned Replica or Replicated. This section describes how to create these caches.
From the 'File' menu select 'New' -> 'Clustered Cache'. A 'New Clustered Cache Wizard' will appear. Steps to create a new clustered cache through wizard are as follows:
Step 1 of 6
Name: Provide a unique identifier for clustered cache. For a cluster, the identifier has to be unique on all the nodes which are part of it.
Step 2 of 6
Cluster Scheme:
Mirrored cache is a cluster of two nodes (Active and passive), where all operations are performed on active node while the passive node is updated asynchronously. Passive node is promoted to active node as soon as the active node goes down. The Partitioned scheme partitions the data across the cluster, whereas the Replicated scheme provides data replication on all the nodes. Partitioned Replica scheme is same as a regular partitioned cache but it allows you to have replicas for each partition, replication can be done either synchronously or asynchronously.
Operation timeout (sec): The maximum time in seconds during which a clustered operation must be completed, otherwise the operation will fail.
Statistics replication interval (sec's.): The time interval in seconds after which a node sends its statistics to all the other nodes in the cluster.
In case of Partitioned Replica cache you can have the choice to select the replication strategy for your cache using the screen shown below. Replication Strategy screen will only be encountered in case of POR.
Replication Strategy: Replication Strategy is defines as how the data is replicated to the backup node. It can be Synchronous or Asynchronous.
  • Asynchronous replication: In Asynchronous replication data operations are replicated asynchronously to the backup node.
  • Synchronous replication: In Synchronous replication data operations are replicated synchronously to the backup node.
Step 3 of 6
In step 3, you will need to select nodes that will participate in cluster.
Select nodes: Select nodes that participate in the cluster. You can specify a node name or select one from the list of available nodes.
Step 4 of 6
Cluster Port: TCP based communication between the cluster nodes requires a well known TCP server port for the establishment of the connection with peers. To avoid conflicts, it is preferable to have a unique port for every cluster. The default port is a proposed nonconflicting port for the cluster by NCache.
You can also change the cluster port manually. In case of port conflict, a warning message will be shown.
Step 5 of 6
Storage Type: Specifies the storage type for the primary cache.
Maximum Size: Specifies an upper limit on the size of the cache in MB. The number of items in the cache are limited by maximum size of the cache and amount of free system memory (virtual or physical).
Step 6 of 6
Eviction Policy: Specifies the eviction policy to determine which items to be removed from cache, if it is full to accommodate new items.
Default Priority: Specifies default priority, that is associated with an item, if no priority is specified for that item in case of priority based eviction.
Eviction Percentage: Specifies the percentage of data to be removed on each eviction.
Clean Interval (sec.): The periodic interval after which the expired items are removed from the cache.
Start this cache on finish: If this check box is checked then this new cache will start automatically as you click the finish.
Using “Start this cache on service startup” option, user will be able to mark the cache as a startup cache which will be started on cache service startup.
See Also
Add Existing Cluster | Refresh a Cluster | Start a Cluster | View Cluster Statistics | Add Server Node | Clear Contents | Remove a Cluster | Apply Configuration


Topic: Add Existing Cluster Cache

Add Existing Cluster Cache

To add an existing Cluster, right click on 'Clusters' from the 'NCache Management' tree and select 'Add Existing Clustered Cache' option from the context menu.
An 'Add Clustered Cache Wizard' will appear with a list of available Clusters. Steps to add an existing cluster through wizard are as follows:
Step 1 of 2
Select a node: Select a running node from where you want to get the existing cluster. You can specify an IP address or select one from the list of available nodes.
Step 2 of 2
Select a clustered cache: Select a clustered cache from the list of available clustered caches on this node. Click finish to end the wizard.
See Also
Create New Cluster | Refresh a Cluster | Start a Cluster | Stop a Cluster | View Cluster Statistics | Add Server Node | Clear Contents | Remove a Cluster | Apply Configuration | Reset Configuration


Topic: Cluster Connectivity

Cluster Connectivity

Connectivity among the nodes of a cluster is very important for cluster operations. Therefore checking the connectivity of cluster is necessary. To check the connectivity of a cluster, NCache provides a dialog showing connectivity among the nodes of specified cluster and details about the status of each node in the cluster.
To View cluster connectivity of two nodes cluster, right click on cluster in the 'NCache Explorer' tree and select 'View Cluster Connectivity' from the context menu.
The dialog given below will appear, showing all the details about connectivity of each node in that cluster.
If any of the cluster node goes down, the cluster connectivity show its status, as shown below.
See Also
Create New Cluster | Add Existing Cluster | Refresh a Cluster | Start a Cluster | Add Server Node | Clear Contents | Remove a Cluster | Apply Configuration


Topic: Clear Contents

Clear Contents

To clear the contents of all nodes of a Cluster, right click on the cluster in the 'NCache Management' tree and select 'Clear Contents' from the context menu.
See Also
Create New Cluster | Add Existing Cluster | Refresh a Cluster | Start a Cluster | View Cluster Statistics | Add Server Node | Remove a Cluster | Apply Configuration


Topic: Apply Cluster Configuration

Apply Cluster Configuration

Apply Configuration:
After any change in cache settings, you need to apply that configuration change in order to register that change on all server nodes. To apply configuration changes on a Cluster, right click on the cluster from 'NCache Management' tree and select 'Apply Configuration' option from the context menu.
Note: Whenever you apply changes to the cluster, it will be stopped and need to be restarted. The client.ncconf is also updated each time you apply configuration. So any custom settings will be lost except the security information.
Hot Apply Configuration:
You can apply configuration changes, which you have made to different options on a Cluster when it is running. To do that, right click on the cluster from 'NCache Management' tree and select 'Hot Apply Configuration' option from the context menu. Changes apply to all nodes in a cluster without stopping it.
Reset Configuration:
To reset configuration of a Cluster, right click on the cluster from 'NCache Management' tree and select 'Reset Configuration' option from the context menu. It will reset all configuration changes to the last saved configuration values for the Cluster.
See Also
Create New Cluster | Add Existing Cluster | Refresh a Cluster | Start a Cluster | Stop a Cluster | View Cluster Statistics | Add Server Node | Clear Contents | Remove a Cluster


Topic: Add Server Node in a Cluster

Add Server Node in a Cluster

A Server Node can be added in cluster any time. After adding a server node in a cluster, you need to start that node so that it can join the cluster. To add a node to a cluster, right click on cluster in the 'NCache Management' tree and select 'Add Server Node' from the context menu.
In either case, a wizard will appear with the list of available nodes. Select a node from the list and click 'Finish'.
The new node will become part of the cluster with the same configurations as of the cluster. A warning message will be shown in case of a port conflict.
See Also
Create New Cluster | Add Existing Cluster | Refresh a Cluster | Start a Cluster | Stop a Cluster | View Cluster Statistics | Clear Contents | Remove a Cluster | Apply Configuration


Topic: View Cluster Statistics

View Cluster Statistics

You can monitor performance of a Cluster either through Performance Monitor (Microsoft Windows NT tool) or NCache Manager. To monitor a Cluster through NCache Manager, right click on the Cluster from 'NCache Management' tree and select 'Statistics' or 'Statistics in New Window' option from the context menu.
If you will select 'Statistics', a view will be opened in the right pane. On the other hand, selecting 'Statistics in New Window' will open a new window for statistics. In both cases, separate graphs will be shown for each node in the cluster. Similarly, you can also view statistics of individual nodes of the cluster by right click on server nodes.
You can select different parameters to be displayed in 'Cluster Performance Test Bed' to analyze cluster performance through 'Tools' -> 'Options' menu option.
For details of the counters, please visit Performance Counter page.
Note: It is suggested that do not turn on all the counters because it will slow down the service.
See Also
Create New Cluster | Add Existing Cluster | Refresh a Cluster | Start a Cluster | Add Server Node | Clear Contents | Remove a Cluster | Apply Configuration


Topic: Start NCache Service

Start NCache Service

To start NCache Service on a Node, right click on the Node in the 'NCache Management' tree and select 'Start NCache Service' from the context menu. It will start the NCache service on that particular node. You can also start the service on a remote machine using the same option.
See Also
Stop NCache Service on a Node | Balance data load | Select Network Interface Card | Make Active Node


Topic: Stop NCache Service

Stop NCache Service

To stop NCache Service on a Node, right click on the Node in the 'NCache Management' tree and select 'Stop NCache Service' from the context menu.
See Also
Start NCache Service on a Node | Balance data load | Select Network Interface Card | Make Active Node


Topic: Restart NCache Service

Restart NCache Service

To restart NCache Service on a Node, right click on the Node in the 'NCache Management' tree and select 'Restart NCache Service' from the context menu.
See Also
Start NCache Service on a Node | Stop NCache Service on a Node | Balance data load | Select Network Interface Card | Make Active Node


Topic: Start/Stop a Cache Server

Start/Stop a Cache Server

To start a server node, right click on the node in the 'NCache Management' tree and select 'Start' from the context menu. On starting a new server node in a cluster will replicate the already existing data on that node (in case of replicated topology).
To stop a server node, right click on the node in the 'NCache Management' tree and select 'Stop' from the context menu.
See Also
Create New Cluster | Add Existing Cluster | Refresh a Cluster | View Cluster Statistics | Add Server Node | Clear Contents | Remove a Cluster | Apply Configuration


Topic: Start/Stop a Cache Cluster

Start/Stop a Cache Cluster

To start a cluster, right click on the cluster in the 'NCache Management' tree and select 'Start' from the context menu. It will start all the server nodes in a cluster.
To stop a cluster, right click on the cluster in the 'NCache Management' tree and select 'Stop' from the context menu.
See Also
Create New Cluster | Add Existing Cluster | Refresh a Cluster | View Cluster Statistics | Add Server Node | Clear Contents | Remove a Cluster | Apply Configuration


Topic: Remove Server Node

Remove Server Node

You can remove a Server Node from a cache cluster. To remove a Server Node, right click on the Node in the 'NCache Management' tree and select 'Remove' from the context menu. The Server Node will be removed from the Cluster.
See Also
Create New Cluster | Add Existing Cluster | Refresh a Cluster | Start a Cluster | View Cluster Statistics | Add Server Node | Clear Contents | Apply Configuration


Topic: Restart a Cluster

Restart a Cluster

Before restarting a cluster, make it sure that your application is not in use otherwise it will throw an exception. "Restart" option will remove all data from the cache. To restart a cluster, right click on the cluster in the 'NCache Management' tree and select 'Restart' from the context menu. It will stop all server nodes in a cluster and give a fresh start to all server nodes.
See Also
Create New Cluster | Add Existing Cluster | Refresh a Cluster | View Cluster Statistics | Add Server Node | Clear Contents | Remove a Cluster | Apply Configuration


Topic: Remove Cluster

Remove Cluster

You can remove a Cluster from your project any time. Removing a cluster will remove all server nodes and replicas along with the Cluster. To remove a Cluster, right click on the Cluster in the 'NCache Management' tree and select 'Remove' from the context menu.
On clicking "Remove" option, manager prompts the following message before removing a cluster. On selecting "Yes", NCache Manager will unregister a cluster from all the cache servers. On selecting "No", cluster will be removed only from the project file.
See Also
Create New Cluster | Add Existing Cluster | Refresh a Cluster | Start a Cluster | View Cluster Statistics | Add Server Node | Clear Contents | Apply Configuration


Topic: Refresh a Cluster

Refresh a Cluster

To refresh a Cluster, right click on the cluster from 'NCache Management' tree and select 'Refresh' option from the context menu. With the help of "Refresh" you can get the current status of every connected server node. It will reload the cache configuration.
See Also
Create New Cluster | Add Existing Cluster | Start a Cluster | View Cluster Statistics | Add Server Node | Clear Contents | Remove a Cluster | Apply Configuration


Topic: Select Network Interface Card

Select Network Interface Card

NCache being a network intensive solution has mainly two kinds of communication going on in a cache cluster.
  1. Cache server to server communication
  2. Cache Client to server communication
NCache can detect all Network Interface Cards (NIC's) on a server node and allows you to choose any. Selected NIC will be used by NCache for cluster wide communication.
If you have two NICs available on a cache server then it is highly recommended to use both NICs for these NCache communications.
NCache will start utilizing both Network Interface Cards (NICs) on Cache Servers, once Dual NIC interface is configured. Using Dual NICs will enhance the overall bandwidth throughput by distributing load on two NICs thus immensely increasing performance. One NIC will be dedicated for server-to-server communication inside the cache cluster and second NIC being reserved only for client-to-server communication. In this way, network load for cache communication is distributed on two NICs and resources will be utilized more efficiently increasing overall performance.
Here is how you can configure NCache dual NIC feature.
How to Configure Dual NICs
There are two ways to configure dual NICs for NCache:
  1. Automatic (through NCache Manager) (Recommended)
  2. Manual (through Configuration files)
Configuration through NCache Manager
  1. Right click on a server node and select 'Select Network Interface Card' option from the context menu.
    NCache will detect and list all the NIC's on that node.
  2. Select NIC of your own choice and press 'Apply'.
  3. Click 'Apply'. You will be prompted to restart NCache Service to work with fresh settings.
  4. Click 'Yes'.
Manual Configuration
For manually specifying separate IPs for NCache cluster server-server communications and client to server communications in order to use two NICs on a cache sever for NCache, you'll have to modify "Alachisoft.NCache.Service.exe.config"
  1. Go to Alachisoft.NCache.Service.exe.config located at:
    %INSTALLATION_PATH%/NCache/bin/service/Alachisoft.NCache.Service.exe.config
  2. Add following line in the configuration file:
    <add key = "NCacheServer.BindToClusterIP" value = "20.200.20.18" />
    <add key = "NCacheServer.BindToClientServerIP" value = "20.200.20.39" />
    BindToClusterIP: You can inform NCache which interface to use for cluster-wide communication. In order to do so, provide the Ip Address you want the cluster server to bind with.
    BindToClientServerIP: You can inform NCache which interface to use for client communication. In order to do so, please provide the Ip Address you want the client's (NCache client) server to bind with.
    Once NCache service IP binding is changed for Dual NICs, you should also make sure that all client nodes configured against this cache cluster should now have their "Client.ncconf" (C:\Program Files\NCache\Config) file updated with the client-server IP address as followed.
    For example, for a cache named 'DemoCache' you need to specify IP address of NIC dedicated for client-server communication in Client.ncconf file on client nodes ( same server IP address that you specified for BindToClientServerIP tag above).
<cache id="DemoCache" client-cache-id="" client-cache-syncmode="optimistic" default-readthru-provider="" default-writethru-provider="" load-balance="True">
<server name="20.200.20.39"/>
In case if your cache cluster consists of two or more nodes and the client.ncconf of other nodes is not updated. Then you will have to use Configure Remote Clients to update client.ncconf of other nodes.
See Also
Start NCache Service on a Node | Stop NCache Service on a Node | Balance data load | Make Active Node


Topic: Balance Data Load

Balance Data Load

NOTE: This feature is not available in NCache Express and Professional edition.
You can request to balance a node in a partitioned cluster without waiting for the automatic load balancing task to trigger it. This brings data load on the node near to average data per node while rest of the data is distributed across other nodes in the cluster. Candidate nodes for accepting load are selected on the bases of amount of data currently present on them. A node having less data gets larger share from the load.
To distribute data evenly across the nodes of a cluster, right click on the cluster in the 'NCache Management' tree and select 'Balance Data Load' from the context menu.
This option is available for partitioned caches only.
See Also
Start the Cache | Start NCache Service on a Node | Stop NCache Service on a Node | Select Network Interface Card | Make Active Node


Topic: Make a node Active

Make a node Active

NOTE: This feature is not available in NCache Express and Professional edition.
In Mirror Cache you have two nodes, Active and Passive. The default node will act as an Active node, where all clients are connected. You can make a passive node active any time. To make a node active, right click on the passive node and select 'Make Active Node' option from the context menu. If the Mirror Cache is stopped then status of the nodes is immediately changed. The passive node becomes active and the active node becomes passive. But if Mirror Cache is running then the status of the nodes is changed only after the cache is restarted.
See Also
Start NCache Service on a Node | Stop NCache Service on a Node | Balance data load | Select Network Interface Card


Topic: Configure Clustered Cache

Configure Clustered Cache

NCache Manager provides ability to change the configuration of Clustered Caches whether Replicated, Partitioned or Partitioned Replica . To change the configuration of a cluster, click the cluster from 'NCache Management' tree. Cluster View will appear in the right pane. This view provides configuration options for the selected cluster.
After Configuring Cache you have to Apply Configurations as well. See how to apply .
Cluster view consists of following tabs:
  • Main
  • Cluster Settings
  • Policies
  • Auto Load Balancing
  • Compact Serialization
  • Query Indexes
  • Backing Source
  • Cache Loader
  • Data Sharing
  • Conflict Resolver
  • Options
  • Security
  • Alerts
Main Tab
  • Clustered Cache Name: A unique identifier for the cluster. For a clustered cache, the identifier has to be unique on all the nodes that are part of it.
  • Clustered Cache Type: Indicates a clustering scheme.
  • Storage Type: Specifies the storage options for the primary cache.
  • Cache Max. Size: Specifies an upper limit on the size of the cache.
  • Isolation Level: Specify application isolation level. A High isolation level implies that the Cache runs in NCache service's process whereas a Low level implies that Cache is InProc to the applications. An OutProc cache can be shared between different applications on the same node. Moreover, an isolated cache's lifetime is explicitly controlled by applications like NCache Manager, Cmd Tools or API's.
  • Auto Start Cache: Using “Auto Start Cache” option, user can set/reset cache starting operation on service start up.
  • Now auto start cache delay time can also be added. To add delay time you have to add following tag in NCache service config file. Value is specified in minutes.
<add key="NCacheSrver.AutoStartDelay" value="5"/>
  • Whenever NCache service will be restarted, all caches which are set to auto start will automatically start after specified delay time interval.
  • After configuring you have to Apply Configurations as well. See how to apply .
Cluster Settings Tab
  • Cluster Port: The port on which cluster communicates.
  • Port Range: Specifies port range for each node in the cluster.
  • Operation timeout (sec.): The maximum time in seconds during which a clustered operation must be completed, otherwise the operation will fail.
  • Statistic replication interval(sec's.): The time interval in seconds after which a node sends its statistics to all the other nodes in the cluster.
  • Use heart beat: When this option is enabled, a node of a cluster will send heart beats to other nodes to show that it is alive, if inactive for specified duration of time. Therefore, if live nodes do not receive heart beats from any idle node after specific duration, they will consider it dead.
  • Retry Interval (sec): It is the time interval between the two successive retries.
  • After configuring you have to Apply Configurations as well. See how to apply .
Policies Tab
  • Eviction Policy: Specifies the eviction policy to determine which items to be removed from cache, if it is full to accommodate new items.
  • Default Priority: Default priority that is associated with an item if no priority is specified for that item in case of priority based eviction.
  • Eviction Percentage: Specifies the percentage of items to be removed on each eviction.
  • Clean Interval (sec.): The periodic interval after which expired items are removed from the cache.
  • After configuring you have to Apply Configurations as well. See how to apply .
Auto Load Balancing (This feature is not available in NCache Express)
  • Auto Load Balancing option is available for partitioned caches only.
  • Enable Auto Load Balancing : To balance data load among all nodes of a cluster automatically after specified period of time, check this option.
  • Balancing Threshold: Threshold is percentage data above average data size per node. Specify threshold value after which automatic balancing task should be started.
  • Balancing Interval (sec): This is periodic interval after which auto load balancing task will be initiated.
  • After configuring you have to Apply Configurations as well. See how to apply .
Compact Serialization Tab (This feature is not available in NCache Express)
  • Add Types : Opens an assembly browser that lets you select the assembly file that contains your compact serialized application objects.
  • Remove : Removes selected types from the registered types list.
  • Add <T> : Adds argument for generic types.
  • Generic Types Handler : Adds generic Types at once.
  • After configuring you have to Apply Configurations as well. See how to apply .
Query Indexes Tab (This feature is not available in NCache Express)
Using Add button select the classes and their attributes you want to index.
Selected assembly displays the list of classes and their attributes on which indexes are required. You can add/remove classes and objects to index the attributes from here.
Backing Source Tab (This feature is not available in NCache Express)
Backing Source tab gives option to enable multiple Read-through and Write-through providers on clustered cache.
  • A cache for which a read-through is enabled can automatically load requested items from data source as if the data is already in the cache. For multiple data sources, multiple read-through providers can be added against a cache. In case of multiple read-through providers you can set a default read-through provider for a cache using the Set as Default button.
Note: Read-Through must be enabled for Cache Forwarding.
  • A write-through or write-behind enabled cache writes updates back to the data source. You can specify multiple write-through providers in case of multiple data sources and can set one of them as a default write-through provider using Set as Default button.
  • After enabling providers for cache you can add providers using Add button. By single click on Add button, "Add New Provider" wizard will appear requiring provider information as shown in the figure.
  • Provider Name: Provider name identifies a unique provider, so for every Read Thru/Write Thru provider, an exclusive provider name must be given.
  • Assembly Name: Browse the assembly name that contains implementation for IReadThruProvider/IWriteThruProvider interface.
  • Class Name: Select the class name from the list that implements IReadThruProvider/IWriteThruProvider interfaces.
  • You can also specify additional configuration parameters that will be passed to the Start method of IReadThruProvider/ IWriteThruProvider.
  • After configuring you have to Apply Configurations as well. See how to apply .
  • You can edit or remove the provider from the list through Edit and Remove button.
  • Deploy Provider: Deploy Provider allow you to copy/update provider assemblies to the cache servers. Use this button to select appropriate assemblies for deployment.
  • After configuring you have to Apply Configurations as well. See how to apply .
Cache Loader Tab
  • Enable Cache Startup Loader: A cache startup loader can automatically loads data specified by the user in the class that implements ICacheLoader interface.
  • Assembly Name: Full path of the assembly that contains implementation for ICacheLoader interface.
  • Class Name: Name of the class that implements ICacheLoader interface.
  • You may specify additional configuration parameters that will be passed to the Start method of ICacheLoader.
  • No. of Retries: Specifies the number of attempts the cache loader will try to load data, if it fails to load data on previous attempt.
  • Retry Interval(sec.): The time interval in seconds between two retry attempts of cache loader.
  • Deploy Cache Loader: Deploy Cache Loader allow you to copy the cache loader assembly to the cache server. Use this button to select the appropriate assembly for deployment.
  • After configuring you have to Apply Configurations as well. See how to apply .
Data Sharing Tab
  • Add Shared Types: Opens an assembly browser that lets you select the assembly/jar files that contains the classes you want to share in cache.
  • Remove: It will remove the particular Shared Type/Class from the list.
  • Import/Export: Shared Type configurations can be import and export in XML file for later use.
  • After configuring you have to Apply Configurations as well. See how to apply .
Conflict Resolver
There could be a situation, when a bridge can try to replicate an operation for a key that already exists in the cache. Conflict Resolver is introduced to resolve the conflict between existing operations and operation replicated from bridge to cache. It decides which key to apply on the cache depending upon defined rules. By default the decision will be made on “Time Based” rule, which keeps the latest key in cache. Users can also define their own rules for conflict resolver.
  • Enable Conflict Resolver: It will automatically load the Conflict Resolver specified by the user in the class that implements IBridgeConflictResolver interface.
  • Assembly Name: Full path of the assembly that contains implementation for IBridgeConflictResolver interface.
  • Class Name: Name of the class that implements IBridgeConflictResolver interface. You can also specify additional parameters which will be passed to the Start method of IBridgeConflictResolve.
  • Deploy Conflict Resolver: Deploy Conflict Resolver allow you to deploy the selected assembly to the cache nodes. Use this button to select the appropriate assemblies for deployment.
  • After configuring you have to Apply Configurations as well. See how to apply .
Options Tab
  • Item add notification: Specifies whether to notify when an item is added to the cache or not.
  • Item remove notification: Indicates whether to notify when an item is removed from the cache or not
  • Item update notification: Denotes whether to notify when an item is updated or not
  • Cache clear notification: Specifies whether to notify when cache is cleared or not.
  • Enable performance counters: Identifies whether performance counters are enabled or not. Performance counters are used to show statistics of the cache.
  • Enable Compression: Shows compression is enabled or not. If enabled, items having size greater than the specified threshold will be compressed.
  • Use Custom SQL Notification Mode: It allows you to create your own SQL notification service and queue. Otherwise default service and queue will be created and used at run time.
  • After configuring you have to Apply Configurations as well. See how to apply .
Security
Administrator and NCache manager can configure API level security for a cache. Each cache will have its own API security configurations independent of other caches and users. Cache API security configurations will be saved in config.ncconf against each cache. NCache Manager provides the above wizard for configuring API security for caches.
Now data can be sent and stored in cache in encrypted form. 3DES encryption algorithm is used to secure data, it uses three successevie iterations of DES. User can enable encryption by selecting "Enable" option and then providing Key value of length 24.
After configuring you have to Apply Configurations as well. See how to apply .
Alerts
Using Alerts tab view you can specify different parameters for email notifications.
  • Enable Email Notifications: Email notifications will be enabled by selecting an Enable Email Notifications check box .
  • Sender Email: Enter the sender email Id.
  • SMTP Server: Specify the SMTP server name.
  • Port: Default port of a server is 25 but you can change it.
  • SSL Required: Secure Server Layer if enabled then email should be send through SSL channel.
  • Authentication Required: If the option is enabled then login and password will be required for authentication.
  • Login: User name only required if 'Authentication' is enabled.
  • Password: Password is required only if 'Authentication' is enabled.
  • To: Specify email recipients (more then one recipient can be specified in this area).
  • Select the events for which the notification is required, listed on the tab.
  • After configuring you have to Apply Configurations as well. See how to apply .
See Also
Configure Local Cache | Configuration Options


Topic: Remote Client Operations

Remote Client Operations

This section explains operations that can be performed on a Remote client node.
In This Section
Add Remote Client
Describes adding a Remote client node.
Remove Remote Client
Describes removing a Remote client node.
Clear Cache Contents
Explains procedure for clearing cache contents.
Remote Client Settings
Describes Remote Client settings.
See Also
Cluster Cache Operations
Discusses variety of operations that can be performed on clustered cache.
Client Cache Operations
Discusses variety of operations that can be performed on client cache.


Topic: Overview

Overview

You can decide whether to run client applications on server nodes (nodes which are participating in cache cluster) or access cache remotely. In case of remote client access, you have to install NCache on remote node and your application will use same API to access cache remotely.
Bare sockets are used for client server communication due to which no dependency on metadata exists. Moreover, there is no extra serialization/deserialization expense. Because of bare sockets, any application other than .Net can also communicate with server. You can specify port for NCache Server, for client server communication, in Alachisoft.NCache.Service.exe.config file.
Client requests are validated by the server and then forwarded to the cache for further processing. Similarly, results from cache are sent back to client application. Every client trying to use cache connects to server via NCache Client API. When client initializes cache, it gets connected to NCache server. NCache server associates the specified cache instance with client connection and any further requests by that client are routed to that specific cache only i.e. NCache server can maintain state. It also means, a single client application can have more than one connection with NCache Server each associated with different cache instance, thus multiple cache instances per application .
When .Net client resides on server node, it can access cache either in InProc or OutProc . However, Java client accesses cache as Outproc, locally.
Both .NET and Java clients can access cache across the network seamlessly. Client API for local and remote clients is same. Remote clients also have failover capability. If their connected server goes down, clients will be automatically connected to the next server in the list. List is dynamically updated at run time as new servers join the cluster.
See Also
Configure Remote Client


Topic: Remote Client Node

Remote Client Node

NCache Manager provides you the wizard for adding client nodes in a cluster. Certain changes are made to make this feature more flexible and easy to use and provided a GUI interface to configure remote clients. You can manage remote clients and can change their configuration from NCache Manager. You don't have to manage security manually through the configuration files anymore, everything can be done through NCache Manager now. Each clustered cache tree in NCache explore contains a node known as "Client Nodes" used for adding a client node in a cluster. Any number of client nodes can be added in a clustered environment using this option.
View Remote Client
Select Clustered Cache to view the nodes in the tree.
Add Remote Client
This step shows how to add a remote client node in a cluster. By right click on "Client Nodes" node, context menu will appear having "Add Node" option. Using this option you can add a single or multiple client nodes in a clustered cache.
On selecting "Add Node" option, Add Node Wizard appears which collects the details required for adding client node(s).
More than one clients can be added in a cluster using the above option. On adding a client node, NCache Service will be connected to a selected client machine.
Press the Finish button to complete the process. The newly added client node will start appearing under the Client Nodes heading in a cluster tree. The following figure shows the updated cluster explorer view.
Remove Remote Client
You can remove a specific client node from cluster by right click on it and selecting "Remove" option from the context menu. The context menu of a client node provides you the facility to apply/reset configuration on a node using Apply Configuration and Reset Configuration options. You can view the statistics of a client cache (in same window or in new window) residing on the selected node using "Client Cache Statistics" and "Client Cache Statistics in New Window" option from the context menu.
Enable/Disable Client Cache
Enable/Disable Client Cache options are available at every client node. These options will not have an effect on working of other client nodes in same cluster.
Once a client cache is disabled using the "Disable Client Cache" option, it will not be deleted from that node. The cache will reside in deactivated form and can be enabled any time by using "Enable Client Cache" option.
  • Enable client cache: will start the cache and enable client cache on the client machine.
  • Disable client cache: will stop cache and disable client cache on the client machine.
Clear Client Cache
Clear Client Cache option is available in context menu of a client node as shown in figure below. It is used to clear client cache content for that node only.
See Also
Create Client Cache


Topic: Configure Remote Client

Configure Remote Client

NCache Manager gives the option to change configuration settings of Remote Clients. To change configuration of a Remote Client, click the node from 'NCache Management' tree. Remote Client View will appear in the right pane. Given snippet shows configuration options of the Remote Client node.
Main Settings
This screenshot shows cache server settings.
  • Connection Timeout (sec.): connection-timeout is a time period for which threads wait before throwing an "OperationFailedException" during connection break down. In this case one thread tries to establish connection with cache server. If the connection is successfully established, all threads complete their respective operations. Otherwise, all threads will throw OperationFailedException.
  • Connection Retries: connection-retries are the number of retries the client makes on the whole list of servers mentioned in the client.ncconf at the time of connection establishment. It is same for connection break down scenario.
  • Retry Interval (sec.): retry-interval is the time for which a client API waits before going through another iteration of connection-retries.
  • Client Request Timeout (sec.): Client-request-timeout is a time period for which a client API waits for a command response from the server. After this period an "OperationFailedException" will be thrown.
Settings
This snippet shows cache level settings.
  • Enable Client Load Balancing: Load balance is "on" by default. If cache is replicated and load balancing is "off" then you can change the priority order of the servers otherwise priority won't matter.
  • Server Priority: Server order is changeable by selecting a specific IP and using the up, down buttons.
  • Client Cache Id shows the name of a client cache running on a selected client node (read only value).
  • Sync Mode: You can change the Sync Mode of a client cache running on a selected client node from this page. It will override the default settings of a client cache only for this node.
  • Sync mode: Client cache is synchronized with the clustered caches through events. It might be possible that client caches are not synchronized with clustered cache for a small period of time. If during this time user gets an item from the client cache, he/she may get an old version. This is the "Optimistic" mode of synchronization. In "Pessimistic" mode of synchronization, client cache always checks for the "version" of the cached item before returning it to the application.
Security
This screenshot shows user credentials required to connect the cache server. If security is enabled, client uses the security credentials to connect with the cache servers. User can provide login details on this page.
Backing Source Settings
This screenshot shows Read-through and Write-through provider options. You can specify the default provider by selecting the respective provider from the list.
See Also
Create Client Cache | Configuration Options


Topic: Client Cache Operations

Client Cache Operations

This section explains operations that can be performed on a client cache.
In This Section
Create Client Cache
Describes creating a new client cache.
Remove Client Node
Explains procedure of removing a client cache from your project.
Enable/Disable Client Cache
Explains procedure for enabling and disabling a client cache.
Clear Cache Content
Explains procedure of clearing a client cache.
Apply Configuration
Describes applying configuration changes to a cache.
Reset Configuration
Explains procedure of resetting cache configuration.
Client Cache Settings
Describes Client Cache Settings settings.
See Also
Cluster Cache Operations
Discusses variety of operations that can be performed on clustered cache.
Remote Client Operations
Discusses variety of operations that can be performed on remote clients.


Topic: Client Cache Overview

Client Cache Overview

When your application resides on a remote client node, accessing the clustered cache remotely, you may want to have a cache on client node to hold a subset of the clustered cache. This client cache (L1 cache) sits on top of the clustered cache (L2 cache), giving further performance boost by reducing trips to the clustered cache. NCache makes sure that your client cache is always synchronized with the clustered cache to avoid data integrity problem.
When application adds data to the clustered cache, it also adds it to the client cache and specifies a cache sync dependency between items in the local and remote cache. Whenever another application changes item in the clustered cache, an event is sent to the client cache to update copy of that item.
NCache provides a new overload of NCache.InitializeCache to help you use the cache sync dependency seamlessly. You do not need to perform operations to both L1 and L2 caches and specify the dependency yourself. The new overload for InitializeCache takes two cache ids, one of L1 cache and other of L2 cache, and returns a cache object. Internally it initializes both caches, you can get their instances from NCache.Caches property. Once you have the instance, you can use the existing API as always. Operations are performed on L1 and L2 caches as follows:
  • Add, Insert, Remove operations are now done on both L1 and L2 caches.
  • The Get operation is performed on L1 cache first. If the item is not found in L1, L2 will be contacted. Once item is found in L2 cache, it will be added to L1 cache as well.
  • All other functions like Search, Contains, Get Enumerator, and fields like ExceptionsEnabled and Count will be performed on L2 cache.
  • All notifications will be of L2 cache.
You can also use client cache by specifying the client-cache-id in client.ncconf . The cache entry in client.ncconf should be modified as follows.
<cache id ="remotecache" client-cache-id="mylocalcache" load-balance="true">
<server name="20.200.20.183"/>
</cache>
<cache id ="mylocalcache" load-balance="true">
<server name="20.200.20.104"/>
</cache>
See Also
Configure Client Cache


Topic: Create Client Cache

Create Client Cache

In NCache Manager, each clustered cache tree contains a node used for the creation of client cache called "Client Cache". Client Cache is just like a local/standalone cache but synchronized with a master/clustered cache. It gives further boost to the performance of those applications which are read intensive and/or read larger data. Client cache can only be created in a clustered environment if client nodes are already added in clustered cache. If user has not added or configured remote clients then he needs to do this first.
By right click on created node, a context menu will appear having an option of "Create New Cache" as shown below. Using this option you can create a client cache in a selected cluster. By default, client cache will be enabled on all the client nodes that appear in NCache Manager. But for the client nodes that are added to NCache Manager after creating client cache, users will have to enable the client cache separately on them.
Step 1
Step 2
On clicking "Create New Cache" option, "New Client Cache Wizard" will be launched for setting client cache properties. Wizard requires the following parameters:
  1. Enter the Name of a Client Cache.
  2. Select the mode of synchronization.
  3. Select Isolation level for the cache.
  4. Press Next button for further settings.
  • Optimistic Mode: With this mode client cache is synchronized with the clustered caches through events. It is possible that client caches are not synchronized with clustered cache for a small period of time. If during that time user gets an item from the client cache, he may get stale item. This is a default mode.
  • Pessimistic Mode: With this mode of synchronization, client cache always checks the "version" of cached item before returning it to the application.
  • Isolation Level: It specifies application isolation level. A High isolation level implies that the Cache runs in NCache service's process whereas a Low level implies that Cache is InProc to the applications. An OutProc cache can be shared between different applications on the same node. Moreover, an isolated cache's lifetime is explicitly controlled by applications like NCache Manager, Cmd Tools or API's.
Step 3
  1. Enter Maximum Size required for the client cache.
  2. Press Next button for further settings.
Maximum Size: Specifies an upper limit on the size of the cache in MB. When specifying max cache size, take into consideration the operating system, platform and the topology. In 32-bit Systems the total memory that an operating system can consume is limited by 4GB. Out of this, the operating system withholds 2GB for its own use and the remaining 2GB for the running processes. It is best to keep the cache size under 1.6GB. For Windows 2003/2008 server with 3GB switch, you should keep cache size under 2.4 GB. On 64-bit Windows platform, you should leave 2.6 GB for the operating system to avoid "out of memory" exceptions.
Step 4
  1. Select Eviction type.
  2. Enter Eviction Percentage.
  3. Enter Clean interval in seconds.
  4. Press Finish button to apply the changes.
The recommended values are already set on the page but you can change them according to the requirements.
  • Eviction Policy: Specifies the eviction policy to determine which items to be removed from cache, if it is full to accommodate new items.
  • Default Priority: Specifies default priority in case of Priority based eviction.
  • Eviction Percentage: Specifies the percentage of items to be removed on each eviction.
  • Clean Interval (sec.): The periodic interval after which expired items are removed from the cache.
  • Using “Start this cache on service startup” option, user will be able to mark the cache as a startup cache which will be started on cache service startup.
On finishing the above wizard, client cache will be created and enabled on all the client nodes that are already added in the cluster as shown in the figure below.
See Also
Client Cache | Configure Client Cache


Topic: Clear Client Cache

Clear Client Cache

Once the client cache has created and enabled on all the client nodes, you can perform the following operations on it, using the menu shown below:
  1. Clear Cache Content option will clear the contents from all the client caches on each node.
  2. You can also enable/disable the client cache from a particular client node.
See Also
Client Cache | Create Client Node | Create Client Cache


Topic: Apply Configuration

Apply Configuration

To Apply Configuration changes on a Client Cache, right click on the Cache from 'NCache Management' tree and select 'Apply Configuration' option from the context menu.
You can apply configuration changes, which you have made to different options on a Client Cache when it is running. To do that, right click on the Cache from 'NCache Management' tree and select 'Hot Apply Configuration' option from the context menu.
To reset configuration of a Client Cache, right click on the Cache from 'NCache Management' tree and select 'Reset Configuration' option from the context menu. It will reset all configuration changes to the last saved configuration values for the Cache.
See Also
Clear Client Cache | Create Client Cache | Remove Client Cache


Topic: Remove Client Cache

Remove Client Cache

Once the client cache has created and enabled on all the client nodes, you can remove the client cache from all the running client nodes as shown below.
See Also
Client Cache | Create Client Cache


Topic: Configure Client Cache

Configure Client Cache

NCache Manager provides facility to change the configuration of Client Caches. To change the configuration of a Client Cache, click the cache from 'NCache Management' tree. Client Cache View will appear in the right pane. This view provides configuration options for the Client Cache.
Main Settings
New created Client cache will appear in NCache Explorer. On clicking the client cache node in NCache Explorer, client cache tabbed view will be displayed in right pane. The recommended values are already set on the page but you can change them according to the requirements.
From Main tab you can set the following attributes:
  • Cache Name: It is read only. It specifies a unique identifier for the cache.
  • Storage Type: Specifies the storage options for the cache.
  • Cache Max. Size: Specifies an upper limit on the cache size.
  • Isolation Level: Specify application isolation level. A High isolation level implies that the Cache runs in NCache service's process whereas a Low level implies that Cache is InProc to the applications. An OutProc cache can be shared between different applications on the same node. Moreover, an isolated cache's lifetime is explicitly controlled by applications like NCache Manager, Cmd Tools or API's.
Policies Settings
From Policies tab you can set the following attributes:
  • Eviction Policy: Specifies the eviction policy to determine which items sto be removed from cache, if it is full to accommodate new items.
  • Default Priority: Default priority that is associated with an item in case of Priority based eviction.
  • Eviction Percentage: Specifies the percentage of items to be removed on each eviction.
  • Turn Off Eviction: Using this option you can disable eviction on a cache.
  • Clean Interval (sec.): The periodic interval after which expired items are removed from the cache.
Options Settings
From Option tab you can set the following attributes:
  • Enable error logging: Specifies whether to save traces of fatal and normal errors to a log file or not. If enabled, log files are created in 'log-files' folder located in the install directory of NCache.
  • Enable detailed error logging: Specifies whether to save traces of info, debug and warnings in a log file or not. If enabled, log files are created in 'log-files' folder located in the install directory of NCache.
  • Enable performance widgets: Identifies whether performance widgets are enabled or not. Performance widgets are used to show statistics of the cache.
  • Enable Compression: Shows compression is enabled or not. If enabled, items having size greater than the specified threshold will be compressed.
  • Use Custom SQL Notification Mode: It allows you to create your own SQL notification service and queue. Otherwise default service and queue will be created and used at run time.
See Also
Clear Client Cache | Create Client Cache | Remove Client Cache | Create Client Node | Remove Client Node | Configuration Options


Topic: Local Cache Operations

Local Cache Operations

This section explains operations that can be performed on a local cache.
In This Section
Create New Cache
Describes creating a new cache.
Add Existing Cache
Explains adding an existing cache in your project.
Start a Cache
Explains starting a cache.
Stop a Cache
Describes stopping a cache.
View Cache Statistics
Briefs how you can see statistics of a running cache.
Clear Contents
Tells how you can clear all contents of a cache.
Remove a Cache
Explains procedure of removing a cache from your project.
Apply Configuration
Describes applying configuration changes to a cache.
Hot Apply Configuration
Describes applying configuration changes to a cache when it is running.
Reset Configuration
Explains procedure of resetting cache configuration.
See Also
Cluster Cache Operations
Discusses variety of operations that can be performed on clustered cache.
Remote Client Operations
Discusses variety of operations that can be performed on remote clients.


Topic: Create New Cache

Create New Cache

To create a new Local Cache, from the 'File' menu select 'New' -> 'Cache'. A 'New Cache Wizard' will appear. Steps to create a new Local Cache through wizard are below:
Step 1 of 4
Select a node: Select a running node where you want to create new cache.
Step 2 of 4
Name: An identifier for the cache.
Step 3 of 4
Storage Type: Specifies the storage type for the primary cache.
Maximum Size: Specifies an upper limit on the cache size in MB.
Step 4 of 4
Eviction Policy: Specifies the eviction policy to determine which items are to be removed from cache, if it is full, to accommodate new items.
Default Priority: Default priority that is associated with an item if no priority is specified for that item in case of priority based eviction.
Eviction Percentage: Specifies the percentage of items to be removed on each eviction.
Clean Interval (sec.): The periodic interval after which the expired items are removed from the cache.
Start this cache on finish: If this check box is checked then this new cache will start automatically as you click the finish. Using “Auto start this cache on service startup” option, user will be able to mark the cache as a startup cache which will be started on cache service startup.
See Also
Add Existing Cache | Start a Cache | View Cache Statistics | Clear Contents | Remove a Cache | Apply Configuration | Hot Apply Configuration | Reset Configuration


Topic: Clear Contents

Clear Contents

To clear the contents of a Local Cache, right click on the Cache in the 'NCache Management' tree and select 'Clear' from the context menu.
See Also
Create New Cache | Add Existing Cache | Start a Cache | View Cache Statistics | Remove a Cache | Apply Configuration | Hot Apply Configuration | Reset Configuration


Topic: Apply Configuration

Apply Configuration

To apply configuration changes on a Local Cache, right click on the Cache from 'NCache Management' tree and select 'Apply Configuration' option from the context menu.
Configurations can also be applied even when cache is running through " Hot Apply Configuration " option.
See Also
Create New Cache | Add Existing Cache | Start a Cache | Stop a Cache | View Cache Statistics | Clear Contents | Remove a Cache | Hot Apply Configuration | Reset Configuration


Topic: Hot Apply Configuration

Hot Apply Configuration

You can apply configuration changes which you have made on Local Cache, even when it is running. To do this, right click on the Cache from 'NCache Management' tree and select 'Hot Apply Configuration' option from the context menu. "Hot Apply Configuration" option applies changes without stopping cache.
See Also
Create New Cache | Add Existing Cache | Start a Cache | View Cache Statistics | Clear Contents | Remove a Cache | Apply Configuration | Reset Configuration


Topic: Add Existing Cache

Add Existing Cache

To add an existing Cache, right click on 'Local Caches' from the 'NCache Management' tree and select 'Add Existing Cache' option from the context menu.
Step 1 of 2
Select a node: Select a running node from where you want to get the existing cache. Specify Node Name/IP address or select one from available node list.
Step 2 of 2
Select a cache: Select a cache from the list of available caches on this node. Click finish to end the wizard.
See Also
Create New Cache | Start a Cache | View Cache Statistics | Clear Contents | Remove a Cache | Apply Configuration | Hot Apply Configuration | Reset Configuration


Topic: Remove Cache

Remove Cache

To remove a Local Cache, right click on the Cache in the 'NCache Management' tree and select 'Remove' from the context menu. The Cache will be removed from the project.
See Also
Create New Cache | Add Existing Cache | Start a Cache | View Cache Statistics | Clear Contents | Apply Configuration | Hot Apply Configuration | Reset Configuration


Topic: Reset Configuration of Local Cache

Reset Configuration of Local Cache

To reset configuration of a Local Cache, right click on the Cache from 'NCache Management' tree and select 'Reset Configuration' option from the context menu. It will reset all configuration changes to the last saved configuration values for the Cache.
See Also
Create New Cache | Add Existing Cache | Start a Cache | View Cache Statistics | Clear Contents | Remove a Cache | Hot Apply Configuration | Apply Configuration


Topic: Start/Stop a Local Cache

Start/Stop a Local Cache

To start a Local Cache, right click on the Cache in the 'NCache Management' tree and select 'Start' from the context menu.
To stop a Local Cache, right click on the Cache in the 'NCache Management' tree and select 'Stop' from the context menu.
See Also
Create New Cache | Add Existing Cache | View Cache Statistics | Clear Contents | Remove a Cache | Apply Configuration | Hot Apply Configuration | Reset Configuration


Topic: Statistics of a Local Cache

Statistics of a Local Cache

To monitor performance of a Local Cache through NCache Manager Application, right click on the Cache from 'NCache Management' tree and select 'Statistics' or 'Statistics in New Window' option from the context menu.
If you will select 'Statistics', a view will be opened in the right pane. On the other hand, selecting 'Statistics in New Window' will open a new window for statistics.
See Also
Create New Cache | Add Existing Cache | Start a Cache | Clear Contents | Remove a Cache | Apply Configuration | Hot Apply Configuration | Reset Configuration


Topic: Configure Local Cache

Configure Local Cache

NCache Manager provides facility to change the configurations of Local Caches. To change the configuration of a Local Cache, click the cache from 'NCache Management' tree. Local Cache View will appear in the right pane. This view provides configuration options for the selected Cache. once you have configured cache you have to apply configurations as well. See How to Apply .
This view consists of the following tabs:
  • Main
  • Policies
  • Query Indexes
  • Compact Serialization
  • Backing Source
  • Cache Loader
  • Data Sharing
  • Options
  • Security
Main Tab
  • Cache Name: Specifies a unique identifier for the cache.
  • Storage Type: Specifies the storage options for the primary cache.
  • Cache Max. Size: Specifies an upper limit on the cache size.
  • Isolation Level: Specifies application isolation level. High isolation level implies that the Cache runs in NCache service's process whereas a Low level implies that Cache is InProc to the applications. An OutProc cache can be shared between different applications on the same node. Moreover, an isolated cache's lifetime is explicitly controlled by applications like NCache Manager, Cmd Tools or API's.
  • Auto Start Cache: Using “Auto Start Cache” option, user can set/reset cache starting operation on service start up.
  • Now auto start cache delay time can also be added. To add delay time you have to add following tag in NCache service config file. Value is specified in minutes.
<add key="NCacheSrver.AutoStartDelay" value="5"/>
  • Whenever NCache service will be restarted, all caches which are set to auto start will automatically start after specified delay time interval.
  • After configuring cache you have to Apply Configurations .
Policies Tab
  • Eviction Policy: Specifies the eviction policy to determine which items should be removed from cache, if it is full to accommodate new items.
  • Default Priority: Default priority that is associated with an item if no priority is specified for that item in case of priority based eviction.
  • Eviction Percentage: Specifies the percentage of items to be removed on each eviction.
  • Clean Interval (sec.): The periodic interval after which expired items are removed from the cache.
  • After configuring cache you have to Apply Configurations .
Query Indexes (This feature is not available in NCache Express)
Selected Classes and their attributes: Displays list of classes and their attributes on which indexes are required. You can add/remove classes and objects to index attributes from here.
Compact Serialization (This feature is not available in NCache Express)
  • Add Compact Types : Opens an assembly browser that lets you select assembly file that contains your compact serialized application objects.
  • Remove : Remove selected types from the registered types list.
  • Add <T> : Adds argument for generic types.
  • Generic Types Handler : Adds generic Types at once.
  • After configuring cache you have to Apply Configurations .
Backing Source Tab (This feature is not available in NCache Express)
Backing Source tab gives option to enable multiple Read-through and Write-through providers on a local cache.
  • A cache for which a read-through is enabled can automatically load requested items from data source as if the data is already in the cache. For multiple data sources, multiple read-through providers can be added against a cache. In case of multiple read-through providers you can set a default read-through provider for a cache using the Set as Default button.
Note: Read-Through must be enabled for Cache Forwarding.
  • A write-through or write-behind enabled cache writes updates back to the data source. You can specify multiple write-through providers incase of multiple data sources and can set one of them as a default write-through provider using the Set as Default button.
  • After enabling providers for a cache you can add providers using Add button. By click on Add button "Add New Provider" wizard will appear requiring provider information as shown in the figure.
  • Provider Name: Provider name identifies a unique provider, so for every Read Thru/Write Thru provider, an exclusive provider name must be given.
  • Assembly Name: Browse the assembly name that contains implementation for IReadThruProvider/IWriteThruProvider interface.
  • Class Name: Select class name from the list that implements IReadThruProvider/IWriteThruProvider interfaces.
  • You can also specify additional configuration parameters that will be passed to the Start method of IReadThruProvider/ IWriteThruProvider.
  • You can edit or remove the provider from the list using Edit and Remove button.
  • Deploy Provider: Deploy Provider allows you to copy/update provider assemblies to the cache servers. Use this button to select the appropriate assemblies for deployment.
  • After configuring cache you have to Apply Configurations .
Cache Loader Tab
  • Enable Cache Startup Loader: A cache startup loader can automatically loads data specified by the user in the class that implements ICacheLoader interface.
  • Assembly Name: Full path of the assembly that contains implementation for ICacheLoader interface.
  • Class Name: Name of the class that implements ICacheLoader interface.
  • You may specify additional configuration parameters that will be passed to the Start method of ICacheLoader.
  • No. of Retries: Specifies the number of attempts the cache loader will try to load data, if it fails to load data on previous attempt.
  • Retry Interval (sec.): The time interval in seconds between two retry attempts of cache loader.
  • Deploy Cache Loader: Deploy Cache Loader allow you to copy the cache loader assembly to the cache server. Use this button to select the appropriate assembly for deployment.
  • After configuring cache you have to Apply Configurations .
Data Sharing Tab
  • Add Shared Types: Opens an assembly browser that lets you select the assembly/jar files that contains the classes you want to share in cache.
  • Remove: It will remove the particular Shared Type/Class from the list.
  • Import/Export: Shared Type configurations can be import and export in XML file for later use.
  • After configuring cache you have to Apply Configurations .
Options Tab
  • Item add notification: Specifies whether to notify when an item is added to the cache or not.
  • Item remove notification: Indicates whether to notify when an item is removed from the cache or not
  • Item update notification: Denotes whether to notify when an item is updated or not
  • Cache clear notification: Specifies whether to notify when cache is cleared or not.
  • Enable performance counters: Identifies whether performance counters are enabled or not. Performance counters are used to show statistics of the cache.
  • Enable Compression: Shows compression is enabled or not. If enabled, items having size greater than the specified threshold will be compressed.
  • Use Custom SQL Notification Mode: It allows you to create your own SQL notification service and queue. Otherwise default service and queue will be created and used at run time.
  • After configuring cache you have to Apply Configurations .
Security
Administrators and NCache managers can configure API level security for a cache. Each cache will have its own API security configurations independent of other caches and users. Cache API security configurations will be saved in config.ncconf against each cache. NCache Manager provides the above wizard for configuring API security for caches.
ANow data can be sent and stored in cache in encrypted form. 3DES encryption algorithm is used to secure data, it uses three successevie iterations of DES. User can enable encryption by selecting "Enable" option and then providing Key value of length 24.
After configuring cache you have to Apply Configurations .
See Also
Configure Clustered Cache | Configuration Options


Topic: Register Server Side Code

Register Server Side Code

This section explains features which can be registered on server side.
In This Section
Compact Serialization
Describes the configuration of Compact Serialization at server end.
Cache Loader
Describes the configuration of Cache Startup Loader at server end.
Query Indexes
Describes the configuration of Query Indexes at server end.
Read-through & Write-through
Describes the configuration of Read-through and Write-through providers at server end.
See Also
Cluster Operations
Discusses variety of operations that can be performed on clusters.
Configure Clustered Cache
Helps you in configuring Clustered Cache.


Topic: Bridge

Bridge

NOTE: This feature is not available in NCache Express and Professional edition.
This section explains operations that can be performed on a Bridge.
In This Section
Create New Bridge
Describes creating a new bridge.
Add Existing Bridge
Explains adding an existing bridge in your project.
Remove Bridge
Explains how to remove a bridge.
Add Bridge Node
Briefs how to add bridge nodes.
Remove Bridge Node
Tells how remove bridge nodes.
Start/Stop Bridge
Explains how to start and stop an active bridge.
Apply Configuration
Describes applying configuration changes to a bridge.
Reset Configuration
Explains procedure of resetting bridge configuration.
Bridge Settings
Explains bridge setting configuration.
See Also
Cluster Cache Operations
Discusses variety of operations that can be performed on clustered caches.
Local Cache Operations
Helps you in configuring Local Caches.


Topic: Overview

Bridge Topology

NOTE: This feature is not available in NCache Express and Professional edition.
Remote data replication is a critical component for any plan to ensure effective and efficient protection and rapid recovery from a major interruption. Synchronous replication of data is good internally for the cluster but its impact on performance becomes a significant consideration when two clusters of cache are geographically separated. Bridge topology is designed for the scenarios which involve replication of data from one on-site cache to one/multiple and on-site/off-site disaster recovery cache(s) across the WAN. Due to asynchronous replication, all clients connected to the active cache(s) get an impression that the operations are being performed on the active cache while a complete backup is taken to the other cache(s) seamlessly.
When an operation is performed on source cache, it is asynchronously handed over to the bridge cache. This operation is then enqueued to a queue maintained by the bridge cache. Operations from the queue are transferred to the other cache(s) when bridge finds the cache(s) available and ready to accept operations. With the bridge topology, it is ensured that:
  • There is no performance degradation.
  • Operations are performed in same sequence as they were on original cache.
  • Operations are not lost in case of connection failure.
Below are the main bridge topologies provided by NCache:
  1. Active Passive (One active and one passive cache)
  2. Hub and Spoke (One active and multiple passive caches)
  3. Active-Active (Only two active sites and no passive cache)
  4. Star (All caches are active)
Active Passive (One active and one passive cache):
Three NCache Clusters participate in Active Passive topology:
  1. An active cache (replicated, partitioned, mirror or partitioned replica), where all clients are connected and perform read and write operations.
  2. A passive cache (replicated, partitioned, mirror or partitioned replica), where all operations performed on an active cache are replicated. Clients can connect to passive cache and perform both read and write operations but those operations are not replicated to the other caches. Modification can be done at passive cache if required.
  3. A Bridge Cache between the active cache and the passive cache.
Hub and Spoke (One active and multiple passive caches):
Here at least three NCache Clusters participate in this topology:
  1. An active cache (replicated, partitioned, mirror or partitioned replica), where all clients are connected and perform read and write operations.
  2. Multiple passive caches (replicated, partitioned, mirror or partitioned replica), where all operations performed on an active cache are replicated. Clients can connect to passive caches and perform both read and write operations but those operations are not replicated to the other caches. Modification can be done at passive caches if required.
  3. A Bridge Cache between the active cache and multiple passive caches.
Active-Active (Only two active sites no passive cache):
Three NCache Clusters participate in Active-Active topology:
  1. Two active caches (replicated, partitioned, mirror or partitioned replica), where all clients are connected and perform read and write operations. Here any updates to the cache are applied asynchronously to the other cache.
  2. A Bridge Cache between both the active caches.
Star (All caches are active):
Here at least three NCache Clusters participate in this topology:
  1. Multiple active caches (replicated, partitioned, mirror or partitioned replica), where all clients are connected and perform read and write operations. Here any updates to the cache are applied asynchronously to all other caches.
  2. A Bridge Cache between all the active caches.
Note:
Passive Caches when get connected to the bridge will be first cleared before connection establishment.
See Also
Create New Bridge


Topic: Create New Bridge

Create New Bridge

NOTE: This feature is not available in NCache Express and Professional edition.
Following are the steps for creating a new bridge cache through wizard:
Step 1 of 6
To create a new Bridge, right click on 'Bridge' from the 'NCache Management' tree and select 'Create New Bridge' option from the context menu.
Step 2 of 6
Enter the Name for a bridge. Name is a unique identifier for the bridge cache. For a cluster, the identifier has to be unique on all the nodes that are a part of it.
Step 3 of 6
You can select the Bridge Member Nodes either by specifying the node name or by selecting it from the available nodes.
Step 4 of 6
In step 4, you have to specify topology for the bridge. Select any bridge topology from the list of topologies given:
  • Active Passive
  • Hub Spoke
  • Active Active
  • Star
Step 5 of 6
In step 5, you will be asked to specify the queue parameters:
  • Enter the Bridge Port; it specifies port number at which each node in bridge listens to accept the connections.
  • Enter the Maximum Queue Size; it specifies upper limit for the size of the queue in MB.
  • Enter Replication Queue Size; it specifies size of the replicator queue for each cache.
  • Enable Queue Optimization; will optimize the traffic between bridge caches and queue to enhance bridge operations.
Step 6 of 6
In step 6, you will be asked to specify some advance options.
You can configure the policies for the cache from here.
  • Enter Queue Replication Interval; it specifies time interval in seconds between two consecutive operations on all target caches.
  • Enter Connection Retry Interval; it specifies time interval in seconds between two consecutive connection retries to target caches.
  • "Start bridge on service restart" option will make it possible to start the bridge on service restart.
On clicking Finish button, the bridge will be created under the heading Bridges and will be shown in NCache Manager.
See Also
Add Existing Bridge


Topic: Add Existing Bridge

Add Existing Bridge

NOTE: This feature is not available in NCache Express and Professional edition.
To add an existing Bridge, right click on 'Bridge' from the 'NCache Management' tree and select 'Add Existing Bridge' option from the context menu.
An 'Add Bridge Cache Wizard' will appear. Steps to add an existing bridge through wizard are as follows:
Step 1 of 2
Select a running node from where you want to get the existing bridge. You can specify an IP address or select one from the list of available nodes.
Step 2 of 2
Select a bridge cache from the list of available bridge caches from the selected node. Click Finish button to end the wizard.
On clicking Finish button, the bridge will be added under the heading Bridges and will be shown in NCache Manager.
See Also
Create New Bridge


Topic: Add Bridge Node

Add Bridge Node

NOTE: This feature is not available in NCache Express and Professional edition.
When an operation is performed on source cache, it is asynchronously copied to the bridge cache. Bridge Node maintains a queue where all operations are en-queued from source cache. A bridge can have multiple nodes.
To add a node to a bridge, right click on a bridge in the 'NCache Management' tree and select 'Add Bridge Node' from the context menu.
Add Node Wizard will appear with the list of available nodes. Select a node from the list and click 'Finish'.
See Also
Create New Bridge


Topic: Add Caches

Add Caches

NOTE: This feature is not available in NCache Express and Professional edition.
All participating caches in the bridge can be added here based on bridge topology specified. Users can only add already created clustered caches. New cache creation facility is not allowed. The caches added under "Caches" will only give the read only view and user will not be able to change cache configuration from here.
Note: Before adding a cache in a bridge, you need to stop the cache if it is running.
"Add Clustered Cache Wizard" will appear with the list of available caches. Select a cache from the list and click 'Finish'.
Users are allowed to perform following operations on Caches added in a Bridge:
  • Make Active: It marks the cache as an active cache.
  • Remove: It removes the specific cache from the list.
  • Allow Client Connection: This option is only enabled on passive cache(s). It allows the cache to accept client connection until the bridge is not in a working state. Once the bridge is started, the cache will again come to passive mode.
See Also
Create New Bridge


Topic: Start/Stop Bridge

Start/Stop Bridge

NOTE: This feature is not available in NCache Express and Professional edition.
To start a Bridge, right click on the Bridge in the 'NCache Management' tree and select 'Start' from the context menu.
To stop a Bridge, right click on the Bridge in the 'NCache Management' tree and select 'Stop' from the context menu.
See Also
Create New Bridge


Topic: Remove Bridge

Remove Bridge

NOTE: This feature is not available in NCache Express and Professional edition.
You can remove a Bridge from your project. Removing a Bridge will remove Bridge Nodes as well. To remove a Bridge, right click on the Bridge in the 'NCache Management' tree and select 'Remove Bridge' from the context menu. The Bridge will be removed from the project.
See Also
Create New Bridge


Topic: Remove Bridge Node

Remove Bridge Node

NOTE: This feature is not available in NCache Express and Professional edition.
To remove a Bridge Node, right click on the bridge node in the 'NCache Management' tree and select 'Remove Node' from the context menu. The Node will be removed from the Bridge Nodes.
See Also
Create New Bridge


Topic: Apply Configuration to Bridge

Apply Configuration to Bridge

NOTE: This feature is not available in NCache Express and Professional edition.
To Apply Configuration changes on a Bridge, right click on the Bridge from 'NCache Management' tree and select 'Apply Configuration' option from the context menu.
To reset configuration of a Bridge, right click on the Bridge from 'NCache Management' tree and select 'Reset Configuration' option from the context menu. It will reset all configuration changes to the last saved configuration values for the Bridge.
See Also
Create New Bridge


Topic: View Statistic

View Statistic

NOTE: This feature is not available in NCache Express and Professional edition.
You can monitor performance of a Bridge through NCache Manager. To monitor a Bridge through NCache Manager, right click on the Bridge from 'NCache Management' tree and select 'Statistics' or 'Statistics in New Window' option from the context menu. If you will select 'Statistics', a view will be opened in the right pane. On the other hand, selecting 'Statistics in New Window' will open a new window for statistics. You can also view statistics of individual node of the bridge by right clicking on bridge node.
See Also
Create New Bridge


Topic: Configure Bridge

Configure Bridge

NOTE: This feature is not available in NCache Express and Professional edition.
NCache Manager provides the facility to change the configuration of Bridge. To change the configuration of a Bridge, click the bridge from 'NCache Management' tree. Bridge Configurations View will appear in the right pane.
Main Settings
Newly created Bridge will appear in NCache Explorer. On clicking the bridge in NCache Explorer, bridge tabbed view will be displayed in right pane. The recommended settings are already set on the page but you can change them according to the requirements.
From Main tab you can set the following attributes:
  • Bridge Name: It is read only. It specifies a unique name for the bridge.
  • Bridge Port : Specifies the specific port number on which a bridge listens. Port number must be unique for each bridge which make possible the creation of multiple bridges running on a same node.
  • Queue Size: Every bridge contains a queue. This value specifies the upper limit for the size of the queue.
  • Enable Queue Optimization: Enable Queue Optimization will optimize the traffic between the bridge cache and queue to enhance bridge operations.
Target Cache Settings
From Target Cache tab you can set the following attributes:
  • Bridge Caches : Specifies the name of a cache on which bridge is supposed to replicate the data.
  • Bulk Operation Size : Specifies the size of the bulk (of operations) which is to be replicated on the target cache.
  • Replication Delay Interval : It specifies the time interval in seconds between two consecutive operations on target cache.
  • Connection Retry Interval : It specifies the time interval in seconds between two consecutive connection retries to target cache.
Options Settings
From Options tab you can enable performance counters which are used for monitoring the bridge performance.
See Also
Configuration Options


Topic: Security

Security

NOTE: This feature is not available in NCache Express and Professional edition.
Every Server node keeps security information that it has to provide to calling clients (Security Users). Alachisoft.NCache.Security.dll at server node is required to provide security services to all clients. Whatever information is required by this assembly, for managing security related issues, is present in security.ncconf file. You will be able to see this config file under "%Install directory%/NCache/config" . This file keeps the metadata for authentication and authorization for calling clients. This XML based file is loaded each time user verification is required for different operations. You can change this file at runtime and it would work for operations called after that change. For more information, see configuring security .
Privileges on managerial node operations can be granted to restricted users. For that, you need to specify User Name and Password while creating a new Cluster in NCache Manager. For details, see Security for Managerial Operations . Similarly, authorized user can perform cache operations through cache API. For details, see Security for API . Now the security parameters travel in the encrypted form.
See Also
Configure Local Cache | Configure Cluster | Configuring Security | Security for Managerial Operations | Security for API | Browsing Domain Users


Topic: Configuring Security

Configuring Security

NOTE: This feature is not available in NCache Express and Professional edition.
Every Server node keeps security information that it has to provide to calling clients. Alachisoft.NCache.NCSecurity.dll at server node is required to provide security services to all clients. Whatever information is required by this assembly, for managing security related issues, is present in security.ncconf file. security.ncconf file helps enabling NCache security as well as to manage Node and API level security. You will find security.ncconf file at "%Install Directory%/NCache/config".
security.ncconf file is as shown below:
<!-- Security Configuration file for NCache 4.1 and later versions -->
<cache-security>
<!-- Change the value true/false to enable or disable security
feature in NCache -->
<enabled>false</enabled>
<!-- LDAP path is required to log-on to domain. -->
<ldap>LDAP://DomainControllerName</ldap>
<!-- Following users are Administrators and are allowed to add 'THIS' node
into their clusters and also allowed to perform Cache operations at
API level for all Caches. -->
<ncache-administrators>
<uid>Administrator</uid>
</ncache-administrators>
</cache-security>
  • <enabled> tells users if security is enabled or not (true/false)
  • <ldap> specifies ldap path for active directory server provider. It is the domain controller. NCache uses Microsoft Active Directory Service for authentication of user. User should exist under given domain in LDAP. For more information, see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/adsi/adsi/ldap_adspath.asp
  • <ncache-administrators> keeps list of users having rights on all node-based and API-based operations.
See Also
Performing cache operations in secured environment | Admin level Security | User Level Security | Browsing Domain Users


Topic: Admin Level Security

Admin Level Security

NOTE: This feature is not available in NCache Express and Professional edition.
Admin level or Node level security can be enabled only by the Administrator of the Node. Administrators can enable/disable node level security on remote machines as well and add/remove NCache managers for that node. Admin level security configurations will be saved in security.ncconf. Following are the steps need to be followed to configure node level security using Security Configuration Wizard.
Step 1
  • Select Security from tool bar.
  • Select Configure Security option.
Step 2
  • Select a node for the security configuration.
Step 3
  • Configuring node level security on remote nodes requires credentials for that node (user name, password). You will be prompted with a dialogue box asking admin name and password for that node. On successful verification you will be moved to the next page of the wizard.
  • Provide Administrative credentials for that node.
  • Press Ok to proceed further.
Step 4
  • You can enable/disable Node level security using the option Enable Security.
  • You can also Add/remove NCache admin/managers from the following wizard.
  • Press Finish to apply the settings.
See Also
Performing cache operations in secured environment | Configuring Security | User Level Security | Browsing Domain Users


Topic: User Level Security

User Level Security

NOTE: This feature is not available in NCache Express and Professional edition.
Administrators and NCache managers can configure user level security for a cache. Each cache will have its own user level security configurations independent of other caches and users. Cache user level security configurations will be saved in config.ncconf against each cache. NCache Manager provides a tab view for configuring user level security for all caches.
Step 1
  • Select the Security tab.
  • You can enable/disable API security on cache using the option Enabled Security.
  • Using security tab you can also specify users who are authentic for the selected cache API as shown in the figure.
How to pass Security Credentials to API:
User can also pass security credentials to API from the application using the following code:
NCache.InitializeCache("cacheId", new Alachisoft.NCache.Web.Security.SecurityParams("Username", "Password"), null);
See Also
Performing cache operations in secured environment | Configuring Security | Admin level Security | Browsing Domain Users


Topic: Browsing Domain Users

Browsing Domain Users

NOTE: This feature is not available in NCache Express and Professional edition.
If security is enabled on a cache or node, one has to provide credential information to perform operations on Clusters and Local Caches in NCache Manager. To access secured application or a node you need to perform the following steps:
Step 1
Select Security option from tool bar and then select Security Credentials to open the Security Credentials screen.
Step 2
  • You are supposed to provide the required credentials on a dialog box.
  • Information given here will be crossed checked with security.ncconf file each time user verification will be required for managerial/application operations.
  • Security parameters travel in the encrypted form.
  • You can also verify the supplied credentials from the same dialog using "Verify Credentials" button.
  • These credentials are used for browsing the domain.
  • If the credentials are not valid the invalid credentials message will be prompt to the users.
  • The following message will be displayed if the credentials are not already set while browsing domain users.
See Also
Performing cache operations in secured environment | Configuring Security | Admin level Security | User Level Security | Configuring API security for client node


Topic: Configuration Options

Configuration Options

This section discusses various configuration options provided by NCache for both local and clustered caches.
In This Section
InProc and OutProc
Discusses InProc and OutProc options for caches and highlights different scenarios in which both can be used.
Heart Beat
Explains heart beat configuration option for clusters to detect connection breakage among the nodes of a cluster.
Data Compression
Explains Data Compression configuration option to minimize data traffic between cluster and client node.
Load Balancing
Explains balancing data load among all nodes in a cluster.
Auto Start Cache
Describes how to start cache(s) at the boot.
Ports
Discusses types of ports and default ports that NCache uses for communication.
Operation Timeout
Explains operation timeout option for configuration.
Client Request Timeout
Explains client timeout configuration option for .NET and Java Clients.
Client/Server Connection Retry
Explains Client/Server Connection Retry configuration option.
Client/Server Connection Timeout
Explains Client/Server Connection Timeout configuration option.
Nagling
Describes what is nagling and how it can be helpful for improving the performance.
Dual Socket
Describes how you can enable nodes in a cluster to establish two connections with every other node.
Error Logging
Describes how you can save error messages to a log file.
Statistics Replication Interval
Explains statistics replication interval.
Maximum Size
Describes specifying an upper limit on the size of the cache in MB
Eviction Policies
Explains evicting cache items when cache reaches maximum storage limit. It also presents various eviction schemes to choose from.
Eviction Percentage
Depicts percentage of items to be removed on each eviction.
Clean Interval
Describes periodic interval to remove expired items from cache.
Read-through and Write-through
Discusses options for transparently fetching and writing data to and from data sources.
Notifications
Explains how you can make your application responsive to various cache events.
Performance Counters
Depicts performance parameters that are used to analyze cluster performance.
Debugging Counters
Explains debugging counters and shows how to enable them for debugging purposes.
See Also
Configuring with NCache Manager
Explains NCache Manager which provides a GUI based cache configuration and lets you create and manage Local and Clustered Caches.
Configuring NCache Clients
Describes configuring NCache light-weight Clients through client.ncconf file.
Configuring Security
Helps enabling NCache security as well as to manage Node and API level security through security.ncconf file.
Configuring NCache Service
Explains configuring NCache Service.
Config.ncconf
Explains config.ncconf file that contains information regarding all registered caches/clusters.


Topic: InProc and OutProc

InProc and OutProc

If your application is running on a server node (the node that is participating in the cluster), you can access the cache either as InProc or OutProc. For InProc, cache lives inside your application process and performs all the clustering operations from there. For OutProc, you have to start the cache independently and then connect to it. Both access modes have their own pros and cons.
InProc mode in a replicated cache can give you really fast GET operations since you're accessing all the data from within your own memory space. However, since your application and the cache are sharing the same memory, you may face memory size limitation (in terms of how much you can cache).
Similarly, OutProc has benefit that multiple applications on the same machine can share a common cache. Additionally, since the cache lives in its own memory, you have more memory available to you. But, there is an overhead of transferring data between your application process and the NCache process.
OutProc requires that your .NET Assemblies (the ones that contain the objects you're going to add into NCache) are either registered in GAC or are located at $INSTALL/NCache/bin/service folder. Otherwise, NCache will not find your object definitions which it requires for .NET Serialization. And, this will result in NCache throwing an exception when you do Add, Insert, Get, or Remove operations.
If you're running NCache in a clustered configuration, you must ensure this on all machines in the cluster. To initialize cache in inproc or ourproc mode, do one of the following.
NCache Manager:
In NCache Manager, you can specify isolation level for Clustered Cache as well as for Local Cache on its Main Tab , in Cluster/LocalCache View window.
Config.ncconf:
In Config.ncconf , you can specify the attribute value of inproc as true (for inproc) or false (for outproc).
<!-- myreplicatedcache will start in inproc mode -->
<cache-config name="myreplicatedcache" inproc="true" config-id="8" last-modified="7/31/2010 3:53:53 PM">
<!-- mypartitionedcache will start in outproc mode -->
<cache-config name="mypartitionedcache" inproc="false" config-id="1" last-modified="6/20/2010 3:50:34 PM">
Note: InProc mode is only available for Replicated and Local cache.
See Also
Configure Local Cache | Configure Cluster


Topic: Heart Beat

Heart Beat

Communication between Cluster nodes is critical for smooth cluster operations. Therefore, NCache provides an option called Heart Beat for the clusters to detect connection breakage with any node of the cluster. Connection breakage may occur due to an unplugged network cable or disabling of a network connection. When this option is enabled, a node of a cluster sends some dummy packets to other nodes and waits for acknowledgment. Therefore, if live nodes do not receive acknowledgments from any idle node after specific duration, they will consider it dead and will update their views by excluding it from the cluster. There will be no overhead of heart beat messages when all nodes are active and sending messages to each other. You can enable/disable heart beat through following methods.
NCache Manager:
You can enable or disable heartbeat option from "Cluster Settings" Tab of Cluster view window.
Config.ncconf:
You can enable heart beat option through Config.ncconf . Heart beat interval can also be specified inside service's config file as follows
<add key="NCacheServer.HeartbeatInterval" value="30"/>
See Also
Configure Cluster


Topic: Data Compression

Data Compression

To minimize data traffic between cluster and client nodes, NCache provides GZip Compression for objects of size greater than the specified threshold value. Objects greater than the specified threshold size will be compressed /decompressed by NCache. Average compression gains are higher for objects of greater size. By default, data compression is off. You can enable/disable data compression by one of following methods.
NCache Manager:
You can enable/disable data compression and also specify compression threshold size for Cluster/Local Cache through Options Tab in view window.
Config.ncconf:
You can enable/disable data compression option for a cache through Config.ncconf as follows.
<compression enabled="true" threshold="500kb"/>
See Also
Configure Local Cache | Configure Cluster


Topic: Load Balancing

Load Balancing

A situation may arise when few nodes in a partitioned cluster are over loaded with data while storage capacity of others is not fully utilized. To make it sure that all nodes in a cluster are getting fair share of data, NCache provides Automatic Load Balancing configuration option. You can enable/disable this option on Automatic Load Balancing Tab of Cluster view window. For Load Balancing enabled, you are also required to specify the balancing threshold and balancing interval values which determine when NCache should look for Load Balancing of data.
Note: Auto Load Balancing option is available for partitioned caches only.
See Also
Configure Cluster


Topic: Auto Start Cache at Boot

Auto Start Cache at Boot

You can automatically start cache(s) at system startup. By default, Auto-start cache option is off. You can enable/disable this option by one of the following ways.
NCache Manager:
In NCache Manager see under "Main" tab and select the option "Auto start this cache on service startup". Select this option for each cache you want to automatically start at NCache service startup.
This is the recommended way for enabling auto-startup option.
After configuring you have to Apply Configurations as well. See how to apply .
Configuration File:
You can enable\disable auto start cache option from Config.ncconf file.
By default auto-start tag is "False". In order to enable this option, set this tag to "True" for each cache you want to automatically start on service startup.
auto-start="True"
Moreover, you can add some delay time in auto-startup. To add delay time you have to add following tag in NCache service config file. Value is specified in minutes.
<add key="NCacheSrver.AutoStartDelay" value="5"/>
Whenever NCache service will be restarted, all caches which are set to auto start will automatically start after specified delay time interval.
Note: Restart NCache Service after adding AutoStartDelay tag.
See Also
Configuring NCache Service


Topic: Ports

Ports

NCache uses TCP ports for communication. Default TCP port is 8250. These ports can be changed, if required, by changing the values of the registry key (TCP.PORT) written upon the installation of NCache.
This key can be found under the following path:
HKEY_LOCAL_MACHINE/SOFTWARE/ALACHISOFT/NCACHE
Note: NCache Manager application assumes the default port. Therefore, upon changing the values of this port, LocalCache/Cluster can not be administered through NCache Manager application. However, NCache command line utilities and tools provide the option to address the LocalCaches/Clusters on other ports. For more details, see NCache Tools .
In This Section
Cluster Ports and Port Ranges
Explains cluster ports and their default values.
Server Port
Describes server port and ways to customize it.
See Also
Configure Local Cache
Helps you configure Clustered or Local Caches through NCache Manager.


Topic: Cluster Port and Port Range

Cluster Port and Port Range

Cluster ports are the ports at which NCache clusters start. You can change the default value of these ports from NCache Manager. Following clusters ports are used by NCache for installed caches:
  • myReplicatedCache - 7800
  • myPartitionedCache - 7801
To change Port of a cluster, go to the "Cluster Settings" Tab of its View window.
See Also
Configure Cluster


Topic: Server Port

Server Port

At the NCache Server Port, NCache Server starts and accepts different client connections. Default value of this port is "9800". You can change the default value through Alachisoft.NCache.Service.exe.config file as follows:
<ncache-server port="9800" connection-retries="60" retry-interval="1"/>
See Also
Configure NCache Service


Topic: Operation Timeout

Operation Timeout

Operation Timeout is the maximum time in seconds during which a clustered operation must be completed, otherwise the operation will fail. Default Timeout value is 60 seconds and can not be less than that. To specify Timeout for a Clustered Cache operation, do one of the following two.
NCache Manager:
You can specify the operation timeout on the " Cluster Settings " Tab in NCache Manager.
Config.ncconf:
You can specify the operation timeout through Config.ncconf as follows.
<cluster topology="partition-replica" op-timeout="120sec" stats-repl-interval="60sec" use-heart-beat="False">
</cluster>
See Also
Configure Cluster


Topic: Client Request Timeout

Client Request Timeout

Client Request Timeout is the maximum time in seconds during which client must receive response from NCache Server. If NCache Server response is not received before this time, NCache API throws an OperationFailedException. Default Client Request Timeout value is 90 seconds. You can specify this timeout for both Java and .Net clients in Client.ncconf as follows:
<ncache-server port="9800" client-request-timeout="90" connection-retries="1" retry-interval="0" connection-timeout="5"/>
See Also
Configure Cluster


Topic: Client/Server Connection Retry

Client/Server Connection Retry

Client API tries to connect with each server number of times you specify in client.ncconf. It goes through all the servers in the list once and if none are available, then sleeps for the 'retry-interval' seconds and then scans the list again. This is done 'connection-retries' times. This is specified in the client.ncconf file as follows:
<ncache-server port="9800" connection-retries="60" retry-interval="1"/>
See Also
Configuring NCache Clients


Topic: Client/Server Connection Timeout

Client/Server Connection Timeout

When client is unable to connect to the Cache Server, all other threads wait for the connection to reestablish. If client is not reconnected in this time, other threads return with Connection Timeout exception. By default this time out is 5 seconds. This Timeout is specified in the client.ncconf file as follows:
<ncache-server port="9800" connection-retries="60" retry-interval="1" connection-timeout="5"/>
See Also
Configuring NCache Clients


Topic: Nagling

Nagling

Nagling refers to concatenating a number of small buffer messages. It increases the efficiency of a network application system by decreasing the number of packets that must be sent. Nagling can be thought of as bulk operation on the network. By default Nagling is enabled. You can turn it off in your service's config file as follows:
<add key="NCacheServer.EnableNagling" value="false"/>
Nagling combines all the available messages present in a queue whose combine size is less than Nagling threshold. Size is specified in terms of Kilo bytes. By default it is 500Kb. You can specify it in service's config file as follows:
<add key="NCacheServer.NaglingSize" value="500"/>
Note: If you are using cache as InProc, you need to specify the above lines of code in config.exe of your application.
See Also
Configuring NCache Service


Topic: Dual Socket

Dual Socket

Each node participating in cluster can establish two connections with every other node. Purpose of increasing the number of connections is to increase throughput by maximizing the network usage. As network I/O is a slow process, therefore, opening multiple connections improve the performance. By default, dual connections are disabled. You can enable or disable this feature by specifying following options in <appSettings> of NCache service's config file . If you are using cache as InProc, you need to specify this in config.exe of your application.
<appSettings>
<add key="NCache.EnableDualSocket" value="true"/>
</appSettings>
See Also
Configuring NCache Service


Topic: Error Logging

Error Logging

When running a cache, error messages can be helpful. These messages can be saved to a log file if required. NCache Manager can be used to enable logging. You will find this option on Main Tab of Cluster/Local Cache view window. Each time user enables error logging a new trace file is created in the "log-files" folder under NCache installation directory with current time stamp.
Enabling error logging generates fatal and normal logs, while enabling detailed error logging generates log file containing info, debug and warning logs. By default, logging is disabled. Enabling "Detail error logging" generates logs very frequently, which may affect the performance of cache/cluster. In case of an error, it is reported in the application's event log in system.
Enable logs for Java Client
Logging in the NCache java client can be controlled by setting enableNCLogs property before initializing the cache. This is how you can enable error logging for Java Client.
[Java]
System.setProperty("enableNCLogs", Level.INFO.toString());
Log file is generated in the application home directory. The above property will enable logging of all INFO messages. It will also enable logging of SEVERE and WARNING messages.
The Level class (java.util.logging) defines a set of standard logging levels that can be used to control logging output. The logging Level objects are ordered and are specified by ordered integers. Enabling logging at a given level also enables logging at all higher levels. Clients should use the predefined Level constants such as Level.SEVERE. The levels in descending order are as follows:
  • SEVERE (highest value)
  • WARNING
  • INFO
  • CONFIG
  • FINE
  • FINER
  • FINEST (lowest value)
In addition, there is a level OFF that can be used to turn off logging, and a level ALL that can be used to enable logging of all messages.
See Also
Configure Local Cache | Configure Cluster | Hot Apply Configuration


Topic: Maximum Size

Maximum Size

Through this configuration option, you can specify an upper limit on the size of the cache in MB. The number of items in the cache are limited by maximum size of the cache and amount of free system memory (virtual or physical). If some eviction policy is specified, whenever total data size in cache reaches maximum size or when less than 10% of memory is left in the system, items are removed from the cache as per eviction policy. Maximum size of a cache can be specified by one of following two ways.
NCache Manager:
You can specify cache max size for a Cache on Main Tab of its view window.
Config.ncconf:
You can specify the cache max size through Config.ncconf as follows.
<cache-config name="mypartitionedcache" inproc="False" config-id="1" last-modified="6/20/2010 3:50:34 PM">
<storage type="heap" cache-size="250mb"/>
</cache-config>
See Also
Configure Local Cache | Configure Cluster


Topic: Statistics Replication Interval

Statistics Replication Interval

This option is available for Clustered Cache only. Statistics replication interval is the time interval in seconds after which a node sends its statistics to all other nodes in a cluster. Replication Interval for Statistics can be specified by one of the following ways.
NCache Manager:
You can specify the statistics replication interval on Cluster Settings Tab of Clustered Cache view window in NCache Manager.
Config.ncconf:
You can specify the statistics replication interval through Config.ncconf as follows.
<cluster topology="partition-replica" op-timeout="120sec" stats-repl-interval="60sec" use-heart-beat="False">
</cluster>
See Also
Configure Cluster


Topic: Eviction Policies

Eviction Policies

There is a storage limit, maximum size is the capacity to which a cache can add objects in it. If cache reaches its maximum size and eviction is turned on, the specified ratio of items will be evicted, to make space for new objects. On the other hand, if cache reaches its maximum storage limit and eviction is turned off, items are neither evicted nor added to the cache any further.
An eviction scheme is used to select the objects that need to be removed from the cache. A particular eviction policy can be selected at the creation time but once it is set it cannot be altered in running cache. User can change eviction policy after creating a cache only if it is not running. Eviction policies for a cache can be specified in one of the following two ways.
NCache Manager:
You can select Eviction Policy for both Clustered and Local Cache from Policies Tab of their view window.
Config.ncconf:
You can select the Eviction Policy for a cache through Config.ncconf as follows.
<cache-config name="mypartitionedcache" inproc="False" config-id="1" last-modified="6/20/2010 3:50:34 PM">
<eviction-policy enabled="True" default-priority="normal" policy="priority" eviction-ratio="0.05"/>
</cache-config>
Note: Eviction-ratio=0.05 is equal to 5% of total cache size. Eviction is not recommended in case of sessions.
In This Section
Least Recently Used (LRU)
Describes the LRU based scheme of eviction.
Least Frequently Used (LFU)
Describes LFU based eviction policy.
Priority Based
Describes eviction of an object based on its relative cost or priority.
See Also
Configure Local Cache
Helps you in configuring Local Cache through NCache Manager.


Topic: Least Frequently Used

Least Frequently Used

In this scheme a counter that counts the access made to an object is used. At the time of eviction objects with lowest counter number are evicted first. Here too a random selection is made between two objects with same counter.
See Also
Configure Local Cache | Configure Cluster


Topic: Least Recently Used

Least Recently Used

This eviction scheme associates a timestamp with all objects. This timestamp is updated each time the object is accessed. When evicting, objects with oldest timestamp are picked first. In case of two objects with the same time stamp, a random selection is made.
See Also
Configure Local Cache | Configure Cluster


Topic: Priority Based Eviction

Priority Based Eviction

This is the default eviction policy and has same mechanism as LFU with the addition of a relative cost that is associated with an object at the time of its addition to cache. Objects with lower cost are removed before objects with higher cost. Client application can choose from a list of priorities that is predefined (Low, Below Normal, Normal, Above Normal, High and Not Removable). In case a priority is not chosen, it is set by default as Normal.
See Also
Configure Local Cache | Configure Cluster


Topic: Eviction Percentage

Eviction Percentage

Eviction percentage is the percentage of items to be removed on each eviction. This option is available on Policies Tab of both Cluster and Local Cache view window along with Eviction Policy.
See Also
Configure Local Cache | Configure Cluster


Topic: Clean Interval

Clean Interval

Clean interval is the periodic interval after which the expired items are removed from the cache. You can change the clean interval for a cache by one of following two ways.
NCache Manager:
Clean interval of a cache can be specified on Policies Tab of Cluster/Local Cache view window.
Config.ncconf:
Clean interval of a cache can also be specified through Config.ncconf as follows.
<cache-config name="mypartitionedcache" inproc="False" config-id="1" last-modified="6/20/2010 3:50:34 PM">
<eviction-policy enabled="True" default-priority="normal" policy="priority" eviction-ratio="0.25"/>
<cleanup interval="15sec"/>
</cache-config>
See Also
Configure Local Cache | Configure Cluster


Topic: Read-through and Write-through

Read-through and Write-through

While working with data sources, it is important to transparently fetch required data from the master data source if it is not available in the cache and vice versa. Read-Through and Write-through are provided by NCache for this purpose. Now you can add multiple Read-Through and Write-through providers with your applications in case of multiple data sources.
This configuration option is available for both Local and Clustered Caches. You can enable this behavior for your cache from Backing Source Tab of their view window.
Read through Caching
A requested value not present in the cache can be automatically obtained from the main data source by the cache and provided to the user in such a manner that it seems to the caller that it came from the cache. This is known as Read Through Cache. The gain from it is that the application can depend on the cache for both cached data as well as for transparent data loading instead of adding data loading logic at the point where it requires the data.
Just like Read Through, data can be written back to the data store as well to keep it updated. NCache provides two ways of achieving this.
Write through Caching
The idea behind Write Through cache is that when an application updates a piece of data in the cache, the operation is not completed until the changed data has been successfully stored in the underlying data source. Though this enhances data integrity, but effects the performance negatively in terms of the latency involved in writing to the data store. This latency can be overcome by Write Behind caching
Write Behind Caching
Unlike write through, write behind caching writes to the data store after some configurable time. The data that needs to be written to the data source is placed in a queue and after the specified duration, it is written to the main data source. This improves the performance as there is no write latency involved. It decreases the load on the database as well, as the Reads to the database are made from the cache and the Writes which are more expensive can be reduced by combining them into a single write. It boosts scalability as well as reduce the load by increasing number of users on the data source.
See Also
Configure Local Cache | Configure Cluster | Using Read-Through Write-Through


Topic: Performance Counters

Performance Counters

Performance counters are shown both from PerfMon and NCache Monitor . The statistics view is also used to see the performance statistics of a cache or a cluster.
These counters include:
  • Fetches/sec: Number of Get operations per second.
  • Hits/sec: Number of successful Get operations per second.
  • Misses/sec: Number of failed Get operations per second.
  • Additions/sec: Number of Add operations per second.
  • Updates/sec: Number of Insert operations per second.
  • Deletes/sec: Number of Remove operations per second.
  • Expirations/sec: Number of items being expired currently per second.
  • Evictions/sec: Number of items evicted per second.
  • State Txfr/sec: Number of items this node is either reading from other nodes or sending to other nodes during a state transfer mode.
  • Data Bal/sec: Number of items this node is either reading from other nodes or sending to other nodes during a Data Load Balancing mode.
  • Mirror Queue Size: Number of items in the Mirror queue.
  • Average sec/fetch: Average time in seconds taken to complete one fetch operation.
  • Average sec/add: Average time in seconds taken to complete one Add operation.
  • Average sec/insert: Average time in seconds taken to complete one insert operation.
  • Average sec/remove: Average time in seconds taken to complete one remove operation.
  • Average sec/cache operation: Average time, in seconds, taken to complete one cache operation.
  • Client Request/sec: Number of requests sent by all clients to the cache server.
  • Client Response/sec: Number of responses received by all clients from the cache server.
  • Clustered opsrecv/sec: Number of clustered operations performed per second.
  • Clustered opsent/sec: Number of clustered operations performed per second.
  • Count: Number of items in the cache.
  • DispatchEnter/sec: Number of clustered operations performed per second.
  • Mirror queue size: Number of items in the Mirror queue.
  • Misses/sec: Number of failed Get operations per second.
  • Readthru/sec: Number of Readthru operations per second.
  • Response sent/sec: Number of clustered operations performed per second.
  • Responses/sec: Number of responses sent (meaning cache response for commands like add, get, insert, remove etc.) to all clients by this cache server.
  • State transfer/sec: Number of items this node is either reading from other nodes or sending to other nodes during a state transfer mode.
  • Writethru/sec: Number of Writethru/Writebehind operations per second.
  • CacheLastAccessCount: Number of items which are older then the access interval specified in the config.
  • Cluster ops/sec: Number of clustered operations performed per second.
  • Bytes sent/sec: How much data is sent from this node to other nodes in the cache.
  • Bytes received/sec: How much data is received by this node from other nodes in the cache.
  • Requests/sec: Number of requests (meaning cache commands like add, get, insert, remove etc.) being processed from all clients by this cache server.
  • Client bytes sent/sec: Bytes being sent from cache server to all its clients.
  • Client bytes received/sec: Bytes being received by cache server from all its clients.
You can select different counters to be displayed in 'Cluster Performance Test Bed' to analyze cluster performance through Options Dialog . You can enable Performance Counters for both Local and Clustered Caches from Options Tab of their view window.
See Also
Configure Local Cache | Configure Cluster


Topic: Event Notifications

Event Notifications

NCache event notifications let you design applications that react to various cache events. These notifications are disabled by default to save precious CPU and network resources. Events are fired upon addition, updation and removal of an object or when cache is cleared. You can turn these notifications on, for Clustered or Local Caches, through Options Tab of their view window.
See Also
Configure Local Cache | Configure Cluster


Topic: Debugging Counters

Debugging Counters

Debugging counters are installed for debugging purposes. These counters include:
  • Socket send time (sec): Time in milli seconds taken to send a request.
  • Socket send size (bytes): Bytes sent per second.
  • Socket recv time (sec): Time in milli seconds taken to receive a request.
  • Socket recv size (bytes): Bytes received per second.
  • Naggling msg count: How many messages were sent together in socket.send.
  • TcpUpQueueCount: Number of items in TCP up queue.
  • TcpDownQueueCount: Number of items in TCP down queue.
  • TcpdownEnter/sec:.
  • BCastQueueCount: Number of items in BCast Queue.
  • MCastQueueCount: Number of items in MCast Queue.
Debugging counters are disabled by default and can be enabled by adding following key-value pair in ' alachisoft.ncache.service.exe.config ' file.
<key="EnableDebuggingCounters" value="true"/>
See Also
Configuring NCache Service


Topic: Cache Server Configuration

Cache Server Configuration

This section explains various cache server configuration in "Alachisoft.NCache.Service.exe.config" file. All configurations in Alachisoft.NCache.Service.exe file will be needed at the start of the NCache service.
In This Section
Overview
Gives you and overview of NCache.Service.exe.config file.
Bind Multiple NIC's
Explains Bind Multiple NIC's, its uses and its default values.
Auto Start Cache on Reboot
Explains Auto Start Cache, its uses and its default values.
Client/Server TCP Port
Explains Client/Server TCP Port its default values.
Configure Windows Events Logging
Explains Windows Events Logging, its uses and its default values.
Configure .NET Garbage Collection
Explains .NET Garbage Collection, its uses and its default values.
Configure Expiration Cleanup
Explains Expiration Cleanup, its uses and its default values.
Configure Eviction Cleanup
Explains Eviction Cleanup, its uses and its default values.
Enable Debug PerfMon Counters
Explains Debug PerfMon Counters, its uses and its default values.
Enable License Logging
Explains License Logging, its uses and its default values.
Configure SQL Dependency
Explains SQL Dependency and its modes.
Configure Response Data Size
Explains the Response Data Size and its various parameters.
Configure Enumeration
Explains the process of Enumeration and its various parameters.
See Also
Cluster Cache Operations
Discusses variety of operations that can be performed on clustered cache.
Configuring with Command Line Tools
Discusses variety of command line tools.


Topic: Overview

Overview

"Alachisoft.NCache.Service.exe.config " file hosts all cache related configurations. For any change in cache configuration, you can either manually update this file or use NCache Manager to update it. This file updates with every change made at NCache Manager. Here you can specify the port at which cache server will listen for the incoming connection requests. Send/receive buffer size of connected client sockets is also given here. You can also identify cache (es) that you want to start at boot in Alachisoft.NCache.Service.exe.config file. This file is located at "%Install Directory%/NCache/bin/service".
See Also
Clustered Cache Operation | Remote Client Operations | Client Cache Operations | Local Cache Operations | Register Server-Side Code | Bridge Topology Operations


Topic: Cache Server Configuration

Cache Server Configuration

Client/Server TCP Port
Client/Server TCP Port in service config will specify the port at which Cache Server will listen for incoming connection requests.
<add key = "NCacheServer.Port" value = "9800"/>
Enable License Logging
Enable License Logging in service config will specify whether this service will log license information for clients or not.
<add key = "NCacheServer.LicenseLogging" value = "false"/>
Bind Multiple NIC's
When your machine has more than one network cards, you can inform NCache which interface to use for cluster-wide communication. In order to do so, provide IP Address you want the cluster server to bind with in service config.
<add key = "NCacheServer.BindToClusterIP" value = "20.200.20.39"/>
You can follow the above procedure for client communication. Provide the IP Address you want the client's (NCache client) server to bind with.
<add key = "NCacheServer.BindToClientServerIP" value = "20.200.20.39"/>
Auto Start Cache on Reboot
You can configure caches to start with the start of NCache service. As, by default NCache service starts at the system startup so these settings are useful incase you want some caches to auto start at the system startup.
<add key = "NCacheServer.AutoStartCache" value = "mycache,myreplicatedcache,mypartitionedcache"/>
<add key = "NCacheServer.CacheUser" value = "domain/userId"/>
<add key = "NCacheServer.CachePassword" value = "password"/>
Enable Debug PerfMon Counters
Some performance counters are disabled by default but they can be really helpful to see NCache behavior over the network. These counters include:
  • Socket send time (time taken for the last send operation)
  • Socket receive time (time taken for the last receive operation)
  • Bytes sent/second
  • Bytes received/second
  • Naggling message count (number of messages bundled together in the last socket send operation)
  • TcpUpQueueCount: Number of items in TCP up queue.
  • TcpDownQueueCount: Number of items in TCP down queue.
  • BCastQueueCount: Number of items in BCast Queue.
  • MCastQueueCount: Number of items in MCast Queue.
These counters help find the source of the problem incase we see the cluster is not performing as expected.
<add key = "NCacheServer.EnableDebuggingCounters" value = "true"/>
Configure Expiration Cleanup
Expired items are removed in bulk. Specify the size of the bulk operation i.e. how many items should be removed in one bulk operation.
<add key = "NCacheServer.ExpirationBulkRemoveSize" value = "10"/>
Expired items are removed in bulk. This may affect the performance of user operations during expirations. This delay specified (in seconds) causes a delay between two consecutive bulk remove operations.
<add key = "NCacheServer.ExpirationBulkRemoveDelay" value = "0"/>
Configure Eviction Cleanup
During eviction items are removed in bulk. Specify the size of the bulk operation i.e. how many items should be removed in one bulk operation. EvictionBulkRemoveSize should be specified in multiple of 300.
<add key = "NCacheServer.EvictionBulkRemoveSize" value = "10"/>
During eviction items are removed in bulk. This may affect the performance of user operations during expirations. This delay specified (in seconds) causes a delay between two consecutive bulk remove operations.
<add key = "NCacheServer.EvictionBulkRemoveDelay" value = "0"/>
Configure Windows Events Logging
CacheSizeThreshold is the size of cache in percentage of total cache size. When this threshold is reached a warning message is logged into system event log. No warning message is logged if the following line is commented.
<add key = "NCacheServer.CacheSizeThreshold" value = "80"/>
CacheSizeReportInterval is the interval in minutes during which CacheSizeThreshold warning is issued once. If cache size falls below CacheSizeThreshold due to eviction and again crosses the CacheSizeThreshold limit during this interval no warning is generated. The minimum value is 5 minutes.
<add key = "NCacheServer.CacheSizeReportInterval" value = "15"/>
Enables/Disables the logging of client connectivity events into event viewer. By default these events are disabled.
<add key = "NCacheServer.LogClientEvents" value = "false"/>
Specifies the level of events which are logged into event viewer. There are three levels of events
  • Error : Only errors will be logged
  • Warning : Errors and Warnings will be logged
  • All : all events will be logged
<add key = "NCacheServer.EventLogLevel" value = "all"/>
Configure .NET Garbage Collection
Enables/Disables forced garbage collection when using Server GC. Applicable on server operating systems only. Possible values are 'true' or 'false'. If value is true, a forced GC.Collect( ) is called after system memory usage reaches a specific threshold. This threshold is specified under property 'NCacheServer.ForcedGCThreshold'. Default value for this property is 'true'.
<add key = "NCacheServer.EnableForcedGC" value = "true"/>
%age Memory usage threshold that is used to call forced garbage collection. This property depends on property 'NCacheServer.EnableForcedGC'. If the property is set 'true', given threshold value is used to call explicit Garbage collection. Default value is 80. This implies that an explicit GarbageCollection should be called when system memory usage reached 80% of the total memory.
<add key = "NCacheServer.ForcedGCThreshold" value = "80"/>
Value of seconds after which service should check if it needs to do a forced garbage collection. This property dictates how frequent you want to check if a forced Garbage Collection is required or not. Default value is 20 seconds. Minimum possible value is 5 seconds.
<add key = "NCacheServer.ForcedGCInterval" value = "20"/>
Configure SQL Dependency
SQL Dependency can be used in two modes i.e. Default mode or Custom mode. In default mode, SQL Dependency creates a default service and queue at run time. In case of Custom mode, a customer defined SQL Dependency service and queue will be created and used by NCache. In this case, NCache will connect with the pre-created service and queue with following naming convention:
  • "NCacheDBService-[IP-Address]"
  • "NCacheDBQueue-[IP-Address]"
You can change the SQL Dependency service and queue name prefix by specifying it against the NCacheServer.NCacheDBService key/NCacheServer.NCacheDBQueue key.
<add key = "NCacheServer.NCacheSQLNotificationService" value = "NCacheSQLService"/>
<add key = "NCacheServer.NCacheSQLNotificationQueue" value = "NCacheSQLQueue"/>
Configure Response Data Size
NCache introduces the "Response Data Size" to limit the large result sets returned in response to Search, Bulk, Tags and Groups operations. .Net framework does not support the serialization of large result sets which exceeds the size of 1.9Gb. To solve this problem NCache split the large result sets into smaller chunks of data.
NCacheServer.ResponseDataSize can be used to specify the size of a response. It will help in limiting a response size by dividing the bigger response into multiple responses each containing the data approximately equal to the specified limit. These multiple responses will be merged by the NCache Client as a single response. Here it takes value in MB’s. Default size is 1024MB.
<add key = "NCacheServer.ResponseDataSize" value = "1024"/>
Note: At least one object must be sent in response even if the data size of an object exceeds the specified limit for data.
Configure Enumeration
The purpose of introducing enumeration is to keep cache free from locking while enumerating the cache data. This process eventually increases the cache performance and its availability for clients. NCache is following the technique of taking snapshots of cache data and send it to the client for enumeration which keeps the cache free from being locked during the process of enumeration. Four attributes are defined for enumeration, which are:
NCacheServer.SnapshotPoolingCacheSize can be used to specify the size of the cache (in terms of number of items) for enabling enumeration on cache. It will help in deciding whether to create a pool of snapshots for enumeration or not. A complete snapshot of cache is returned to the enumerator until the threshold reaches its limit. Once the threshold value is crossed, cache will create a pool of snapshots that will hold those snapshots based on time slicing. These snapshots will be provided to the enumerator on demand from client by the cache server. Default Size is 100000 items in cache.
<add key = "NCacheServer.EnableSnapshotPoolingCacheSize" value = "100000"/>
NCacheServer.SnapshotPoolSize can be used to specify the number of snapshots allowed in the pool for enumeration. Once the pool reaches its maximum limit, it won’t allow more snapshots to be added to the pool. It will wait till any existing snapshot in the pool has been removed. Default Size is 10 snapshots in cache snapshot pool.
<add key = "NCacheServer.SnapshotPoolSize" value = "10"/>
NCacheServer.SnapshotCreationThreshold can be used to specify after how many seconds a new snapshot will be added to pool for enumeration purpose. Same cache snapshot from the pool is provided to all enumerators on cache until the threshold time is elapsed. Any enumerator that requests a snapshot after that will get a new snapshot from the pool. Default size is 30 seconds.
<add key = "NCacheServer.SnapshotCreationThreshold" value = "30"/>
NCacheServer.EnumeratorChunkSize can be used to specify the chunk size for enumeration. Chunk size is the number of cache items returned to the enumerator from cache server. Once the enumerator is done enumerating through a chunk of data it will get the next chunk from the cache server for enumeration. Default size is 1000 items returned in each chunk.
<add key = "NCacheServer.EnumeratorChunkSize" value = "1000"/>
See Also
Clustered Cache Operation | Remote Client Operations | Client Cache Operations | Local Cache Operations | Register Server-Side Code | Bridge Topology Operations


Topic: Configuring with Command Line Tools

Configuring with Command Line Tools

This section discusses various command line tools which are categorized in various groups according to the different options available in NCache Management tree.
In This Section
Clustered Cache Operations
Describes command line tools for Clustered Cache Operations.
Remote Client Operations
Describes command line tools for Remote Client Operations.
Client Cache Operations
Describes command line tools for Client Cache Operations.
Local Cache Operations
Describes command line tools for Local Cache Operations.


Topic: Clustered Cache Operations

Clustered Cache Operations

This section discusses various command line tools for clustered cache operations.
In This Section
Create a New Clustered Cache
Describes how a createcache utility allows you to register a new cache on a server.
Add Node to Cache Cluster
Describes how an addnode utility allows you to add a node to an already existing clustered cache.
Remove Node from Cache Cluster
Describes how a removenode utility removes a node from an already existing clustered cache.
Start/Stop a Cache Server
Describes how start/stopcache utility allows you to start/stop an already registered cache on a server.
Clear Cache Content
Describes how clearcache utility clears the cache contents.


Topic: Add Node

Add Node

The addnode utility allows you to add a node to an already existing clustered cache. The effect of this utility is that the configuration of the cache is added to the specified server and is updated on all other nodes indicating that this server has become a part of the clustered cache.
addnode cache-id /e[existing] server-name1 /n[new] server-name2 [option[...]]
Argument | Description
cache-id | Specify id of the clustered cache to which the node will be added.
/e [existing] server-name1
Specify a server-name where NCache service is running and a clustered cache with the specified cache-id is registered.
/n [new] server-name2
Specify the server-name where NCache service is also running which is to be added in the already existing clustered cache.
Option | Description
/p port | Specifies port if the server channel is not using the default port. The default TCP port is 8250.
/uid user-id | user-id is required when security is enabled on Cache Server. user-id must be the active directory user-id prefixed with the domain name.
/pwd password | Specifies password to authorize the user, when security is enabled on Cache Server, for starting NCache. This password must be the same as the active directory user password.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
The system, where you use addnode utility, must have NCache service installed and running. To start the service on a system, you must have access rights.
Examples
The following command picks the 'myCache' configuration from 'theSourceSever' and if found registers the same cache on 'theDestServer'.
addnode myCache /e theSourceServer /n theDestServer
The following command displays command syntax and options for the utility. Logo banner is displayed as a part.
addnode /?
The following command displays command syntax and options for the utility suppressing the display of logo banner.
addnode /? /nologo
See Also
Create a New Clustered Cache | Remove Node from Cache Cluster | Start/Stop a Cache Server | Clear Cache Content


Topic: Start/Stop Cache

Start/Stop Cache

The startcache utility allows you to start an already registered cache on a server.
startcache cache-id(s) [option[...]]
Argument | Description
cache-id(s) | Specifies one or more id(s) of the cache(s) registered on the server.
Option | Description
/s server-name | Specifies a server name where the NCache service is running. The default is the local machine.
/p port | Specifies the port if the server channel is not using the default port. The default TCP port is 8250.
/uid user-id | user-id is required when security is enabled on Cache Server. user-id must be the active directory user-id prefixed with the domain name.
/pwd password | Specifies password to authorize the user, when security is enabled on Cache Server, for starting NCache. This password must be the same as the active directory user password.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
You can specify multiple cache-ids on the same command line.
The system, where you use startcache utility, must have NCache service installed and running. By default, startcache utility tries to start the service if it is not running. But if it fails to do so, you must start the service manually. To start the service on a system, you must have access rights.
Examples
The following command starts a cache 'theCache' on the local machine. 'theCache' is already registered on the local machine.
startcache theCache
The following command starts the caches 'theCache' and 'thePartitionedCache' on the local machine.
startcache theCache thePartitionedCache
The following command starts a cache 'theCache' on a server 'theServer'.
startcache theCache /s theServer
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
startcache /?
The following command displays the command syntax and options for the utility suppressing the display of the logo banner.
startcache /? /nologo
The stopcache utility allows you to stop an already running cache on a server.
stopcache cache-id(s) [option[...]]
Argument | Description
cache-id(s) | Specifies one or more id(s) of the cache(s) running on the server.
Option | Description
/s server-name | Specifies a server name where the NCache service is running. The default is the local machine.
/p port | Specifies the port if the server channel is not using the default port. The default TCP port is 8250.
/uid user-id | user-id is required when security is enabled on Cache Server. user-id must be the active directory user-id prefixed with the domain name.
/pwd password | Specifies password to authorize the user, when security is enabled on Cache Server, for stopping NCache. This password must be the same as the active directory user password.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
You can specify multiple cache-ids on the same command line.
The system, where you use stopcache utility, must have NCache service installed and running. By default, stopcache utility tries to start the service if it is not running. But if it fails to do so, you must start the service manually. To start the service on a system, you must have access rights.
Examples
The following command stops a cache 'theCache' on the local machine.
stopcache theCache
The following command stops the caches 'theCache' and 'thePartitionedCache' on a server 'theServer'.
stopcache theCache thePartitionedCache /s theServer
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
stopcache /?
The following command displays the command syntax and options for the utility suppressing the display of the logo banner .
stopcache /? /nolog
See Also
Create a New Clustered Cache | Add Node to Cache Cluster | Remove Node from Cache Cluster | Clear Cache Content


Topic: Remove Node

Remove Node

removenode utility removes a node from an already existing clustered cache. The effect of removenode utility is that the configuration of the cache is removed from the specified server and is updated on all other nodes indicating that this node is no more part of the clustered cache.
removenode cache-id [option[...]]
Argument | Description
cache-id | Specify the id of the clustered cache that will be removed from the server.
Option | Description
/s server-name | Specify the server name from where the specified clustered cache will be removed. NCache service must be running on this server.
/p admin-port | Specifies the port if the server channel is not using the default port. The default port for the channel is 8250.
/uid user-id | user-id is required when security is enabled on Cache Server. user-id must be the active directory user-id prefixed with the domain name.
/pwd password | Specifies password to authorize the user, when security is enabled on Cache Server, for stopping NCache. This password must be the same as the active directory user password.
/nologo | Suppresses the startup banner and copyright message.
/? | Displays command syntax and options for the utility.
Remarks
The system, where you use removenode utility, must have NCache service installed and running. To start the service on a system, you must have access rights.
Examples
The following command removes a cache 'theCache' from the server1.
removenode theCache /s server1
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
removenode /?
The following command displays the command syntax and options for the utility suppressing the display of the startup banner .
removenode /? /nologo
See Also
Create a New Clustered Cache | Add Node to Cache Cluster | Start/Stop a Cache Server | Clear Cache Content


Topic: Create Cache

Create Cache

The createcache utility allows you to register a new cache on a server.
createcache cache-id [option[...]]
Argument | Description
cache-id | Specifies a id of the cache to be registered on the server.
Option | Description
/s server-name | Specifies a server name where the NCache service is running. The default is the local machine.
/p port | Specifies the port if the server channel is not using the default port. The default TCP port is 8250.
/size cache-size | Specifies the size(MB) of the cache to be created. The default size is 250 MB
/evict-policy /e eviction-policy | Specifies the eviction policy for cache items. Cached items will be cleaned from the cache according to the specified policy if the cache reaches its limit. The default eviction policy is Priority.
/ratio /r eviction-ratio | Specifies the eviction ratio (Percentage) for cache items. Cached items will be cleaned from the cache according to the specified ratio if the cache reaches its limit. The default eviction ratio is 5%.
/interval /i clean-interval | Specifies the time interval (seconds) after which cache eviction is called. The default interval is 15 seconds.
/topology /t topology-name | Specifies the topology in case of clustered cache. The default topology is local-cache.
/cluster-port /c port of cluster | Specifies the port of the server, at which server listens. The default port is 8250.
/def-priority /d default-priority | Specifies the default priority in case of priority based eviction policy. The default priority is Normal.
/uid user-id | user-id is required when security is enabled on Cache Server. user-id must be the active directory user-id prefixed with the domain name.
/pwd password | Specifies password to authorize the user, when security is enabled on Cache Server, for starting NCache. This password must be the same as the active directory user password.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
The system, where you use createcache utility, must have NCache service installed and running. By default, createcache utility tries to start the service if it is not running, but if it fails to do so, you must start the service manually. To start the service on a system, you must have access rights.
Examples
The following command creates a cache 'theCache' on the local machine.
createcache theCache
The following command creates a cache 'theCache' on a server 'theServer'.
createcache theCache /s theServer
The following command creates a cache 'theCache' on a server 'theServer' having following details, cache-size '250 MB', eviction-policy 'lru', eviction ratio '5%', clean-interval '30sec', topology 'mirror'.
createcache theCache /s theServer /size 250 /e lru /r 5 /i 30 /t mirror
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
createcache /?
The following command displays the command syntax and options for the utility suppressing the display of the logo banner.
createcache /? /nologo
See Also
Add Node to Cache Cluster | Remove Node from Cache Cluster | Start/Stop a Cache Server | Clear Cache Content


Topic: Clear Cache

Clear Cache

This utility clears the cache contents.
clearcache cache-id [option[...]]
Argument | Description
cache-id | Specify the id of the cache that you intend to clear.
Option | Description
/f[orceclear] | Force the clearing of the cache. If not specified the user will be asked before clearing cache contents.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
The system, where you use clearcache utility, must have NCache service installed and running. To start the service on a system, you must have access rights.
Examples
The following command clears the contents of 'myCache'.
clearcache myCache
The following command displays command syntax and options for the utility. Logo banner is displayed as a part.
clearcache /?
The following command displays command syntax and options for the utility suppressing the display of logo banner.
clearcache /? /nologo
See Also
Create a New Clustered Cache | Add Node to Cache Cluster | Remove Node from Cache Cluster | Start/Stop a Cache Server


Topic: Remote Client Operations

Remote Client Operations

This section discusses various command line tools for Remote client operations.
In This Section
Add Remote Client
Describes how an addclientnode utility allows you to add a client node in an already created cluster.
Remove Remote Client
removeclientnode utility allows you to remove a particular client node from a cluster.


Topic: Add Client Node

Add Client Node

The addclientnode utility allows you to add a client node in an already created cluster.
addclientnode cache-id(s) /s[servername] server-name /c[clientnode] [option[...]]
Argument | Description
cache-id(s) | Specifies one or more id(s) of a Clustered Cache. Cache must exist on source server.
/s[servername] source-server-name | Specifies a server name where the NCache service is running and a cache with the specified cache-id is registered. Cache configuration is copied from this server to the destination server. The default is the local machine.
/c[clientnode] new-client-node-name | Specifies a client node where the NCache service is running and a cache with the specified cache-id is present.
Option | Description
/p[port] port-number | Specifies a port number for communication with the NCache server.
/nologo | Suppresses display of the logo banner.
/? | Displays command syntax and options for the utility.
Remarks
You can add multiple client nodes in a clustered cache.
The system, where you use addclientnode utility, must have NCache service installed and running. By default, addclientnode utility tries to add a client node if it is not already exists in a cluster. Otherwise it will prompt an error.
Examples
The following command adds a client node on a specified cache and server.
addclientnode mycache /s 20.200.20.2 /c 20.200.20.2
The following command specifies the port number for communication with NCache server.
addclientnode mycache /s 20.200.20.2 /c 20.200.20.2 /p 7803
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
addclientnode mycache /s 20.200.20.2 /c 20.200.20.2 /?
The following command displays the command syntax and options for the utility suppressing the display of the logo banner.
addclientnode mycache /s 20.200.20.2 /c 20.200.20.2 /? /nologo
See Also
Remove Remote Client


Topic: Remove Client Node

Remove Client Node

The removeclientnode utility allows you to remove a particular client node from a cluster.
removeclientnode cache-id(s) /s[servername] server-name /c[clientnode] [option[...]]
Argument | Description
cache-id(s) | Specifies one or more id(s) of a Clustered Cache. Cache must exist on source server.
/s[servername] source-server-name | Specifies a server name where the NCache service is running and a cache with the specified cache-id is registered. Cache configuration is copied from this server to the destination server. The default is the local machine.
/c[clientnode] client-node-name | Specifies the client node name where the NCache service is running to remove it from the cache's current client nodes.
Option | Description
/p[port] port-number | Specifies a port number for communication with the NCache server.
/nologo | Suppresses display of the logo banner.
/? | Displays command syntax and options for the utility.
Remarks
The system, where you use removeclientnode utility, must have NCache service installed and running. By default, removeclientnode utility tries to remove a client node if it is already exists in a cluster. Otherwise it will prompt an error.
Examples
The following command removes a client node from a specified cache and server.
removeclientnode mycache /s 20.200.20.2 /c 20.200.20.2
The following command specifies the port number for communication with NCache server.
removeclientnode mycache /s 20.200.20.2 /c 20.200.20.2 /p 7803
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
removeclientnode mycache /s 20.200.20.2 /c 20.200.20.2 /?
The following command displays the command syntax and options for the utility suppressing the display of the logo banner.
removeclientnode mycache /s 20.200.20.2 /c 20.200.20.2 /? /nologo
See Also
Add Remote Client


Topic: Client Cache Operations

Client Cache Operations

This section discusses various command line tools for client cache operations.
In This Section
Create New Cache
Describes how a createclientcache utility allows you to create a client cache on all client nodes already added in a cluster.
Remove Cache
Describes how a removeclientcache utility allows you to remove a client cache from all client nodes in a cluster.
Clear Cache Content
Describes how clearcache utility clears the cache contents.


Topic: Remove Client Cache

Remove Client Cache

The removeclientcache utility allows you to remove a client cache from all client nodes in a cluster.
RemoveClientCache client-cache-id /c[clusterid] cluster-id /s[servername] server-name [option[...]]
Argument | Description
client-cache-id | Specifies the name or Id of Client Cache.
/c[clusterid] cluster-id | Specifies the clustered cache name. A clustered cache must be specified for removing a client cache.
/s[servername] source-server-name | Specifies a server name where the NCache service is running and a cache with the specified cache-id is registered. Cache configuration is copied from this server to the destination server. The default is the local machine.
Option | Description
/p[port] port-number | Specifies a port number for communication with the NCache server.
/nologo | Suppresses display of the logo banner.
/? | Displays command syntax and options for the utility.
Remarks
removeclientcache will remove a client cache from all client nodes in a cluster.
The system, where you use removeclientcache utility, must have NCache service installed and running. By default, removeclientcache utility tries to remove a client cache from all client nodes if it exists in a cluster. Otherwise it will prompt an error.
Examples
The following command removes a client cache from all node on a specified cache and server.
removeclientcache mycache /c ClusteredCache /s 20.200.20.2
The following command specifies the port number for communication with NCache server.
removeclientcache mycache /c ClusteredCache /s 20.200.20.2 /p 7803
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
removeclientcache mycache /c ClusteredCache /s 20.200.20.2 /?
The following command displays the command syntax and options for the utility suppressing the display of the logo banner.
removeclientcache mycache /c ClusteredCache /s 20.200.20.2 /? /nologo
See Also
Create New Cache | Clear Cache Content


Topic: Create Client Cache

Create Client Cache

The createclientcache utility allows you to create a client cache on all client nodes already added in a cluster.
CreateClientCache client-cache-id /c[clusterid] cluster-id /s[servername] server-name [option[...]]
Argument | Description
client-cache-id | Specifies the name or Id of Client Cache.
/c[clusterid] cluster-id | Specifies the clustered cache name. A clustered cache must be specified for creating a client cache.
/s[servername] source-server-name | Specifies a server name where the NCache service is running and a cache with the specified cache-id is registered. Cache configuration is copied from this server to the destination server. The default is the local machine.
Option | Description
/p[port] port-number | Specifies a port number for communication with the NCache server.
/nologo | Suppresses display of the logo banner.
/? | Displays command syntax and options for the utility.
Remarks
You can add only one client cache on all client nodes in a cluster.
The system, where you use createclientcache utility, must have NCache service installed and running. By default, createclientcache utility tries to add a client cache on all client node if no client cache exists in a cluster. Otherwise it will prompt an error.
Examples
The following command creates a client cache on a all client nodes in a specified cache and server.
createclientcache mycache /c ClusteredCache /s 20.200.20.2
The following command specifies the port number for communication with NCache server.
createclientcache mycache /c ClusteredCache /s 20.200.20.2 /p 7803
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
createclientcache mycache /c ClusteredCache /s 20.200.20.2 /?
The following command displays the command syntax and options for the utility suppressing the display of the logo banner.
createclientcache mycache /c ClusteredCache /s 20.200.20.2 /? /nologo
See Also
Remove Cache | Clear Cache Content


Topic: Clear Cache

Clear Cache

This utility clears the cache contents.
clearcache cache-id [option[...]]
Argument | Description
cache-id | Specify the id of the cache that you intend to clear.
Option | Description
/f[orceclear] | Force the clearing of the cache. If not specified the user will be asked before clearing cache contents.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
The system, where you use clearcache utility, must have NCache service installed and running. To start the service on a system, you must have access rights.
Examples
The following command clears the contents of 'myCache'.
clearcache myCache
The following command displays command syntax and options for the utility. Logo banner is displayed as a part.
clearcache /?
The following command displays command syntax and options for the utility suppressing the display of logo banner.
clearcache /? /nologo
See Also
Create New Cache | Remove Cache


Topic: Local Cache Operations

Local Cache Operations

This section discusses various command line tools for Local cache operations.
In This Section
Create a New Cache
Describes how a createcache utility allows you to register a new cache on a server.
Clear Cache Content
Describes how clearcache utility clears the cache contents.


Topic: Create Cache

Create Cache

The createcache utility allows you to register a new cache on a server.
createcache cache-id [option[...]]
Argument | Description
cache-id | Specifies a id of the cache to be registered on the server.
Option | Description
/s server-name | Specifies a server name where the NCache service is running. The default is the local machine.
/p port | Specifies the port if the server channel is not using the default port. The default TCP port is 8250.
/size cache-size | Specifies the size(MB) of the cache to be created. The default size is 250 MB
/evict-policy /e eviction-policy | Specifies the eviction policy for cache items. Cached items will be cleaned from the cache according to the specified policy if the cache reaches its limit. The default eviction policy is Priority.
/ratio /r eviction-ratio | Specifies the eviction ratio(Percentage) for cache items. Cached items will be cleaned from the cache according to the specified ratio if the cache reaches its limit. The default eviction ratio is 5%.
/interval /i clean-interval | Specifies the time interval(seconds) after which cache eviction is called. The default interval is 15 seconds.
/topology /t topology-name | Specifies the topology in case of clustered cache. The default topology is local-cache.
/cluster-port /c port of cluster | Specifies the port of the server, at which server listens. The default port is 8250.
/def-priority /d default-priority | Specifies the default priority in case of priority based eviction policy. The default priority is Normal.
/uid user-id | user-id is required when security is enabled on Cache Server. user-id must be the active directory user-id prefixed with the domain name.
/pwd password | Specifies password to authorize the user, when security is enabled on Cache Server, for starting NCache. This password must be the same as the active directory user password.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
The system, where you use createcache utility, must have NCache service installed and running. By default, createcache utility tries to start the service if it is not running, but if it fails to do so, you must start the service manually. To start the service on a system, you must have access rights.
Examples
The following command creates a cache 'theCache' on the local machine.
createcache theCache
The following command creates a cache 'theCache' on a server 'theServer'.
createcache theCache /s theServer
The following command creates a cache 'theCache' on a server 'theServer' having following details, cache-size '250 MB', eviction-policy 'lru', eviction ratio '5%', clean-interval '30sec', topology 'mirror'.
createcache theCache /s theServer /size 250 /e lru /r 5 /i 30 /t mirror
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
createcache /?
The following command displays the command syntax and options for the utility suppressing the display of the logo banner.
createcache /? /nologo
See Also
Clear Cache Content


Topic: Clear Cache

Clear Cache

This utility clears the cache contents.
clearcache cache-id [option[...]]
Argument | Description
cache-id | Specify the id of the cache that you intend to clear.
Option | Description
/f[orceclear] | Force the clearing of the cache. If not specified the user will be asked before clearing cache contents.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
The system, where you use clearcache utility, must have NCache service installed and running. To start the service on a system, you must have access rights.
Examples
The following command clears the contents of 'myCache'.
clearcache myCache
The following command displays command syntax and options for the utility. Logo banner is displayed as a part.
clearcache /?
The following command displays command syntax and options for the utility suppressing the display of logo banner.
clearcache /? /nologo
See Also
Create a New Cache


Topic: NCache Monitor for Cache Cluster

NCache Monitor for Cache Cluster

NCache Monitor is a diagnostic tool to analyze performance, health and events of a cache cluster both on a local machine and on remote machine. It provides valuable information to system administrators to optimize efficiency of a cache cluster. From this tool, administrators can monitor system events, view detailed information of all nodes in a cluster, monitor performance of a cluster, set alerts and import/export user credentials. Administrators can run the tool as a separate application and can monitor clusters from a computer which is not a part of the cluster or on which NCache service is not installed or running.
In This Section
GUI Tool Overview
Describes the over all NCache Monitor GUI overview.
Server Dashboard
Explains the server dashboard and various graphs that are available on server dashboard.
Client Dashboard
Explains the client dashboard and various graphs that are available on client dashboard.
New Dashboard
Explains the how to create a new dashboard and different view and options available on a newly created dashboard.
Cluster Selection
Explains how to select a cluster in NCache Monitor for monitoring.
Options Menu
Explains option available in NCache Monitor.


Topic: GUI Tool Overview

GUI Tool Overview

You can launch NCache Monitor in two ways:
  • Start --> Programs --> NCache --> NCache Monitor or
  • From NCache Manager, Right click on a 'Cluster' you want to monitor from the 'NCache Management' tree and select 'Monitor Cluster' option from the context menu. It will open the NCache Monitor.
Following are some of the main operations you can perform using NCache Monitor:
  • NCache Monitor provides you the facility to monitor various resources. The first step which needs to be performed is the selection of a cluster. 'Select Cluster Wizard' appears at the start up of the application or using the File --> Select Cluster option.
  • After selection of a cluster in NCache Monitor, now you can either use default dashboards for monitoring performance, health or events of cache cluster or you can create your own dashboard according to your requirements.
  • Dashboard provides different types of views for monitoring various widgets. Views are specific to the widgets. Three types of monitoring views can be displayed in a dashboard as show in the figure below, that are:
  • Graphs
  • Lists
  • Perfmon
  • You can highlight the graph line for clear visibility using the icon shown in the figure below. To highlight the graph first select Highlight icon from the tool bar and then select the line you want to highlight in a graph (in case of multiple nodes).
  • NCache Monitor provides you the facility to set properties for different views. 'Options' menu provide various preferences to customize NCache Monitor graphs and lists. You can access the option dialog from Tools --> Options.
See Also
Configure Cluster Cache


Topic: Server Dashboard

Server Dashboard

Dashboard provides different types of views for monitoring various counters. Views are specific to the counters. After selection of a cluster in NCache Monitor, you can either use default dashboard for monitoring performance, health or events of cache cluster or you can define your own dashboard according to your needs. Server Dashboard is one of the default dashboards which appears automatically after the selection of a cluster. Server dashboard cannot be modified, however you can retrieve server dashboard any time from View option. Server dashboard contains following graphs:
You can view the cluster Dashboard from the following option:
Cluster Health
Cluster health shows the connection status among the nodes of a cluster. It displays information in a form of list having following values:
  • Status: It shows the status of every node in a cluster i.e. running, stopped, state transfer etc
  • Node: Nodes IP addresses are shown in this column.
  • Connection Status: It shows connection status of all the nodes with other nodes in a cluster. A node can either be fully connected (connected to all nodes in a cluster) or partially connected (connected to some of the nodes in a cluster).
  • Broken Link: It shows the broken links of a corresponding node with the other nodes in case of partial connection.
  • Clients: It shows the number of clients connected to the corresponding node.
NCache CPU Graph
NCache CPU graph shows CPU cycles consumed by NCache Server.
NCache Network Graph
NCache Network Graph contains two counters:
  • Current Bandwidth: It is an estimate of the current bandwidth of network interface in bits per second (BPS). For interfaces that do not vary in bandwidth or for those where no accurate estimation can be made, this value is the nominal bandwidth.
  • Bytes Total/sec: It is the rate at which bytes are sent and received over each network adapter, including framing characters. Network Interface/Bytes Received/sec is a sum of Network Interface/Bytes Received/sec and Network Interface/Bytes Sent/sec.
Cache Size Graph
Cache Size graph shows cache data against the total capacity of the cache.
NCache Request/sec Graph
Number of requests received (meaning cache commands like add, get, insert, remove etc.) from all clients by this cache server.
NCache Memory Graph
Private Bytes is current size of the memory in bytes that shows this process has allocated and cannot be shared with other processes.
Events Logs
Here you can monitor events of all registered sources. Source can be any software that logged the event, which can be either an application name such as NCache, or a component of the system or a large application such as ASP.NET. Event log service records all the events in the Application logs. The Application log contains events logged by applications or programs. For example, a database program might record a file error in the Application log. The program developer decides which events to record.
Event Viewer : A component you can use to view and manage event logs.
Any event of a registered source fired will be shown with respect to the node in Event Logs view. It contains the following values:
  • Type: Type/category of the event which is logged by the registered source, that is: Information, Error or Warning.
  • Node: IP of the node that has fired this event.
  • Date: Date at which the event is logged on a corresponding node.
  • Time: Time of the event.
  • Source: Source which generates the event, this can be any source which are registered in Event log.
  • Message: Actual message of the event. You can add number of sources in Event Log to monitor activities on that source.
See Also
NCache Monitor Dashboard | NCache Monitor Options


Topic: Client Dashboard

Client Dashboard

Client Dashboard is one of the default dashboards which appears automatically after the selection of a cluster. Client dashboard cannot be modified, however you can retrieve client dashboard any time using View option. Client dashboard contains following graphs:
You can view the cluster Dashboard from the following option:
NCache Client CPU Graph
% Processor Time is the percentage of elapsed time that a processor spends to execute a non-Idle thread. It is calculated by measuring the duration in which an idle thread is active in sample interval and subtracting from total interval. (Each processor has an idle thread that consumes cycles when no other threads are ready to run). This counter is the primary indicator of processor activity, and displays the average percentage of busy time observed during the sample interval. It is calculated by monitoring the time that the service is inactive, and subtracting that value from 100%. It is against the Total instance. The category of this graph is Processor and the counter is % Processor Time.
NCache Client Memory Graph
Committed Bytes is the amount of committed virtual memory, in bytes. Committed memory is the physical memory which has space reserved on the disk paging file(s). There can be one or more paging files on each physical drive. This counter displays the last observed value only; it is not an average. The category of this graph is Memory and the counter is Committed Bytes.
NCache Client Network Usage Graph
NCache Client Network Usage graph contains two counters:
  • Current Bandwidth is an estimate of the current bandwidth of the network interface in bits per second (BPS). For interfaces that do not vary in bandwidth or for those where no accurate estimation can be made, this value is the nominal bandwidth.
  • Bytes Total/sec is the rate at which bytes are sent and received over each network adapter, including framing characters. Network Interface/Bytes Received/sec is a sum of Network Interface/Bytes Received/sec and Network Interface/Bytes Sent/sec.
This category of this graph is NCache Client.
NCache Client Req Queue Graph
This graph shows the total number of requests from all clients on a single machine waiting for response from cache server. The category of this graph is NCache Client and the counter is Request Queue Size/sec.
NCache Client Read Ops/sec
This graph shows the number of Read operations per second. The category of this graph is NCache Client and the counter is Read Operations/sec.
NCache Client Write Ops/sec
This graph shows the number of Write operations per second. The category of this graph is NCache Client and the counter is Write Operations/sec.
ASP.NET Requests/sec Graph
This graph shows the number of requests executed per second. It is against the Total instance. The category of this graph is ASP.NET Applications and the counter is Requests/sec.
ASP.NET Pending Queue/sec Graph
This graph shows the number of requests in the application request queue. It is against the Total instance. The category of this graph is ASP.NET Applications and the counter is Requests in Application Queue.
ASP.NET Total Sessions Graph
This graph shows the total number of sessions since the application was started. It is against the Total instance. The category of this graph is ASP.NET Applications and the counter is Session Total.
See Also
NCache Monitor Dashboard | NCache Monitor Options


Topic: NCache Monitor Defining Dashboard

NCache Monitor Defining Dashboard

After selection of a cluster in NCache Monitor, now you can either use the default dashboards for monitoring performance, health or events of cache cluster or you can create your own dashboards according to your needs. Default dashboards cannot be modified, however you can make any modifications in your own dashboards.
Step 1
  • To create a new dashboard, follow these steps:
  • Select File --> 'New Dashboard' to create a new dashboard as shown in figure.
Step 2
  • Following screen will appear for creating a new dashboard.
  • Enter 'Dashboard Name'.
  • Click 'Next' to move to the next screen.
Step 3
  • Specify number of Rows and Columns required in a dashboard.
  • You can set different number of columns in every row.
  • On finishing the above steps following screen will be displayed having three rows and a single column as specified above.
  • You can create more than one dashboards for a selected cache cluster.
  • All the open dashboards created against cluster will be automatically saved on closing NCache Monitor, and will be retrieved whenever that cluster is selected for monitoring.
  • The closed dashboards are not saved for a selected cluster.
Step 4
  • You can monitor the widgets of a selected cache cluster by dragging a counter from a Toolbox to a dashboard.
Toolbox contains different counters for monitoring performance, health and events of a cache cluster. Widgets are categorized in two groups that are:
  • NCache Server: It contains pre-define NCache server widgets.
  • NCache Client: It contains pre-define NCache client widgets.
See Also
NCache Monitor Cluster | NCache Monitor Options


Topic: New Dashboard

New Dashboard

Item Count Graph
This graph shows number of items in the cache against cache instances. The category of this graph is NCache and the counter is Count.
Additions/sec Graph
This graph shows the number of Add operations per second. It is against the cache instance. The category of this graph is NCache and the counter is Addition/sec.
Fetches/sec Graph
This graph shows the number of Get operations per second. It is against the cache instance. The category of this graph is NCache and the counter is Fetches/sec.
Updates/sec Graph
This graph shows the number of Insert operations per second. It is against the cache instance. The category of this graph is NCache and the counter is Updates/sec.
Deletes/sec Graph
This graph shows the number of Remove operations per second. It is against the cache instance. The category of this graph is NCache and the counter is Deletes/sec.
Client Process Statistics
Here you can monitor the processes running on different clients connected to the selected cluster. It displays information in a list having following values:
  • Process ID : It shows all the process IDs running currently on various clients connected to the selected cluster.
  • Client IP : It shows list of client IPs connected to the selected cluster on which processes are running.
  • Port : It shows the client port.
  • Client IP : It shows list of server IPs in a selected cluster.
  • Sent Bytes : It shows the number of bytes sent by each process.
  • Received Bytes : It shows the number of bytes received by each process.
In Client Process Statistics list you can group the statistical data on the basis of any parameter listed above. For grouping we need to drag the parameter to the Drag space. For example the following figure shows the grouping of process on the basis of Server IP. You can also undo the grouping by dragging the parameter back from a drag bar to the list.
System CPU Usage
% Processor Time is the percentage of elapsed time that the processor spends to execute a non-Idle thread. It is calculated by measuring the duration in which an idle thread is active in the sample interval and subtracting from total interval (Each processor has an idle thread that consumes cycles when no other threads are ready to run). This counter is the primary indicator of processor activity, and displays the average percentage of busy time observed during the sample interval. It is calculated by monitoring time the that the service is inactive, and subtracting that value from 100%. It is against the Total instance. The category of this graph is Processor and the counter is % Processor Time.
System Memory Usage
Committed Bytes is the amount of committed virtual memory, in bytes. Committed memory is the physical memory which has space reserved on the disk paging file(s). There can be one or more paging files on each physical drive. This counter displays the last observed value only; it is not an average. The category of this graph is Memory and the counter is Committed Bytes.
PerfMon Control
Perfmon is used for general purpose counters which are not provided by us. Here you can add any counter for monitoring the performance. Perfmon is a normal windows control and can be used in a same way. All the added widgets will be saved on closing the NCache Monitor.
See Also
NCache Monitor Dashboard | NCache Monitor Options


Topic: NCache Monitor Cluster Selection

NCache Monitor Cluster Selection

NCache Monitor provides you the facility to monitor various resources. The first step which needs to be performed is selection of the cluster. 'Select Cluster Wizard' appears at the start up of the application or using the File --> Select Cluster option.
Step 1
  • "Select Cluster Wizard" screen appears as shown below.
  • Select a node from a list of 'Available Nodes'. Node must be the part of that cluster you want to monitor. Or, you can manually specify the node name or IP address in the text box.
  • Click 'Next' to proceed further.
Step 2
  • The selected node can be a part of more than one cluster. Select a cluster you want to monitor from the list of clusters running on that particular node.
  • Click 'Finish' to add the cluster.
  • The cluster will be added in NCache Monitor for monitoring its performance, health and events.
See Also
NCache Monitor Dashboard | NCache Monitor Options


Topic: NCache Monitor Options

NCache Monitor Options

NCache Monitor provides you the facility to set the properties for different views. 'Options' menu provide various preferences to customize NCache Monitor graphs and lists. You can access the option dialog from Tools --> Options.
Step 1
  • Tools --> Options --> General.
  • Using Options --> General screen you can set Sampling Rate value for a graph. Sampling rate is the time after which the data will be collected from all the nodes connected to the cache cluster for monitoring performance.
  • Enter the Sample Rate value and press OK button to apply the changes.
Step 2
  • Tools --> Options --> Graph.
  • You can also set the Time Interval (x-axis value) for a graph to be displayed using the following screen. For example if you specify time interval of 3 minutes then dashboard will show 3 minutes performance graph at one time.
  • Enter the Time Interval value and press OK button to apply the changes.
Step 3
  • Tools --> Options --> Event Logs.
  • This option dialog is used to register the sources for which you want to monitor events. The events logged against registered sources can be seen in Event Logs at dashboard. Every application logs its events to event viewer with its unique source name.
  • Source is the application that logged the event, which can be either an application name such as NCache, or a component of the system or a large application such as ASP.NET.
  • Enter the number log entries you want to display in option dialog at Log entries to display text box.
  • To register a source you need to enter the source name in Event Source text box.
  • Press Add button to add the source in the Source list.
  • You can also remove the source using Remove button.
See Also
NCache Monitor Cluster | NCache Monitor Dashboard


Topic: Command LineTools

Command LineTools

NCache is provided with a good number of command line utilities. Most of them are there to deal with the caches. They provide an efficient way to register, unregister, start, stop and activate caches. They also provide a way to view the list of all registered caches along with their current status. 'genmackeys' is an exception, that generates machine keys.
In This Section
createcache
Describes how to create a cache.
addnode
Explains how to add a node to an already existing clustered cache.
removenode
Describes how to remove a node from a clustered cache.
addtestdata
Describes how to add test data to an already existing cache.
dumpcache
Describes how to dump the available cache keys on a server.
configurenodesecurity
Describes how to configure node level security.
startcache
Describes how to start an already registered cache using startcache command line utility.
stopcache
Describes stopcache command line utility used to stop an already running cache.
listcaches
Describes using listcaches command line utility to get a list of all registered caches.
addclientnode
Describes how to add a client node in a cluster.
configureclient
Describes how to configure a client node.
configurecachesecurity
Describes how to configure cache level security.
removeclientnode
Describes how to remove a client node from a cluster.
createclientcache
Describes how to create a client cache in a cluster.
removeclientcache
Describes how to remove a client cache from a cluster.
Upgrade Configuration
Describes how to upgrade the configuration file and make a backup copy on a same location.
stresstesttool
Describes StressTestTool command line tool used to evaluate and monitor NCache's overall performance under high transactional environment.
PowerShell Create cache Scripts
Describes how to use Create cache script for creating a Clustered cache or local cache.
See Also
Getting Started
Familiarizes you with the fundamentals of NCache and offers help to use NCache quickly and efficiently.
Configuring the Cache
Discusses configuration options that NCache provides for local and clustered caches. It also helps in configuring NCache through NCache Manager and configuration files.
Developing with NCache
Focuses on what is essential to become skilled at developing with NCache. It includes programmers guide, sample applications, hands on tutorials and extensive help on API reference.


Topic: createcache

createcache

The createcache utility allows you to register a new cache on a server.
createcache cache-id [option[...]]
Argument | Description
cache-id | Specifies a id of the cache to be registered on the server.
Option | Description
/s server-name | Specifies a server name where the NCache service is running. The default is the local machine.
/p port | Specifies the port if the server channel is not using the default port. The default TCP port is 8250.
/size cache-size | Specifies the size(MB) of the cache to be created. The default size is 250 MB
/evict-policy /e eviction-policy | Specifies the eviction policy for cache items. Cached items will be cleaned from the cache according to the specified policy if the cache reaches its limit. The default eviction policy is Priority.
/ratio /r eviction-ratio | Specifies the eviction ratio(Percentage) for cache items. Cached items will be cleaned from the cache according to the specified ratio if the cache reaches its limit. The default eviction ratio is 5%.
/interval /i clean-interval | Specifies the time interval(seconds) after which cache eviction is called. The default interval is 15 seconds.
/topology /t topology-name | Specifies the topology in case of clustered cache. The default topology is local-cache.
/cluster-port /c port of cluster | Specifies the port of the server, at which server listens. The default port is 8250.
/def-priority /d default-priority | Specifies the default priority in case of priority based eviction policy. The default priority is Normal.
/uid user-id | user-id is required when security is enabled on Cache Server. user-id must be the active directory user-id prefixed with the domain name.
/pwd password | Specifies password to authorize the user, when security is enabled on Cache Server, for starting NCache. This password must be the same as the active directory user password.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
The system, where you use createcache utility, must have NCache service installed and running. By default, createcache utility tries to start the service if it is not running, but if it fails to do so, you must start service manually. To start service on a system, you must have access rights.
Examples
The following command creates a cache 'theCache' on the local machine.
createcache theCache
The following command creates a cache 'theCache' on a server 'theServer'.
createcache theCache /s theServer
The following command creates a cache 'theCache' on a server 'theServer' having following details, cache-size '250 MB', eviction-policy 'lru', eviction ratio '5%', clean-interval '30sec', topology 'mirror'.
createcache theCache /s theServer /size 250 /e lru /r 5 /i 30 /t mirror
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
createcache /?
The following command displays the command syntax and options for the utility suppressing the display of the logo banner.
createcache /? /nologo
See Also
listcaches | addnode | removenode | stopcache | addtestdata | startcache | addclientnode | removeclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: addnode

addnode

The addnode utility allows you to add a node to an already existing clustered cache. The effect of this utility is that the configuration of the cache is added to the specified server and is updated on all other nodes indicating that this server has become a part of the clustered cache.
addnode cache-id /e[existing] server-name1 /n[new] server-name2 [option[...]]
Argument | Description
cache-id | Specify id of the clustered cache to which the node will be added.
/e [existing] server-name1
Specify a server-name where NCache service is running and a clustered cache with the specified cache-id is registered.
/n [new] server-name2
Specify the server-name where NCache service is also running which is to be added in the already existing clustered cache.
Option | Description
/p port | Specifies port if the server channel is not using the default port. The default TCP port is 8250.
/uid user-id | user-id is required when security is enabled on Cache Server. user-id must be the active directory user-id prefixed with the domain name.
/pwd password | Specifies password to authorize the user, when security is enabled on Cache Server, for starting NCache. This password must be the same as the active directory user password.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
The system, where you use addnode utility, must have NCache service installed and running. To start the service on a system, you must have access rights.
Examples
The following command picks the 'myCache' configuration from 'theSourceSever' and if found registers the same cache on 'theDestServer'.
addnode myCache /e theSourceServer /n theDestServer
The following command displays command syntax and options for the utility. Logo banner is displayed as a part.
addnode /?
The following command displays command syntax and options for the utility suppressing the display of logo banner.
addnode /? /nologo
See Also
listcaches | removenode | startcache | stopcache | addtestdata | addclientnode | removeclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: removenode

removenode

removenode utility removes a node from an already existing clustered cache. The effect of removenode utility is that the configuration of the cache is removed from the specified server and is updated on all other nodes indicating that this node is no more part of the clustered cache.
removenode cache-id [option[...]]
Argument | Description
cache-id | Specify the id of the clustered cache that will be removed from the server.
Option | Description
/s server-name | Specify the server name from where the specified clustered cache will be removed. NCache service must be running on this server.
/p admin-port | Specifies the port if the server channel is not using the default port. The default port for the channel is 8250.
/uid user-id | user-id is required when security is enabled on Cache Server. user-id must be the active directory user-id prefixed with the domain name.
/pwd password | Specifies password to authorize the user, when security is enabled on Cache Server, for stopping NCache. This password must be the same as the active directory user password.
/nologo | Suppresses the startup banner and copyright message.
/? | Displays command syntax and options for the utility.
Remarks
The system where you use removenode utility, must have NCache service installed and running. To start service on a system, you must have access rights.
Examples
The following command removes a cache 'theCache' from the server1.
removenode theCache /s server1
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
removenode /?
The following command displays the command syntax and options for the utility suppressing the display of the startup banner .
removenode /? /nologo
See Also
listcaches | addnode | startcache | stopcache | addtestdata | addclientnode | removeclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: addtestdata

addtestdata

Adds some test data into a specified cache as we could do in Enterprise edition by NCache Manger to see whether cluster is joined or not.
For .Net setup: addtestdata cache-id [option[...]]
For Java setup: java -cp "addtestdata.jar:$CLASSPATH" com.alachisoft.tools.addtestdata mycache
Argument | Description
cache-id | Specify the id of the cache
Option | Description
/c[ount] | Specify the number of items to be added to the cache. By default 10 items are added to the cache.
/s[size] | Specify the size (in bytes) of each item to be added to the cache. By default each item of size1k (1024 bytes) is added to the cache.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
The system where you use addtestdata utility, must have NCache service installed and running. To start service on a system, you must have access rights.
Examples
The following command adds 10 items to 'myCache', each of size 256 (bytes).
addtestdata myCache /c 10 /s 256
The following command displays command syntax and options for the utility. Logo banner is displayed as a part.
addtestdata /?
The following command displays command syntax and options for the utility suppressing the display of logo banner.
addtestdata /? /nologo
See Also
listcaches | removenode | startcache | stopcache | clearcache | addnode | addclientnode | removeclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: dumpcache

dumpcache

The dumpcache utility dumps the available cache keys to Console or given out-put file.
For .Net setup: dumpcache cache-id [option[...]]
For Java setup: java -cp "dumpcache.jar:$CLASSPATH" com.alachisoft.tools.dumpcache mycache
Argument | Description
cache-id | Specifies an id of the cache that is running on the server.
Option | Description
keycount | Specifies number of keys to be dumped. The default is 1000.
keyfilter | Specifies a substring that a key contains.
/? | Displays command syntax and options for the utility.
Remarks
The system, where you use dumpcache utility, must have NCache service installed and running.
Examples
The following command dumps a cache 'theCache' on the local machine.
dumpcache theCache
The following command dumps a cache 'theCache' on the local machine with keycount 2000.
dumpcache theCache 2000
The following command dumps a cache 'theCache' on the local machine with keycount 2000 having keyfilter 'ryan'.
dumpcache theCache 2000 ryan
To dump cache to an output file, you can use > sign to get console-out to a file. For example If keys need to be dumped under file Keys.txt you can use following command.
dumpcache theCache 2000 ryan > Keys.txt
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
dumpcache /?
See Also
listcaches | addnode | removenode | stopcache | addtestdata | clearcache | startcache | createcache | addclientnode | removeclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: configurenodesecurity

configurenodesecurity

The configurenodesecurity utility allows you to configure security on a client node in an already created cluster.
configurenodesecurity /es[enablesecurity] /n[nodename] node-name /a[adminid] admin-name /p[password] password
Argument | Description
/es[enablesecurity] | Specifies that the tool is being used for enabling security on a specific node.
/n[nodename] node-name | Specifies the target node to enable security.
/a[adminid] admin-name | Specifies the administrator Id. To enable security on any node, it is vital to have administrative rights.
/p[password] password | Specifies the administrator password.
configurenodesecurity /ds[disablesecurity] /n[nodename] node-name /u[userid] user-name /p[password] password /dc[domaincontroller] domain-controller
Argument | Description
/ds[disablesecurity] | Specifies that the tool is being used for disabling security on a specific node.
/n[nodename] node-name | Specifies the target node to disable security.
/u[userid] user-name | Specifies the user Id. This user name can also be an administrator, because to disable security you can either be an NCache node administrator or you have the administrator rights on the target node.
/p[password] password | Specifies the password against the user name.
/dc[domaincontroller] domain-controller | Specifies the domain controller.
configurenodesecurity /au[adduser] /n[newusername] new-user-name /nn[nodename] node-name /u[userid] user-name /p[password] password /dc[domaincontroller] domain-controller
Argument | Description
/au[adduser] | Specifies that the tool is being used for adding a user to NCache node administrators.
/n[newusername] | Specifies the new user name to add.
/nn[nodename] node-name | Specifies the target node on which the user exists.
/u[userid] user-name | Specifies the domain user Id.
/p[password] password | Specifies the password against the user name.
/dc[domaincontroller] domain-controller | Specifies the domain controller.
configurenodesecurity /ru[removeuser] /d[deleteuser] user-to-delete /u[username] user-name /p[password] password /dc[domaincontroller] domain-controller
Argument | Description
/ru[removeuser] | Specifies that the tool is being used for removing a user from NCache node administrators.
/d[deleteuser] user-to-delete | Specifies the existing user which is now being deleted/removed from NCache node administrators.
/u[userid] user-name | Specifies the domain user Id.
/p[password] password | Specifies the password against the user name.
/dc[domaincontroller] domain-controller | Specifies the domain controller.
Remarks
You can enable/disable node level security any time.
The system where you use configurenodesecurity utility, must have NCache service installed and running. By default, configurenodesecurity utility tries to enable security on a specified client node.
Examples
The following command enables security on a specified client node.
configurenodesecurity /e /n 20.200.20.2 /a Admin /p
The following command disables security on a specified client node for a particular user.
configurenodesecurity /d /n 20.200.20.2 /u User /p Password/dc 20.200.20.32
The following command adds a new user to NCache administrators node.
configurenodesecurity /a /n User /nn 20.200.20.2 /u User /p Password/dc 20.200.20.32
The following command removes user from NCache administrators node.
configurenodesecurity /r /d User /u User /p Password/dc 20.200.20.32
See Also
listcaches | addnode | removenode | startcache | stopcache | addtestdata | addclientnode | removeclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurcachesecurity


Topic: startcache

startcache

The startcache utility allows you to start an already registered cache on a server.
startcache cache-id(s) [option[...]]
Argument | Description
cache-id(s) | Specifies one or more id(s) of the cache(s) registered on the server.
Option | Description
/s server-name | Specifies a server name where the NCache service is running. The default is the local machine.
/p port | Specifies the port if the server channel is not using the default port. The default TCP port is 8250.
/uid user-id | user-id is required when security is enabled on Cache Server. user-id must be the active directory user-id prefixed with the domain name.
/pwd password | Specifies password to authorize the user, when security is enabled on Cache Server, for starting NCache. This password must be the same as the active directory user password.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
You can specify multiple cache-ids on the same command line.
The system, where you use startcache utility, must have NCache service installed and running. By default, startcache utility tries to start the service if it is not running. But if it fails to do so, you must start the service manually. To start the service on a system, you must have access rights.
Examples
The following command starts a cache 'theCache' on the local machine. 'theCache' is already registered on the local machine.
startcache theCache
The following command starts the caches 'theCache' and 'thePartitionedCache' on the local machine.
startcache theCache thePartitionedCache
The following command starts a cache 'theCache' on a server 'theServer'.
startcache theCache /s theServer
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
startcache /?
The following command displays the command syntax and options for the utility suppressing the display of the logo banner.
startcache /? /nologo
See Also
listcaches | addnode | removenode | stopcache | addtestdata | addclientnode | removeclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: stopcache

stopcache

The stopcache utility allows you to stop an already running cache on a server.
stopcache cache-id(s) [option[...]]
Argument | Description
cache-id(s) | Specifies one or more id(s) of the cache(s) running on the server.
Option | Description
/s server-name | Specifies a server name where the NCache service is running. The default is the local machine.
/p port | Specifies the port if the server channel is not using the default port. The default TCP port is 8250.
/uid user-id | user-id is required when security is enabled on Cache Server. user-id must be the active directory user-id prefixed with the domain name.
/pwd password | Specifies password to authorize the user, when security is enabled on Cache Server, for stopping NCache. This password must be the same as the active directory user password.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
You can specify multiple cache-ids on the same command line.
The system where you use stopcache utility, must have NCache service installed and running. By default, stopcache utility tries to start the service if it is not running. But if it fails to do so, you must start the service manually. To start the service on a system, you must have access rights.
Examples
The following command stops a cache 'theCache' on the local machine.
stopcache theCache
The following command stops the caches 'theCache' and 'thePartitionedCache' on a server 'theServer'.
stopcache theCache thePartitionedCache /s theServer
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
stopcache /?
The following command displays the command syntax and options for the utility suppressing the display of the logo banner .
stopcache /? /nologo
See Also
listcaches | addnode | removenode | startcache | addtestdata | addclientnode | removeclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: listcaches

listcaches

The listcaches utility allows you to get a list of all the caches registered on the server along with their current status.
listcaches [option[...]]
Option | Description
/s server-name | Specifies a server name where the NCache service is running. The default is the local machine.
/p port | Specifies the port if the server channel is not using the default port. The default TCP port is 8250.
/a | Displays a detailed information about the cache(s) registered on the server.
/x | Displays configuration as part of the detailed information in XML format. This parameter affects only when /a is also specified.
/z | Displays configuration as part of the detailed information in property-string format. This parameter affects only when /a is also specified.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
The system where you use listcaches utility, must have NCache service installed and running. By default, listcaches utility tries to start the service if it is not running. But if it fails to do so, you must start the service manually. To start service on a system, you must have access rights.
Examples
The following command lists all the caches, registered on the local machine.
listcaches
The following command lists all the caches, registered on a server 'theServer'.
listcaches /s theServer
The following command displays the detailed information about all the caches registered on the local machine and their configurations using property string.
listcaches /a /z
The following command displays the configuration of all the caches registered on the local machine in XML format.
listcaches /a /x
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
listcaches /?
The following command displays the command syntax and options for the utility suppressing the display of logo banner.
listcaches /? /nologo
See Also
addnode | removenode | startcache | stopcache | addtestdata | addclientnode | removeclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity
Send Comments on this Topic


Topic: addclientnode

addclientnode

The addclientnode utility allows you to add a client node in an already created cluster.
addclientnode cache-id(s) /s[servername] server-name /c[clientnode] [option[...]]
Argument | Description
cache-id(s) | Specifies one or more id(s) of a Clustered Cache. Cache must exist on source server.
/s[servername] source-server-name | Specifies a server name where the NCache service is running and a cache with the specified cache-id is registered. Cache configuration is copied from this server to the destination server. The default is the local machine.
/c[clientnode] new-client-node-name | Specifies a client node where the NCache service is running and a cache with the specified cache-id is present.
Option | Description
/p[port] port-number | Specifies a port number for communication with the NCache server.
/nologo | Suppresses display of the logo banner.
/? | Displays command syntax and options for the utility.
Remarks
You can add multiple client nodes in a clustered cache.
The system where you use addclientnode utility, must have NCache service installed and running. By default, addclientnode utility tries to add a client node if it is not already exists in a cluster. Otherwise it will prompt an error.
Examples
The following command adds a client node on a specified cache and server.
addclientnode mycache /s 20.200.20.2 /c 20.200.20.2
The following command specifies the port number for communication with NCache server.
addclientnode mycache /s 20.200.20.2 /c 20.200.20.2 /p 7803
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
addclientnode mycache /s 20.200.20.2 /c 20.200.20.2 /?
The following command displays the command syntax and options for the utility suppressing the display of the logo banner.
addclientnode mycache /s 20.200.20.2 /c 20.200.20.2 /? /nologo
See Also
listcaches | addnode | removenode | startcache | stopcache | addtestdata | emoveclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: configureclient

configureclient

The configureclient utility allows you to configure/update client.ncconf of a client machine with the given information.
configureclient cache-id /s server-name [option[...]]
Argument | Description
cache-id | Specifies a cache-id which is running on specified client, and to be updated on the client.ncconf of specified client machine.
/s server-name | Specifies one or more server name(s) where the clustered cache exists. Servers list should be comma separated
Option | Description
/c client-name | Specifies a client name where the client.ncconf to be updated. The default is the local machine.
/p port | Specifies the port if the server channel is not using the default port. The default TCP port is 8250.
/cc client-cache | Specifies a local-cache-name which will be updated on the client.ncconf of specified client.
/l load-balance | Specifies whether the load-balancing is set true or false. The default is true.
/uid user-id | user-id is required when security is enabled on Cache Server. user-id must be the active directory user-id prefixed with the domain name.
/pwd password | Specifies password to authorize the user, when security is enabled on Cache Server. This password must be the same as the active directory user password.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
You can specify multiple server-names on the same command line.
Examples
The following command updates client.ncconf on the local machine with cache-id 'theCache' running on server 'theServer'.
configureclient theCache /s theServer
The following command updates client.ncconf on the client machine 'theClient; with cache-id 'theCache' running on server 'theServer'.
configureclient theCache /s theServer /c theClient
The following command updates client.ncconf on the client machine 'theClient; with cache-id 'theCache' running on servers 'Server1,Server2,Server3', with load-balance 'true' and client-cache 'theClientCache'.
configureclient theCache /s Server1,Server2,Server3 /c theClient /cc theClientCache /l true
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
configureclient /?
The following command displays the command syntax and options for the utility suppressing the display of the logo banner .
configureclient /? /nologo
See Also
listcaches | addnode | removenode | startcache | addtestdata | clearcache | getcachecount | createcache | addclientnode | removeclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: configurecachesecurity

configurecachesecurity

The configurecachesecurity utility allows you to configure security on a client cache in an already created cluster.
configurecachesecurity /es[enablesecurity] /c[cacheid] cache-name /s[servername] server-name /u[user-id] user name /p[password] password /dc[domaincontroller] domain-controller [option[...]].
Argument | Description
/es[enablesecurity] | Specifies that the tool is being used for enabling security on a specific cache.
/c[cacheid] cache-name | Specifies the target cache to enable security.
/s[servername] server-name | Specifies the server node name.
/a[user-id] user name | Specifies the NCache administrator name.
/p[password] password | Specifies the NCache administrator password.
/dc[domaincontroller] domain-controller | Specifies the domain controller.
configurecachesecurity /ds[disablesecurity] /c[cacheid] cache-name /s[servername] server-name /u[userid] user-name /p[password] password /dc[domaincontroller] domain-controller
Argument | Description
/ds[disablesecurity] | Specifies that the tool is being used for disabling security on a specific cache.
/s[servername] server-name | Specifies the server node name.
/u[userid] user-name | Specifies the NCache administrator name.
/p[password] password | Specifies the NCache administrator password.
/dc[domaincontroller] domain-controller | Specifies the domain controller.
configurecachesecurity /au[adduser] /n[newusername] new-user /s[servername] server-name /u[userid] user-name /p[password] password /dc[domaincontroller] domain-controller
Argument | Description
/au[adduser] | Specifies that the tool is being used for adding a user in Cache administrator's list.
/n[newusername] new-user | Specifies the user name to add.
/s[servername] server-name | Specifies the server node name.
/u[userid] user-name | Specifies the NCache administrator name.
/p[password] password | Specifies the NCache administrator password.
/dc[domaincontroller] domain-controller | Specifies the domain controller.
configurecachesecurity /ru[removeuser] /d[deleteuser] user-to-delete /s[servername] server-name /u[username] user-name /p[password] password /dc[domaincontroller] domain-controller
Argument | Description
/ru[removeuser] | Specifies that the tool is being used for removing a user from Cache administrator's list.
/d[deleteuser] user-to-delete | Specifies the existing user which is now being deleted or removed from NCache node administrators.
/s[servername] server-name | Specifies the server node name.
/u[userid] user-name | Specifies the domain user Id.
/p[password] password | Specifies the password against the user name.
/dc[domaincontroller] domain-controller | Specifies the domain controller.
Remarks
You can enable/disable cache level security any time.
The system where you use configurecachesecurity utility, must have NCache service installed and running. By default, configurecachesecurity utility tries to enable security on a specified client cache.
Examples
The following command enables security on a specified client cache.
configurecachesecurity /e /c mycache /s 20.200.20.2 /u User /p Password/dc 20.200.20.32 [option[...]].
The following command disables security on a specified client cache for a particular user.
configurecachesecurity /d /c mycache /s 20.200.20.2 /u User /p Password/dc 20.200.20.32
The following command adds a new user to cache administrator's.
configurecachesecurity /a /n User /s 20.200.20.2 /u User /p Password/dc 20.200.20.32
The following command removes user from cache administrator's list.
configurecachesecurity /r /d User /s 20.200.20.2 /u User /p Password/dc 20.200.20.32
See Also
listcaches | addnode | removenode | startcache | stopcache | addtestdata | ddclientnode | removeclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity


Topic: removeclientnode

removeclientnode

The removeclientnode utility allows you to remove a particular client node from a cluster.
removeclientnode cache-id(s) /s[servername] server-name /c[clientnode] [option[...]]
Argument | Description
cache-id(s) | Specifies one or more id(s) of a Clustered Cache. Cache must exist on source server.
/s[servername] source-server-name | Specifies a server name where the NCache service is running and a cache with the specified cache-id is registered. Cache configuration is copied from this server to the destination server. The default is the local machine.
/c[clientnode] client-node-name | Specifies the client node name where the NCache service is running to remove it from the cache's current client nodes.
Option | Description
/p[port] port-number | Specifies a port number for communication with the NCache server.
/nologo | Suppresses display of the logo banner.
/? | Displays command syntax and options for the utility.
Remarks
The system where you use removeclientnode utility, must have NCache service installed and running. By default, removeclientnode utility tries to remove a client node if it is already exists in a cluster. Otherwise it will prompt an error.
Examples
The following command removes a client node from a specified cache and server.
removeclientnode mycache /s 20.200.20.2 /c 20.200.20.2
The following command specifies the port number for communication with NCache server.
removeclientnode mycache /s 20.200.20.2 /c 20.200.20.2 /p 7803
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
removeclientnode mycache /s 20.200.20.2 /c 20.200.20.2 /?
The following command displays the command syntax and options for the utility suppressing the display of the logo banner.
removeclientnode mycache /s 20.200.20.2 /c 20.200.20.2 /? /nologo
See Also
listcaches | addnode | removenode | startcache | stopcache | addtestdata | addclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: getcachecount

getcachecount

The getcachecount utility allows you to view the number of items in the cache.
For .Net setup: GetCacheCount cache-id [option[...]]
For Java setup: java -cp "getcachecount.jar:$CLASSPATH" com.alachisoft.tools.getcachecount mycache
Argument | Description
cache-id | Specify id of the cache that you want to get count of.
Option | Description
/s server | Specifies a server name where the NCache service is running. The default is the local machine.
/p port | Specifies port if the server channel is not using the default port. The default TCP port is 8250.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
The system where you use getcachecount utility, must have NCache service installed and running.
Examples
The following command picks the 'myCache' configuration from 'theSever' and if found, gets the number of items it contains.
getcachecount myCache /s theServer
The following command displays command syntax and options for the utility. Logo banner is displayed as a part.
getcachecount /?
See Also
listcaches | removenode | startcache | stopcache | addtestdata | clearcache | addclientnode | removeclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: createclientcache

createclientcache

The createclientcache utility allows you to create a client cache on all client nodes already added in a cluster.
CreateClientCache client-cache-id /c[clusterid] cluster-id /s[servername] server-name [option[...]]
Argument | Description
client-cache-id | Specifies the name or Id of Client Cache.
/c[clusterid] cluster-id | Specifies the clustered cache name. A clustered cache must be specified for creating a client cache.
/s[servername] source-server-name | Specifies a server name where the NCache service is running and a cache with the specified cache-id is registered. Cache configuration is copied from this server to the destination server. The default is the local machine.
Option | Description
/p[port] port-number | Specifies a port number for communication with the NCache server.
/nologo | Suppresses display of the logo banner.
/? | Displays command syntax and options for the utility.
Remarks
You can add only one client cache on all client nodes in a cluster.
The system where you use createclientcache utility, must have NCache service installed and running. By default, createclientcache utility tries to add a client cache on all client node if no client cache exists in a cluster. Otherwise it will prompt an error.
Examples
The following command creates a client cache on a all client nodes in a specified cache and server.
createclientcache mycache /c ClusteredCache /s 20.200.20.2
The following command specifies the port number for communication with NCache server.
createclientcache mycache /c ClusteredCache /s 20.200.20.2 /p 7803
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
createclientcache mycache /c ClusteredCache /s 20.200.20.2 /?
The following command displays the command syntax and options for the utility suppressing the display of the logo banner.
createclientcache mycache /c ClusteredCache /s 20.200.20.2 /? /nologo
See Also
listcaches | addnode | removenode | startcache | stopcache | addtestdata | addclientnode | removeclientnode | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: removeclientcache

removeclientcache

The removeclientcache utility allows you to remove a client cache from all client nodes in a cluster.
RemoveClientCache client-cache-id /c[clusterid] cluster-id /s[servername] server-name [option[...]]
Argument | Description
client-cache-id | Specifies the name or Id of Client Cache.
/c[clusterid] cluster-id | Specifies the clustered cache name. A clustered cache must be specified for removing a client cache.
/s[servername] source-server-name | Specifies a server name where the NCache service is running and a cache with the specified cache-id is registered. Cache configuration is copied from this server to the destination server. The default is the local machine.
Option | Description
/p[port] port-number | Specifies a port number for communication with the NCache server.
/nologo | Suppresses display of the logo banner.
/? | Displays command syntax and options for the utility.
Remarks
removeclientcache will remove a client cache from all client nodes in a cluster.
The system where you use removeclientcache utility, must have NCache service installed and running. By default, removeclientcache utility tries to remove a client cache from all client nodes if it exists in a cluster. Otherwise it will prompt an error.
Examples
The following command removes a client cache from all node on a specified cache and server.
removeclientcache mycache /c ClusteredCache /s 20.200.20.2
The following command specifies the port number for communication with NCache server.
removeclientcache mycache /c ClusteredCache /s 20.200.20.2 /p 7803
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
removeclientcache mycache /c ClusteredCache /s 20.200.20.2 /?
The following command displays the command syntax and options for the utility suppressing the display of the logo banner.
removeclientcache mycache /c ClusteredCache /s 20.200.20.2 /? /nologo
See Also
listcaches | addnode | removenode | startcache | stopcache | addtestdata | clearcache | addclientnode | removeclientnode | createclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: clearcache

clearcache

This utility clears the cache contents.
For .Net setup: clearcache cache-id [option[...]]
For Java setup: java -cp "clearcache.jar:$CLASSPATH" com.alachisoft.tools.clearcache mycache
Argument | Description
cache-id | Specify the id of the cache that you intend to clear.
Option | Description
/f[orceclear] | Force the clearing of the cache. If not specified the user will be asked before clearing cache contents.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
The system where you use clearcache utility, must have NCache service installed and running. To start the service on a system, you must have access rights.
Examples
The following command clears the contents of 'myCache'.
clearcache myCache
The following command displays command syntax and options for the utility. Logo banner is displayed as a part.
clearcache /?
The following command displays command syntax and options for the utility suppressing the display of logo banner.
clearcache /? /nologo
See Also
listcaches | removenode | startcache | stopcache | addtestdata | addnode | addclientnode | removeclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: upgradeconfiguration

upgradeconfiguration

The upgradeconfiguration utility allows you to upgrade the configuration file and make a backup copy on a same location.
upgradeconfiguration /f[filepath] /c[copy] [options[...]]
Argument | Description
/f[filepath] file-path | Specifies the path of the configuration file that is to be upgraded, along with the file name.
/c[copy] copy | Indicates weather or not a backup copy must be created before upgrading the original config. The copied file is placed at the same location.
Option | Description
/nologo | Suppresses display of the logo banner.
/? | Displays command syntax and options for the utility.
Remarks
The system where you use upgradeconfiguration utility, must have NCache service installed and running. By default, upgradeconfiguration utility tries to upgrade the configuration file and create its backup.
Examples
The following command upgrades the configuration file and makes a backup copy of it.
upgradeconfiguration /f "C://NCache//Config.ncconf" /c
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
upgradeconfiguration /f "C://NCache//Config.ncconf" /c /?
The following command displays the command syntax and options for the utility suppressing the display of the logo banner.
upgradeconfiguration /f "C://NCache//Config.ncconf" /c /? /nologo
See Also
listcaches | addnode | removenode | startcache | stopcache | addtestdata | clearcache | addclientnode | removeclientnode | createclientcache | removeclientcache | configurnodesecurity | configurcachesecurity


Topic: stresstesttool

stresstesttool

StressTestTool.exe allows you to quickly simulate heavy transactional load on a given cache. And, this helps you to see how NCache actually performs under stress in your own environment.
Please watch NCache performance counters in NCache Manager "statistics" or in regular PerfMon.
NOTE:
A test case represents a user session or multiple get and update operations on the same cache key. Use test case to simulate an ASP.NET or JSP sessions. When all test-case-iterations are used, a user session becomes idle and left to expire.
Each test-case-iteration consists of one or more gets and updates (ASP.NET session simulation would use 1 get and 1 update). And test-case-iteration-delay represents a delay between each iteration and can be used to simulate ASP.NET session behavior where a user clicks on a URL after 15-30 seconds delay.
For .Net setup: stresstesttool cache-id [option[...]]
For Java setup: java -cp "stresstesttool.jar:$CLASSPATH" com.alachisoft.tools.stresstesttool mycache
Argument | Description
cache-id | Name of the cache.
Option | Description
/n item-count | How many total items you want to add. (default: infinite)
/i test-case-iterations | How many iterations within a test case (default: 20)
/d test-case-iteration-delay | How much delay (in seconds) between each test case iteration (default: 0)
/g gets-per-iteration | How many gets within one iteration of a test case (default: 1)
/u updates-per-iteration | How many updates within one iteration of a test case (default: 1)
/s item-size | Specify in bytes the size of each cache item (default: 1024)
/e sliding-expiration | Specify in seconds sliding expiration (default: 300; minimum: 15)
/t thread-count | How many client threads (default: 1; max: 3)
/r reporting-interval | Report after this many total iterations (default: 5000)
/nologo | Suppresses the startup banner and copyright message.
/? | Displays a detailed help screen.
Remarks
The system where you use stresstesttool, must have NCache service installed and running. To start the service on a system, you must have access rights.
Examples
The following command tests 'myCache'.
stresstesttool myCache /n 2 /i 20 /d 2 /g 2 /u 2 /s 512 /e 20 /t 1 /r 3000
The following command displays command syntax and options for the utility. Logo banner is displayed as a part.
stresstesttool /?
The following command displays command syntax and options for the utility suppressing the display of logo banner.
stresstesttool /? /nologo
See Also
listcaches | removenode | startcache | stopcache | clearcache | addnode | addclientnode | removeclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: genmackeys

genmackeys

NOTE: This feature is not available in NCache Express and Professional edition.
'genmackeys' utility configures keys to use for encryption and decryption of forms authentication cookie data and view state data, and for verification of out-of-process session state identification. When executed, it gives a 'validationKey', 'decryptionKey' and 'type of encryption used to validate data'. This information can then be provided in ASP.NET application's web.config file in <machinekey .. /> . While using distributed session in a webfarm, it is required so that ASP.NET session IDs are generated in same manner on all nodes.
genmackeys [option[...]]
Option | Description
/vklen validationKey length | Specifies the length of key used for validation of encrypted data. The key must be a minimum of 40 characters (20 bytes) and a maximum of 128 characters (64 bytes) long. Default is 20 bytes.
/dklen decryptionKey length | Specifies the length of key used to encrypt data. The key should be 16 characters in length when using DES encryption and 48 characters in length when using Triple DES encryption. Default is 16 characters.
/enc {SHA1|AES|MDS|3DES} | Specifies the type of encryption used for validation of data. This value can be 'SHA1', 'AES', 'MD5' or '3DES'. Default is 'SHA1'.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
For more information on using machine keys, see msdn help.
Examples
The following command generates the validation key and decryption key using default lengths and default encryption type i.e. 'SHA1'.
genmackeys
The following command generates the validation key using a key length of 64 characters and a decryption key using a key length of 48 characters.
genmackeys /vklen 64 /dklen 48
The following command generates the validation key and decryption key with encryption type '3DES'.
genmackeys /enc 3DES
The following command displays the command syntax and options for the utility. Logo banner is displayed as a part.
genmackeys /?
The following command displays the command syntax and options for the utility suppressing the display of logo banner.
genmackeys /? /nologo
See Also
listcaches | addnode | removenode | startcache | stopcache | getcachecount | Keep Alive | addtestdata | clearcache | addclientnode | removeclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: Keep Alive

Keep Alive

NOTE: This feature is not available in NCache Express and Professional edition.
NCache can be used both InProc and OutProc. If you want to use NCache InProc in your Web Application you have to keep it in the application scope. In ASP.NET the application times out if no session is maintained on it during the period of timeout. To make it sure that application never times out, we have to create a temporary session at least once before the timeout so that timeout never occurs. Keep Alive Application is used for this purpose.
You can specify any number of URLs and related intervals after which it will send an http request to the given URL to create a temporary session on the application.
You may add or remove any URL through Add or Remove button. Or you may go to the File menu option and select Add URL or Remove URL option for adding or removing a URL respectively. To remove the URL you must select the URL to be removed from the list of URLs before selecting the remove option.
On Add URL dialog you can type the URL in the text box and select or type an interval in the interval box. Click OK to add the URL or Cancel to cancel the operation.
See Also
listcaches | addnode | removenode | startcache | stopcache | genmackeys | getcachecount | addtestdata | clearcache | addclientnode | removeclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: Log Analyzer

Log Analyzer

NOTE: This feature is not available in NCache Express and Professional edition.
'loganalyzer' tool helps you collect all the license logs from your cache servers and merge them in one place. It produces two reports i.e. 'user report.txt' and 'server report.txt'. 'user report.txt' is readable and for your information only. 'server report.txt' is for Alachisoft servers for license compliance verification.
This tool is required in environments where it can become a tedious process to activate NCache on each machine. In such environments, NCache is only activated on cache servers while the cache clients use these servers' licensing information to prove their identity. In such environments, loganalyzer must be run as and when required by Alachisoft.
The tool LogAnalyzer.exe is placed inside the tools folder along with LogAnalyzer.exe.config. LogAnalyzer.exe.config must be configured properly before running the tool.
LogAnalyzer is only required to be run on one of the cache server machines. However the configuration file must contain the names of all servers.
Following are the details regarding LogAnalyzer.exe.config.
<configuration>
<appSettings>
<!-- Enter the email address used at the time of activation -->
<add key="email" value="fuller@alachisoft.com"/>
<!-- Enter a comma seperated list of servers below -->
<add key="servers" value="sanfransisco, sanramon, sanjose"/>
<!-- Enter the path of the folder where processed log will be saved -->
<add key="output_folder" value="c:/reports"/>
<!--
Specify auto_upload as true if you want this tool to automatically send the log file to Alachisoft.
Otherwise you can email serverreport.txt in the 'output_folder' to support@alachisoft.com
Note: It requires active internet connection and access to port 80
-->
<add key="auto_upload" value="true"/>
</appSettings>
</configuration>
  • email: This is the email which you use for official communication with Alachisoft sales/support. e.g. myemail@mydomain.com
  • servers: This is a comma separated list of cache servers that are licensed i.e. server1, server2, server3
  • output_folder: This is the folder where the reports are saved after merging.
  • auto_upload: Setting this to true will configure the tool to automatically send the 'server report.txt' file to Alachisoft.
Running the tool generates a couple of files in the output folder specified in the config file. The file 'user report.txt' is in readable form and is only for user information. However, the file 'server report.txt' is in encoded format and is readable only by Alachisoft servers. This file can automatically be uploaded to Alachisoft servers by configuring the 'auto_upload' attribute value equal to true. If you do not want it to be uploaded automatically or in case of an exception during auto upload, you can email it to support@alachisoft.com .
Note: Make sure that value of key NCacheServer.LicenseLogging in Alachisoft.NCache.Service.exe.config is set to true. Also restart the NCache service for changes to take affect.
See Also
listcaches | addnode | removenode | startcache | stopcache | genmackeys | addtestdata | clearcache | getcachecount | addclientnode | removeclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: Administrators-guide-forPowerShell

CreateCache using PowerShell Script

This PowerShell script allows users to automate the process of creating local or clustered caches. This tool comes very handy for automating the deployment process in your QA, staging, and production environments. Internally it uses the CreateCache command line tool for cache creation. The only difference is that it can accept servers list (comma separated list) instead of single server for creating a clustered cache.
Please refer to the Troubleshooting Install script section if you have any issues in executing this script. You should find the UninstallNCache .ps1 script at the NCache installation path in the integration folder:
%INSTALLPATH%/NCache/Integration/PowerShell/ CreateCache.ps1
PS C:/Users>./CreateCache.ps1 cache-id /uid server-username /pwd server-password [option[...]]
Argument | Description
cache-id | Specifies an ID of the cache to be registered on a server.
/uid | Specify a valid user name that has permissions to execute the command on remote machine.
/pwd | Specify a valid password.
Option | Description
/s server-name | Specify one or more cache server names in comma separated format and make sure the service is running on all of these machines. Default is local machine. Example /s Server1, Server2, Server3.
/p port | Specifies the port if the server channel is not using the default port. The default is 8251 for http and 8250 for tcp channels.
/size cache-size | Specify cache memory size in terms MBs which is the amount of data the cache can store. Default value is 250MB
/evict-policy /e eviction-policy | Specifies the eviction policy for cache items. Cached items will be cleaned from the cache according to the specified policy if the cache reaches its limit. Possible values are: Priority, LFU, LRU (default).
/ratio eviction-ratio /r | Specifies the eviction ratio (Percentage) for cache items. Cached items will be cleaned from the cache according to the specified ratio if the cache reaches its limit. Default value is 5 %.
/interval clean-interval /i | Specify an interval after which cache should start the cleaning process and then wait for the next interval. Default clean-interval is 15 seconds.
/topology topology-name /t | Specifies the topology in case of clustered cache. Possible values are: partitioned-replicas-server, mirror, replicated and partitioned.
/replication-strategy /rs | Only in case of 'partition-replicas-server' being the topology, this specifies the replication strategy: async (default) or sync.
/cluster-port /c | Specify an available or unique port for cluster communication. Default is 7800.
/def-priority /d default-priority | Specifies the default priority in case priority based eviction policy is selected. Possible values are: high, above-normal, normal (default), below-normal and low.
/nologo | Suppresses the display of logo banner.
/? | Displays command syntax and options for the utility.
Remarks
In the following examples we will create a Local Cache, Replicated Cache and Partitioned Replica cache on three machines Test1, Test2, and Test3 using the PowerShell script CreateCache.ps1. It is assumed that NCache is installed on the default path "C:/program files". You must have to provide valid admin user ID and password that has the permissions to execute commands on remote machine.
Example of Creating Local Cache
PS C:/Program Files/ncache/integration/PowerShell>./CreateCache.ps1 myLocalCache /s Test1 /uid administrator /pwd 123pwd
This will create a local-cache "myLocalCache" on server "Test1" with default configuration. Please replace the server "Test1" with your own server name and user id, password with the actual user credentials.
Example of Creating Partitioned Replica Cache
PS C:/Program Files/ncache/integration/PowerShell>./CreateCache.ps1 test_part_replica /s Test1, Test2, Test3 /e priority /r 5 /size 500 /t partitioned-replica /c 7870 /uid administrator /pwd 123pwd
This will create a partitioned-replica cache cluster "test_part_replica" of three nodes (Test1, Test2, and Test3) of Size 500MB, eviction-policy priority eviction-ratio 5 and cluster-port 7870 and configuration will be updated on all cache servers.
Example of Creating Replicated Cache
PS C:/Program Files/ncache/integration/PowerShell>./CreateCache.ps1 test_repl_cache /s Test1, Test2 /e priority /r 5 /size 500 /t replicated /c 7880 /uid administrator /pwd 123pwd
This will create a replicated cache cluster " test_repl_cache" of two nodes (Test1 and Test2) and configuration will be updated on all cache servers.


Topic: Alachisoft (R) NCache Utility Verify NCache License

Alachisoft (R) NCache Utility Verify NCache License

This tool verifies NCache License. For registered version it will display the registration details. In evaluation mode it will display the remaining day if evaluation is still valid else give the expiration message.
java -cp "verifyncachelicense.jar:$CLASSPATH" com.alachisoft.tools.verifyncachelicense
Option | Description
/nologo | Suppresses the startup banner and copyright message.
/? | Displays command syntax and options for the utility.
Usage:
Verifyncachelicense [option[...]].
See Also
listcaches | removenode | startcache | stopcache | addtestdata | clearcache | addclientnode | removeclientnode | createclientcache | removeclientcache | upgradeconfiguration | configurnodesecurity | configurcachesecurity


Topic: Developing with NCache

Developing with NCache

This section focuses on what is essential to become skilled at developing with NCache. It includes programmer's guide and extensive help on API reference. Programmer's guide provides practical help for using advanced features of NCache. API reference presents reference to NCache class library so that you can utilize namespaces, methods and properties effectively.
In This Section
.Net Programmers Guide
Provides a practical guide for programmers who want to use various features of NCache to develop high performance and scalable .NET applications.
Java Programmers Guide
Provides a practical guide for programmers who want to use various features of NCache to develop high performance and scalable Java applications.
See Also
Introduction to NCache
Presents a brief introduction to NCache, with an emphasis on new and old features, editions and requirements of NCache.
Getting Started
Familiarizes you with the fundamentals of NCache and offers help to use NCache quickly and efficiently.
Configuring the Cache
Discusses configuration options that NCache provides for local and clustered caches. It also helps in configuring NCache through NCache Manager and configuration files.
Troubleshooting
Helps you troubleshoot different problems that may arise while using NCache.


Topic: .NET Programmer's Guide

.NET Programmer's Guide

This section provides a practical guide for programmers who want to use various features of NCache in .Net to develop high performance and scalable applications. It provides four different sets of features for programming with NCache. In order to use NCache API in .Net applications, following things are required to be done:
  1. For .Net applications, you must add reference to the 'Alachisoft.NCache.Web.Caching.dll' in your application. This assembly contains all the APIs which are required to connect to the server and use cache. This assembly is copied into the install directory of NCache, by default it is in "%INSTALL_DIR%/NCache/bin/assembly/".
  2. Client API also requires the server list generated from NCache Manager. For this purpose, client configuration file must be placed in NCache install directory. The Client Configuration file is updated whenever you apply configurations to the cache. Information for compact data types is also generated as part of ( config.ncconf ), if the cache is registered with any Compact Serializable data type.
In This Section
Client Side API Programming
Provides a practical guide for client side features.
Server Side API Programming
Provides a practical guide for server side features.
Client Side ASP.NET Features
Demonstrates the use and capabilities of client side ASP.NET features.
Client Side Third Party Integrations
Demonstrates the use and capabilities of client side Third Party Integration tools.


Topic: Client Side API Programming

Client Side API Programming

This tutorial is a practical guide for programmers who want to utilize powerful features of Client side NCache to create high performance and scalable .NET applications. This includes working examples and code snippets to utilize various features of NCache efficiently.
In This Section
Initialize Cache
Explains the procedure how to initialize a cache.
Dispose Cache
Describes how to dispose a cache.
Access Multiple Caches in Single App
Explains way of using multiple caches in a single application.
Get Item
Describes how to get items for the cache.
Add/Update Item
Describes the procedure of adding and inserting/updating items in a cache.
Specify Expiration
Describes how certain cached items can be automatically removed from the cache when required.
Specify Priority
Explains adding items in the cache with priority settings.
Group/Subgroup
Presents distributing related objects in 'logical' groups.
Tags
Explains how Tags work.
Named Tags
Explains how Named Tags work.
Lock/Unlock Item
Describes how to lock cached items to prevent multiple clients from updating the same data simultaneously.
Item Version
Demonstrates how item versioning works.
Streaming API
NCache provides you the facility of Streaming. Using streaming NCache binary data can be read or written from/to the cache using streams.
Bulk Operations
Describes performing bulk operations to add, insert or remove collection of items in a single method call. It helps speeding up the process and minimizes cluster traffic.
Async Operations
Explains utilizing notifications that arise as a result of add, insert or remove operations against all or selective cache items, or when cluster status changes.
Cache Dependency
Explains how to implement dependency of cached items on files, database table rows and other cached items.
Event Notifications
Explains utilizing notifications that arise as a result of add, insert or remove operations against all or selective cache items, or when cluster status changes.
Read-through, Write-through, Write-behind
Shows how to transparently fetch the required data from the master datasource if it is not available in the cache and vice versa.
Queries & LINQ
Presents search API for querying objects from the cache using SQL like syntax.
Continuous Query
Explains how Continuous Query work.


Topic: Overview

How to setup development Environment?

  1. File-> New -> Project.
  2. Select a Console Application from range of generic templates.
  3. Specify the Name for the Application.
  4. Specify the appropriate Location to save a project.
  5. Click OK button to create a new project.
  6. Add the following reference in your application to start working with NCache, as shown in the figure below: Alachisoft.NCache.Web.
  7. Select the reference from the list of references as shown below:
  8. Add the following namespace in your application:
using Alachisoft.NCache.Web.Caching;
See Also
Adding items with priority settings | Using Bulk Operations | Using Data Grouping


Topic: Initialize Cache

Initialize Cache

After you have configured the cache, embed NCache API calls in your application to use it. The first thing you need to do is to initialize the cache. Include the following namespace in your project:
using Alachisoft.NCache.Web.Caching;
The code for initializing the cache is as follows:
// Initialize the cache.
Cache _cache = NCache.InitializeCache("mycache");
Initializing Cache in ASP.NET Applications
If you're developing ASP.NET application, the best place to put InitializeCache call is in your Application_Start() functions in Global.asax.cs file. Additionally, instead of hard coding, we recommend keeping the cache-name in Web.Config and then accessing it from your code. This way, if you will be required to change your cache name at any stage, you won't have to recompile the code.
// Pick up the cache-name from Web.Config
public override void Init()
{
string cacheName = ConfigurationSettings.AppSettings["CacheName"];
Cache _cache = NCache.InitializeCache(cacheName);
}
And, in your Web.Config, you can specify cache name as follows:
<appSettings>
<add key = "CacheName" value = "mycache"/>
</appSettings>
See Also
Adding Items | Finding items | Removing Items | Dispose Cache | Start Cache | Stop Cache


Topic: Add/Update

Add/Update

Once you have a valid cache handle, you can perform "Add" operations. The Add operation has many overloads and the basic overload takes two parameters "key" as string and "value" as object. The value must be a .NET serializable object otherwise NCache will throw a serialization exception.
Include the following namespace in your project:
using Alachisoft.NCache.Web.Caching;
Using Add Method
An "Add" method will add item to the cache only if that item does not already exist in the cache. Otherwise, it will throw an exception.
  1. Create a new Class named 'Customer' in your already created Test Application.
  2. Insert the following code in the 'Customer' class.
    [Serializable]
    class Customer
    {
    ...
    }
  3. Now insert the following code in the 'Main' of the project:
    static void Main( string [] args)
    {
    Cache _cache = NCache.InitializeCache("mycache");
    _cache.Clear();
    Customer customer = new Customer ();
    customer.name = "David" ;
    customer.customerID = 1001;
    customer.City = "London" ;
    customer.ContactNumber = "+44-xxx-xxxx-xxxx" ;
    customer.IsOrderInProcess = true ;
    // Add Item to Cache
    _cache.Add( "Customer:David:1001", customer);
    Object object_Customer = _cache.Get("Customer:David:1001");
    Customer customerInformation = ( Customer )object_Customer;
    Console.WriteLine("Customer ID: " + customerInformation.customerID);
    Console.WriteLine("Name: " + customerInformation.name);
    Console.WriteLine("City: " + customerInformation.City);
    Console.WriteLine("Contact Number: " + customerInformation.ContactNumber);
    Console.WriteLine("Order placed: " + customerInformation.IsOrderInProcess);
    }
  4. Start the Local Cache 'myCache'.
  5. Run the project.
Using Insert Method
Additionally, you can use "Insert" method to either add or update the item in the cache. Insert method adds the item if it does not already exist in the cache. Otherwise, it updates the item.
  1. Create a new Class named 'Customer' in your already created Test Application.
  2. Insert the following code in the 'Customer' class.
    [Serializable]
    class Customer
    {
    ...
    }
  3. Now insert the following code in the 'Main' of the project:
    static void Main( string [] args){
    Cache _cache = NCache.InitializeCache("mycache");
    _cache.Clear();
    Customer customer = new Customer ();
    customer.name = "David" ;
    customer.customerID = 1001;
    customer.City = "London" ;
    customer.ContactNumber = "+44-xxx-xxxx-xxxx" ;
    customer.IsOrderInProcess = true ;
    // Insert Item to Cache
    _cache.Insert("Customer:David:1001", customer);
    Object objectCustomer = _cache.Get("Customer:David:1001");
    Customer customerInformation = (Customer)objectCustomer;
    Console.WriteLine("Customer ID: " + customerInformation.customerID);
    Console.WriteLine("Name: " + customerInformation.name);
    Console.WriteLine("City: " + customerInformation.City);
    Console.WriteLine("Contact Number: " + customerInformation.ContactNumber);
    Console.WriteLine("Order placed: " + customerInformation.IsOrderInProcess);
    }
  4. Start the Local Cache 'myCache'.
  5. Run the project.
See Also
Initialize Cache | Finding items | Removing Items | Dispose Cache | Start Cache | Stop Cache


Topic: Finding Items

Finding Items

Items can be retrieved from the cache either by using a Get method or the cache indexer. Both of the methods are explained below with examples.
Include the following namespace in your project:
using Alachisoft.NCache.Web.Caching;
Using Get Method
Here is how you can retrieve items from the cache.
Cache _cache = NCache.Caches["mycache"];
// Returns null if item not found
object myObject = _cache.Get("Customer:David:1001");
if (myObject == null)
{
// Item not found
}
Using Cache["key"]
Here is another way to retrieve items from the cache.
Cache _cache = NCache.Caches["mycache"];
// Returns null if item not found
object myObject = _cache["Customer:David:1001"];
if (myObject == null)
{
// Item not found
}
Using Contains Method
You can also check whether an item exists in the cache or not.
Cache _cache = NCache.Caches["mycache"];
// Returns true or false
if (_cache.Contains("Customer:David:1001") == false)
{
// Item not found
}
See Also
Initialize Cache | Adding Items | Removing Items | Dispose Cache | Start Cache | Stop Cache


Topic: Delete Items

Delete Items

Once you have a valid cache handle, you can do the "Delete" operations on a cache. This operation has many overloads and the basic overload takes only one parameter i.e. "key" as string.
Include the following namespace in your project:
using Alachisoft.NCache.Web.Caching;
Using Delete Method
A "Delete" method will delete item from the cache only if that item already exist in the cache. Exception will be thrown if the method is unable to delete the key from the cache.
  1. Create a new Class named 'Customer' in your already created Test Application.
  2. Insert the following code in the 'Customer' class.
    [Serializable]
    class Customer
    {
    ...
    }
  3. Now insert the following code in the 'Main' of the project:
    static void Main( string [] args)
    {
    Cache _cache = NCache.InitializeCache("mycache");
    _cache.Clear();
    Customer customer = new Customer();
    customer.name = "David" ;
    customer.customerID = 1001;
    customer.City = "London" ;
    customer.ContactNumber = "+44-xxx-xxxx-xxxx" ;
    customer.IsOrderInProcess = true ;
    // Add Item to the Cache
    _cache.Add("Customer:David:1001", customer);
    // Delete the above Item from the Cache
    _cache.Delete("Customer:David:1001");
    }
  4. Start the Local Cache 'myCache'.
  5. Run the project.
See Also
Initialize Cache | Finding items | Removing Items | Dispose Cache | Start Cache | Stop Cache


Topic: Get Cache Item

Get Cache Item

Items can be retrieved from the cache by using a Get method. Overloaded methods are also explained below:
Include the following namespace in your project:
using Alachisoft.NCache.Web.Caching;
Using Get Method:
Here is how you can retrieve items from the cache.
//returns null if item not found
Object myObject = _cache.Get("Customer:David:1001");
if (myObject == null)
{
//item not found
}
To get latest Cache value of cache Item:
  1. Create a new Class named 'Customer' in your already created Test Application.
  2. Insert the following code in the 'Customer' class.
    [Serializable]
    class Customer
    {
    ...
    }
  3. Now insert the following code in the 'Main' of the project.
Cache _cache = NCache.InitializeCache("mycache");
_cache.Clear();
Customer customer = new Customer();
customer.Name = "David";
customer.Id = 1001;
// Add Item to Cache
_cache.Add("Customer:David:1001", customer);
// Get the latest value with respect to key "Customer:David:1001"
CacheItem cItem = _cache.GetCacheItem("Customer:David:1001");
if (cItem != null) // check if Item exists
{
// do some operations
// ...
// Update Cache Item
_cache.Insert("Customer:David:1001", customer);
CacheItem cItem1 = _cache.GetCacheItem("Customer:David:1001");
Customer customer1 = (Customer)cItem1.Value;
Console.WriteLine("Customer ID: " + customer1.Id);
Console.WriteLine("Name: " + customer1.Name);
}
5. Start the Local Cache 'myCache'.
6. Run the project.
See Also
Initialize Cache | Finding items | Removing Items | Dispose Cache | Start Cache | Stop Cache


Topic: Dispose Cache

Dispose Cache

After you are done using the cache, you can dispose it. Include the following namespace in your project:
using Alachisoft.NCache.Web.Caching;
The code for disposing the cache is as follows:
Cache _cache = NCache.Caches["mycache"];
// Dispose the cache
_cache.Dispose();
Disposing the cache in ASP.NET Applications
If you're developing ASP.NET application, the best place to put Dispose() call is in your Http Application's Dispose() method. This method is called when the instance of your HttpApplication is destroyed.
public virtual void Dispose()
{
Cache _cache = NCache.Caches["mycache"];
// Dispose the cache
_cache.Dispose();
}
See Also
Initialize Cache | Adding Items | Finding items | Removing Items | Start Cache | Stop Cache


Topic: Access Multiple Caches in Single Application

Access Multiple Caches in Single Application

NCache allows you to initialize multiple cache instances in a same application. The following code shows how to use this feature.
1. Include the following namespace in your application.
using Alachisoft.NCache.Web.Caching;
2. Create a new Class named 'Customer' in your already created Test Application.
3. Insert the following code in the 'Customer' class.
[Serializable]
class Customer
{
...
}
4. Now insert the following code in the 'Main' of the project:
Cache _cache1 = NCache.InitializeCache("mycache");
Cache _cache2 = NCache.InitializeCache("myreplicatedcache");
// Perform any of the operations provided by NCache on any of the cache initialized
_cache1.Clear();
_cache2.Clear();
Customer customer = new Customer();
customer.name = "David";
customer.customerID = 1001;
Customer customer1 = new Customer();
customer1.name = "Alex";
customer1.customerID = 1002;
// Add Item to Cache
NCache.Caches["mycache"].Add("Customer:David:1001", customer);
NCache.Caches["myreplicatedcache"].Add("Customer:Alex:1002", customer1);
// Get Items from Cache
Object objectCustomer = NCache.Caches["mycache"].Get("Customer:David:1001");
Object objectCustomer1 = NCache.Caches["myreplicatedcache"].Get("Customer:Alex:1002");
Customer customerInformation = (Customer)objectCustomer;
Console.WriteLine("Customer ID: " + customerInformation.customerID);
Console.WriteLine("Name: " + customerInformation.name);
Console.WriteLine();
customerInformation = (Customer)objectCustomer1;
Console.WriteLine("Customer ID: " + customerInformation.customerID);
Console.WriteLine("Name: " + customerInformation.name);
Console.WriteLine();
5. Start both the caches.
6. Run the project.
See Also
Adding items with priority settings | Using Bulk Operations | Using Data Grouping


Topic: Expiring Cached Items

Expiring Cached Items

An expiration object can be associated with each item being added to the cache. When that expiration object invalidates (invalidation of expiration object depends on the provided parameters), the associated item is removed from the cache. NCache provides two types of expirations i.e. Absolute expiration and Sliding expiration.
Absolute Expiration:
Absolute Expiration is the time in which an added object expires and is removed from the cache.
Sliding Expiration:
Time interval between the last accessed time of the added object and object expiration time. If this interval is equal to 10 minutes, then object will expire and it will be removed from the cache 10 minutes after it is last accessed. If you are using absolute expiration, the slidingExpiration parameter must be NoSlidingExpiration.
Using Absolute and Sliding Expiration:
While adding some items to the cache, you can provide a DateTime value which is translated into Absolute Expiration and the item is removed from the cache at the specified DateTime value. If you don't want to provide any Absolute Expiration, you can use an enumeration (NoAbsoluteExpiration) provided by NCache. Similarly, you can provide a TimeSpan value which is translated into Sliding Expiration and item is removed from the cache if the specified period of time has elapsed since it was last accessed. If you don't want to provide a Sliding Expiration, you can use an enumeration (NoSlidingExpiration) provided by NCache.
Following is a step-by-step guide for using absolute and sliding expirations:
  1. Include the following namespaces in your application:
    using Alachisoft.NCache.Web.Caching;
    using Alachisoft.NCache.Runtime;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    [Serializable]
    class Customer
    {
    ...
    }
  4. Now insert the following code in the 'Main' of the project:
Cache cache = NCache.InitializeCache("mycache");
cache.Clear();
Customer customer1 = new Customer();
customer1.name = "David";
customer1.customerID = 1001;
customer1.OrderPlaced = "C-11";
customer1.City = "New York";
CacheItem cItem1 = new CacheItem(customer1);
//Adding Item with Absolute Expiration:
cache.Add("Customer:David:1001", cItem1, null, System.DateTime.Now.AddSeconds(30), Cache.NoSlidingExpiration, CacheItemPriority.Normal);
Customer customer2 = new Customer();
customer2.name = "Alex";
customer2.customerID = 1002;
customer2.OrderPlaced = "C-10";
customer2.City = "London";
CacheItem cItem2 = new CacheItem(customer2);
//Adding Item with Sliding Expiration:
cache.Add("Customer:Alex:1002", cItem2, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 0, 30), CacheItemPriority.Default);
5. Start the Local Cache 'mycache'.
6. Run the project.
See Also
Using Cache Dependency | Adding items with priority settings | Using Bulk Operations | Using Data Grouping


Topic: Adding items with priority settings

Adding items with priority settings

The cache uses priorities when it has to evict objects. Objects with low priority are removed first from the cache then the objects with higher priority . You can add an item to the Cache with priority settings by using the priority parameter of the Add or Insert method. The following example uses the Add method to add an item to the Cache with a high priority.
  1. Include the following namespaces in your application.
    using Alachisoft.NCache.Web.Caching;
    using Alachisoft.NCache.Runtime;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    [Serializable]
    class Customer
    {
    ......
    }
  4. Now insert the following code in the 'Main' of the project:
    Cache _cache = NCache.InitializeCache("mycache");
    _cache.Clear();
    Customer customer = new Customer ();
    customer.name = "David" ;
    customer.customerID = 1001;
    customer.City = "London" ;
    customer.ContactNumber = "+44-xxx-xxxx-xxxx" ;
    customer.IsOrderInProcess = true ;
    _cache.Add( "Customer:David:1001" , customer, null , Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.High);
    Object objectCustomer = _cache.Get("Customer:David:1001");
    Customer customerInformation = (Customer)objectCustomer;
    Console.WriteLine("Customer ID: " + customerInformation.customerID);
    Console.WriteLine("Name: " + customerInformation.name);
    Console.WriteLine("City: " + customerInformation.City);
    Console.WriteLine("Contact Number: " + customerInformation.ContactNumber);
    Console.WriteLine("Order placed: " + customerInformation.IsOrderInProcess);
  5. Start the Local Cache 'myCache'.
  6. Run the project.
Through NCache Manager, default priority can be specified for items of Caches/Clusters, if no priority is specified for them at the time of addition into cache. See Policies Tab for Cluster and Policies Tab for Local Cache presenting Default Priority configuration option.
See Also
Using Cache Dependency | Expiring Cached Items | Using Bulk Operations | Using Data Grouping


Topic: Group/Subgroup

Data Grouping

NOTE: This feature is not available in NCache Express and Professional edition.
Data grouping is a way to manage related objects in logical 'groups'. Every object being added in the cache can be tagged with a group identifier. Objects with same group identifier logically belong to the same group and can be identified by group identifier. The current version of NCache supports only two levels of grouping, a top level group and then its sub-groups.
For using Data Groups include the following namespace in your application:
using Alachisoft.NCache.Web.Caching;
using System.Collections;
Adding an item to a Data Group
The following code adds an item to data group 'sub-zero' inside group 'zero'.
Cache _cache = NCache.InitializeCache("mycache");
object item = "value" ;
_cache.Add("Customer:David:1001", item, "zero", "sub-zero");
Updating an item in a Data Group
The following code updates an item in data group 'sub-zero' inside group 'zero'.
Cache _cache = NCache.InitializeCache("mycache");
object item= "value1" ;
_cache.Insert("Customer:David:1001", item, "zero", "sub-zero");
Retrieving list of Data Group Keys
The following code retrieves list of items included in group 'zero'.
Cache _cache = NCache.InitializeCache("mycache");
ArrayList keys = _cache.GetGroupKeys("zero", null); sys.collection
foreach ( object obj in keys)
Console.WriteLine(obj);
Emptying a Data Group
The following code removes all items from data group 'sub-zero' inside group 'zero'.
Cache _cache = NCache.InitializeCache("mycache");
_cache.RemoveGroupData("zero", "sub-zero");
See Also
Adding Items to the Cache | Deleting Items from the Cache | Getting notified when an item is removed


Topic: Tags

Tags

NOTE: This feature is not available in NCache Express edition.
NCache provides you the facility of Tags which acts as an identifying mark for the cache items. Through tags, user can associate keywords(s) with cache objects. Moreover, user can get and remove items from the cache by tags.
Include the following namespace in your project before using Tags:
using Alachisoft.NCache.Runtime.Caching;
Initialize cache and tags:
Cache _cache = NCache.InitializeCache("mycache");
_cache.Clear();
Object valueToStore = "Can contain any type";
Tag [] tagList = new Tag [2];
tagList[0] = new Tag ("myTag1");
tagList[1] = new Tag ("myTag2");
Add items to cache containing tags:
_cache.Add("x-y-z", valueToStore, tagList);
Get Keys from cache containing tag:
ICollection keys = _cache.GetKeysByTag(tagList[0]);
ICollection keys = _cache.GetKeysByAnyTag(tagList);
ICollection keys = _cache.GetKeysByAllTags(tagList);
Get items from cache containing tag:
Hashtable ht = _cache.GetByTag(tagList[0]);
Hashtable ht = _cache.GetByAllTags(tagList);
Hashtable ht = _cache.GetByAnyTag(tagList);
Remove items from cache containing tag:
_cache.RemoveByTag(new Tag("myTag1"));
_cache.RemoveByAllTags(new Tag[] { new Tag("myTag1"), new Tag("myTag2") });
_cache.RemoveByAnyTag(new Tag[] { new Tag("myTag1"), new Tag("myTag2") });
Using Query string for searching Cache items with respect to Tags:
object valueToStore = "Can contain any type";
Tag [] tagList = new Tag [2];
tagList[0] = new Tag ("myTag1");
tagList[1] = new Tag ("myTag2");
// Add items to cache containing tags
_cache.Add("x-y-z", valueToStore, tagList);
Hashtable queryValue = new Hashtable();
ArrayList queryTagList = new ArrayList();
queryTagList.Add("myTag1");
queryTagList.Add("myTag2");
queryValue.Add("$Tag$", queryTagList);
// Query string, for searching Cache items with respect to Tags, should be specific to the following
_cache.Search("SELECT System.String WHERE this.$Tag$=? AND this.$Tag$=?", queryValue);
See Also
Adding items with priority settings | Using Bulk Operations | Using Data Grouping


Topic: Named Tags

Named Tags

NOTE: This feature is not available in NCache Express edition.
NCache is providing feature “Named Tags” through which user will be able to associate one or more keywords with cache items. These keywords will act as an identifying mark for the cache items and will be used for querying the cache data.
"Named Tags" is the enhancement of "Tags". Consider a scenario where user needs to store an object in textual form such as "xml", he will not be able to search that object using tags. The limitation of tags is that it can only have text values and only one attribute i.e. $Tag$. With named tags user will be able to store additional information (of any type) required to query the object stored as string.
Here users are required to provide the list of named tags, each having two parameters, "key" (name of a tag) as string and "value" (assigned value) as any primitive type. NCache then allows you to search your objects through these named tags.
“NamedTagsDictionary” class will be used to define Named Tags which will be added with the cache items for further use. Only string is allowed as a Named Tag “keys” and primitive data types are allowed as valid Named Tag “values”.
To use the Named Tags, include the following namespace in your project:
using Alachisoft.NCache.Runtime.Caching;
Initialize cache and Named Tags:
Cache _cache = NCache.InitializeCache("mycache");
_cache.Clear();
NamedTagsDictionary nameTag1 = new NamedTagsDictionary();
nameTag1.Add("Name", "Alex");
nameTag1.Add("Age", 25);
nameTag1.Add("Salary", 10000.50);
Add item to cache with Named Tags:
_cache.Add("key-1", "Customer", nameTag1);
Insert item to cache with Named Tags:
_cache.Insert("key-1", "Employee", nameTag1);
Using Query string for searching cache items with respect to Named Tags:
string queryString = "SELECT $Text$ WHERE this.Age = ? AND this.Name = ? AND this.Salary = ?";
Hashtable values = new Hashtable();
values.Add("Age", 10);
values.Add("Name", "Alex");
values.Add("Salary", 10000.25);
IDictionary dict = _cache.SearchEntries(queryString, values);
if (dict.Count > 0)
{
IDictionaryEnumerator ide = dict.GetEnumerator();
while (ide.MoveNext())
{
String key = (String)ide.Key;
Person prs = (Person)ide.Value;
HandlePerson(prs);
Console.WriteLine("Key = {0}, Age: {1}", key, prs.Age);
}
}
Note:
Here $Text$ represents the textual data in a cache. If Named Tags are associated with some string value then this syntax can be used in queries. $Text$ is independent of client and can return values added by both .Net and Java clients. If Named Tags are associated with “int” or any other data type then specific syntax to that type will be used. For example for "int" data type System.Int32 will be used to query Named Tags.
See Also
Adding items with priority settings | Using Bulk Operations | Using Data Grouping


Topic: Locking Cached Items

Locking Cached Items

Locking prevents multiple clients from updating the same data simultaneously and also ensures data consistency. A proper locking mechanism is necessary to ensure data consistency when there is a possibility of multiple clients accessing and possibly modifying the same data at the same time.
NCache provides an exclusive lock mechanism where once a client request acquires a lock for a particular data item, it blocks the access for that item to every other client until the lock is released. Locks can also be forcefully released. A lockId and lockdate is associated with every locked item and are verified every time a locked item is accessed.
Following are the methods that can be used to implement locking in an application. For using locking include the following namespace in your application:
using Alachisoft.NCache.Web.Caching;
Method Name | Parameters | Description
Get | string key, Timespan lockTimeout, ref lockHandle lockHandle, bool acquireLock | Gets cached item and can also acquire lock on it if value of acquireLock parameter is set to true. key is a key of item to get. lockTimeout is time span after which the lock will be released automatically. lockHandle is an object of the lockHandle class which contains all information about the lock. acquireLock determines whether to acquire lock or not. Cache _cache = NCache.InitializeCache("mycache"); // Acquires lock for specified time LockHandle lockHandle = new LockHandle(); Object lockedItem = _cache.Get("key", new TimeSpan(0, 0, 5), ref lockHandle, true);
Insert | string key, CacheItem item, lockHandle lockHandle, bool releaseLock | Inserts an item in cache and can also release a lock if item was locked. key is a key of item to insert. item is a an item to insert in cache. lockHandle is an object of the lockHandle class which contains all information about the lock. releaseLock determines whether to release a lock or not on successful insert. Cache _cache = NCache.InitializeCache("mycache"); LockHandle lockHandle = new LockHandle(); CacheItem cItem = new CacheItem ("my Item"); CacheItemVersion lockedItem = _cache.Insert("key", cItem, lockHandle, true);
Remove | string key, lockHandle lockHandle | Removes an item from cache. key is a key of item to release lock. lockHandle is an object of the lockHandle class which contains all information about the lock. Cache _cache = NCache.InitializeCache("mycache"); LockHandle lockHandle = new LockHandle (); _cache.Remove("key", lockHandle);
Lock | string key, Timespan lockTimeout, out lockHandle lockHandle | Locks cached item. key is a key of item to acquire a lock. lockTimeout is time span after which the lock will be released automatically. lockHandle is an object of the lockHandle class which contains all information about the lock. Cache _cache = NCache.InitializeCache("mycache"); // Acquires lock for specified time LockHandle lockHandle = new LockHandle (); _cache.Lock("key", new TimeSpan (0, 0, 5), out lockHandle);
UnLock | string key | Forcefully unlocks the cached item. key is a key of item to release lock. Cache _cache = NCache.InitializeCache("mycache"); _cache.Unlock("key");
UnLock | string key, lockHandle lockHandle | Unlocks the cached item. key is a key of item to release lock. lockHandle is an object of the lockHandle class which contains all the information about lock. Cache _cache = NCache.InitializeCache("mycache"); LockHandle lockHandle = new LockHandle(); _cache.Unlock("key", lockHandle);
NCache will ignore the locks if other overloads of Get, Insert and Remove methods are called.
See Also
Initialize Cache | Adding Items | Finding items | Removing Items | Dispose Cache | Start Cache | Stop Cache


Topic: Cache Item Version

Cache Item Version

CacheItem Version is a property associated with every cache item. It is basically a numeric value that is used to represent the version of cached item which changes with every update to an item. This property allows you to track whether any changes occurred or not.
NCache first reads item version before updating it. It will update only if the item version is same i.e. only latest version is stored in the cache. As clusters are of distributed nature, so there could be a possibility that some cache clients might not have updated copy of item. So for concurrency reasons CacheItemVersion class is very important to be implemented. Following are the steps to use cache item version:
  1. Include the following namespace in your application.
    using Alachisoft.NCache.Web.Caching;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    [Serializable]
    class Customer
    {
    ...
    }
  4. Now insert the following code in the 'Main' of the project.
Cache _cache = NCache.InitializeCache("mycache");
_cache.Clear();
Customer customer = new Customer();
customer.name = "David";
customer.customerID = 1001;
customer.OrderPlaced = "C-11";
customer.City = "New York";
CacheItem cItem = new CacheItem(customer);
//Add Item to Cache
CacheItemVersion version1 = _cache.Add("Customer:David:1001", cItem);
// Update the Cache Item, to change the CacheItemVersion
customer.name = "David";
customer.customerID = 1001;
customer.OrderPlaced = "C-11";
customer.City = "London";
GetIfNewer:
Here is how you can retrieve items from the cache
//Update Cache Item Version
CacheItemVersion version2 = _cache.Insert("Customer:David:1001", cItem);
Object obj = _cache.GetIfNewer("Customer:David:1001", ref version1);
if (obj == null)
{
Console.WriteLine("Value not updated");
}
else
{
Console.WriteLine("Current Version of Customer:David:1001 is:"+version1.Version.ToString());
}
Remove:
Here is how you can remove items from the cache.
//Update Cache Item Version
CacheItemVersion version3 = _cache.Insert("Customer:David:1001", cItem);
//Remove only if the local Client has the latest Version
Object objGet = _cache.Remove("Customer:David:1001", version3);
if (objGet == null)
{
Console.WriteLine("Item not removed from the cache. Newer Version of Item exists");
}
else
{
Console.WriteLine("Item Removed from the cache");
}
Update:
Here is how you can get the latest items from the cache.
//Update Cache Item Version
CacheItemVersion version4 = cache.Insert("Customer:David:1001", cItem);
//Get only if the local Client has the latest Version
Object objGet = _cache.Get("Customer:David:1001", ref version1);
if (objGet == null)
{
Console.WriteLine("Item version updated");
}
else
{
Console.WriteLine("Value not updated");
}
5. Start the Local Cache 'myCache'.
6. Run the project.
See Also
Initialize Cache | Adding Items | Finding items | Removing Items | Dispose Cache | Start Cache | Stop Cache


Topic: Streaming API

Streaming API

NCache API now allows you to read and write binary data stream in the cache. NCache has implemented a CacheStream which is derived from the standard Stream and provides major functionality of streaming in NCache. However, it does not support 'seeking' which is the querying and modifying of the current position within a stream.
Streaming can be used with the following namespace:
using Alachisoft.NCache.Web.Caching;
using System.IO;
Stream Modes:
Stream works in two modes:
CacheStream Reader:
Read mode can either be acquired with lock or without lock. In read with lock mode, multiple read operations can be performed simultaneously on a stream but no write operation is allowed in this mode. While in read without lock, write operations can be done parallel to read operations.
  • Stream Read: (With Lock): Multiple read operations can be performed on a stream, no write operation is allowed in this mode. CacheStream Reader class will throw an exception if stream is already in use by other application.
    CacheStream stream = _cache.GetCacheStream(key, StreamMode.Read);
    stream.Read(readBuffer, 0, readBuffer.Length);
    stream.Close();
  • Stream Read: (Without Lock): Multiple read and write operations can be performed on a stream.
    stream = _cache.GetCacheStream(key, StreamMode.ReadWithoutLock);
    stream.Read(readBuffer, 0, readBuffer.Length);
    stream.Close();
CacheStream Writer:
In write mode only single write operation can be performed on a stream. No read operation is allowed in this mode. CacheStream Writer class will throw an exception if stream is already in use by other application.
stream = _cache.GetCacheStream(key, StreamMode.Write);
stream.Write(writeBuffer, 0, writeBuffer.Length);
stream.Close();
Stream Close:
After using the stream in any mode, users are supposed to close the stream in order to release the lock.
Buffered Stream:
Cache stream directly reads and writes data from the cache. It directly calls cache for both operations which thereby increases the calls to the cache and reduces the performance of an application. To overcome the above issue NCache introduces the Buffer stream. Buffer stream is the set of bytes used for storing the data up to the certain limit before reading or writing it to the cache. Until the buffer reaches its maximum limit the data will not be read or write from/to the cache. Buffer stream reads or writes a chunk of data to the cache in a single call which reduces the number of calls to the cache. This chunk will be equal to the buffer size. Buffer size varies according to the requirement of application. Following code shows how to GetBufferedStream:
Stream wstream = _cache.GetCacheStream(key, StreamMode.Write).GetBufferedStream(1000);
wstream.Write(writeBuffer, 0, 200);
wstream.Write(writeBuffer, 200, 600);
wstream.Write(writeBuffer, 600, 1000);
wstream.Close();
See Also
Using Cache Dependency | Adding items with priority settings | Using Bulk Operations | Using Data Grouping


Topic: Bulk Operations

Bulk Operations

NOTE: This feature is not available in NCache Express and Professional edition.
Where normal add, insert and remove methods let you work with single key-value pairs, bulk operations let you add, update or remove a collection of key-value pairs in a single method call. The idea behind bulk operations is to minimize the cluster traffic by bundling multiple operations into a single call. This is handy if you want to work with collection of items.
Note: Here users are supposed to provide unique keys for all bulk operations.
  1. Include the following namespace in your application.
    using Alachisoft.NCache.Web.Caching;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    [Serializable]
    class Customer
    {
    ...
    }
  4. Now insert the following code in the 'Main' of the project:
    For Adding Collection of Items
    Cache _cache = NCache.InitializeCache( "mycache" );
    _cache.Clear();
    Customer customer = new Customer ();
    customer.name = "David" ;
    customer.customerID = 1001;
    customer.City = "London" ;
    customer.ContactNumber = "+44-xxx-xxxx-xxxx" ;
    customer.IsOrderInProcess = true ;
    Customer customer1 = new Customer ();
    customer1.name = "Alex" ;
    customer1.customerID = 1002;
    customer1.City = "Chicago" ;
    customer1.ContactNumber = "+44-xxx-xxxx-xxxx" ;
    customer1.IsOrderInProcess = false ;
    string [] keys = new string [] { "Customer:David:1001" , "Customer:Alex:1002" };
    CacheItem [] items = new CacheItem [2];
    items[0] = new CacheItem (customer);
    items[1] = new CacheItem (customer1);
    //Add items to cache in Bulk
    _cache.AddBulk(keys, items, DSWriteOption.None, null );
    For Retrieving Collection of Items
    //Get items from cache in Bulk
    IDictionary objectRecieved = _cache.GetBulk(keys, DSReadOption.None);
    IEnumerator iter = objectRecieved.Values.GetEnumerator();
    while (iter.MoveNext())
    {
    Customer customerInformation = (Customer)iter.Current;
    Console.WriteLine("Customer ID: " + customerInformation.customerID);
    Console.WriteLine("Name: " + customerInformation.name);
    Console.WriteLine("City: " + customerInformation.City);
    Console.WriteLine("Contact Number: " + customerInformation.ContactNumber);
    Console.WriteLine("Order placed: " + customerInformation.IsOrderInProcess);
    Console.WriteLine();
    }
    For Updating Collection of Items
    //Insert Bulk
    _cache.InsertBulk(keys, items, DSWriteOption.None, null);
    //Get items from cache in Bulk
    IDictionary objectRecieved = _cache.GetBulk(keys, DSReadOption.None);
    IEnumerator iter = objectRecieved.Values.GetEnumerator();
    while (iter.MoveNext())
    {
    Customer customerInformation = (Customer)iter.Current;
    Console.WriteLine("Customer ID: " + customerInformation.customerID);
    Console.WriteLine("Name: " + customerInformation.name);
    Console.WriteLine("City: " + customerInformation.City);
    Console.WriteLine("Contact Number: " + customerInformation.ContactNumber);
    Console.WriteLine("Order placed: " + customerInformation.IsOrderInProcess);
    Console.WriteLine();
    }
    For Removing Collection of Items
    //Remove items from cache in Bulk
    IDictionary removedRecieved = _cache.RemoveBulk(keys, DSWriteOption.None, null);
    IEnumerator iter = removedRecieved.Values.GetEnumerator();
    while (iter.MoveNext())
    {
    Customer customerInformation = (Customer)iter.Current;
    Console.WriteLine("Customer ID: " + customerInformation.customerID);
    Console.WriteLine("Name: " + customerInformation.name);
    Console.WriteLine("City: " + customerInformation.City);
    Console.WriteLine("Contact Number: " + customerInformation.ContactNumber);
    Console.WriteLine("Order placed: " + customerInformation.IsOrderInProcess);
    Console.WriteLine();
    }
    For Deleting Collection of Items
    The following code deletes a collection of items from the cache. This API performs the same functionality as "RemoveBulk" but it does not return any value.
    //Delete items from cache in Bulk
    _cache.DeleteBulk(keys, DSWriteOption.None, null);
  5. Start the Local Cache 'myCache'.
  6. Run the project.
See Also
Adding Items to the Cache | Deleting Items from the Cache | Getting notified when an item is removed


Topic: Async Operations

Async Operations

NCache now offers Asynchronous cache operations, so that maximum performance can be achieved. Following are the simple coding examples implementing Async operations:
  1. Include the following namespace in your application.
    using Alachisoft.NCache.Web.Caching;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    [Serializable]
    class Customer
    {
    ...
    }
  4. Now insert the following code in the 'Main' of the project:
    Cache _cache = NCache.InitializeCache("mycache");
    _cache.Clear();
    Customer customer = new Customer ();
    customer.name = "David" ;
    customer.customerID = 1001;
    customer.City = "London" ;
    customer.ContactNumber = "+44-xxx-xxxx-xxxx" ;
    customer.IsOrderInProcess = true ;
    For Adding item in a cache asynchronously
    // Add Item to Cache asynchronously
    _cache.AddAsync("Customer:David:1001" , new CacheItem (customer), DSWriteOption.None, null);
    Thread.Sleep(1000);
    Object objectCustomer = _cache.Get("Customer:David:1001");
    Customer customerInformation = (Customer)objectCustomer;
    Console.WriteLine("Customer ID: " + customerInformation.customerID);
    Console.WriteLine("Name: " + customerInformation.name);
    Console.WriteLine("City: " + customerInformation.City);
    Console.WriteLine("Contact Number: " + customerInformation.ContactNumber);
    Console.WriteLine("Order placed: " + customerInformation.IsOrderInProcess);
    For Updating item in a cache asynchronously
    // Add Item to Cache asynchronously
    _cache.InsertAsync("Customer:David:1001", new CacheItem(customer), DSWriteOption.None, null);
    Thread.Sleep(1000);
    Object objectCustomer = _cache.Get("Customer:David:1001");
    Customer customerInformation = (Customer)objectCustomer;
    Console .WriteLine("Customer ID: " + customerInformation.customerID);
    Console .WriteLine("Name: " + customerInformation.name);
    Console .WriteLine("City: " + customerInformation.City);
    Console .WriteLine("Contact Number: " + customerInformation.ContactNumber);
    Console .WriteLine("Order placed: " + customerInformation.IsOrderInProcess);
    For Removing item from a cache asynchronously
    // Remove Item from Cache asynchronously
    _cache.RemoveAsync("Customer:David:1001", null, DSWriteOption.None, null);
    For Clearing cache asynchronously
    // Clears Cache asynchronously
    _cache.ClearAsync(DSWriteOption.None, null, null);
  5. Start the Local Cache 'myCache'.
  6. Run the project.
See Also
Adding items with priority settings | Using Bulk Operations | Using Data Grouping


Topic: Resync Expired Items

Resync Expired Items

The expired items of the cache are required to be reloaded from the main data source. The idea of Resync Expired Items is that, instead of removing items from the cache, they are placed in a queue, awaiting to be automatically reloaded from the main data source when updated. An obsolete expired item is moved to the top of the queue for immediate updating when accessed. This ensures providing of updated data to the user. With Resync Expired Items enabled, no item expires ever unless it is removed from the data source. Hence, automatic synchronization with the master data source occurs. For Resync Expired Items, Read Through cache must be enabled and include the following namespace in your application:
using Alachisoft.NCache.Web.Caching;
While adding items to the cache, Resync Expired Items needs to be enabled for individual items. For reference, see the code below:
CacheItem item = new CacheItem (customer);
item.SlidingExpiration = new TimeSpan (0, 0, 30);
item.IsResyncExpiredItems = true ; //Resync Expired Items is enabled.
Cache _cache = NCache.InitializeCache( "myCache" );
_cache.Insert(customer.CustomerID, item);
See Also
Using Read-Through & Write-Through caching


Topic: Performing Cache Operations in Secured Environment

Performing Cache Operations in Secured Environment

If security is enabled, only authorized user can perform cache operations, provided those users exist under given domain in LDAP. Login credentials are required to belong to any WINDOWS Server, hosting the user login and running Active Directory services. User can give credential information in overloaded API's or in client.ncconf file. Now security parameters travel in the encrypted form. This feature can be used with the following namespace:
using Alachisoft.NCache.Web.Caching;
Providing credentials in API
For API'sInitializeCache, StartCache and StopCache, there are overloads that accept User ID and Password as parameters. They are then sent to the server for authentication and authorization.
// Initialize the cache.
NCache.InitializeCache("myReplicatedCache", new Alachisoft.NCache.Web.Security.SecurityParams ("john", "john123" ), new Alachisoft.NCache.Web.Security.SecurityParams ("sam", "sam123" ));
Note: Alachisoft.NCache.Web.Security.SecurityParams is an information holder class for User IDs and Passwords. The first SecurityParam is for primaryUserCredentials and second is for secondaryUserCredentials. InitializeCache
call either returns a cache instance after which user can perform cache operations on it or it throws the following exception.
Alachisoft.NCache.Runtime.Exceptions.SecurityException.
See Also
Security | Configuring Security | Admin level Security | User Level Security | Browsing Domain Users


Topic: Cache Dependency

Cache Dependency

Caching can depend on several items which includes file, database table rows, query strings, and also other cached items. If you add an item to the Cache with a dependency, when the dependency changes, the item is automatically removed from the cache. You can add items with dependencies to your application's cache with the Add and Insert methods.
In This Section
Using Key Dependency
Explains way to associate one cached item with another item in a cache.
Using File Dependency
Describes how to set the validity of a cache item based on an external file/files.
Using Aggregate Dependency
Describes how to set the aggregate dependency for a cache item.
Using Custom Dependency
Depicts how you can use custom dependencies by defining your own expiration logics.
Using CacheSyncDependency
Illustrates ways to synchronize two caches.
Using SqlCacheDependency
Represents keeping the cached items synchronized with the SQL database.
Using Oracle Dependency
Represents keeping the cached items synchronized with the Oracle database.
Using OLEDB Dependency
Explains how you can maintain the cached items synchronized with any of the database.
Enabling Database Cache Dependency in NHiberate
Gives steps to enable SqlCacheDependency and DbCacheDependency in NHiberate.
Using Database Dependencies with CAB
Explains how to create DB dependencies with Caching application block.
See Also
Expiring cached items
Describes how certain cached items can be automatically removed from the cache when required.
Adding items with priority settings
Explains adding items in the cache with priority settings.
Using Bulk Operations
Describes performing bulk operations to add, insert or remove collection of items in a single method call. It helps speeding up the process and minimizes cluster traffic.
Using Data Grouping
Presents distributing related objects in 'logical' groups.
Performing cache operations in secured environment
Describes procedure of performing cache operations when security is enabled for NCache.


Topic: Key Dependency

Key Dependency

NOTE: This feature is not available in NCache Express edition.
Key based dependency associates one cached item with another item in the cache. It invalidates the dependent item when that particular item changes. Whenever that item is removed or updated from the cache, associated object will be expired. Key based dependency is cascaded. For example, if key1 depends on key2, key2 depends on key3 and key3 depends on key4, then removal of key4 will result in expiration of key1, key2 and key3. It is not clean interval dependent.
Add the following namespaces in your project:
using Alachisoft.NCache.Web.Caching;
using Alachisoft.NCache.Runtime;
using Alachisoft.NCache.Runtime.Dependencies;
The following code explains the implementation.
Cache _cache = NCache.InitializeCache("mycache");
_cache.Add("Key-1", "Key Value");
String[] cacheKeys = new String[1];
cacheKeys[0] = "Key-1";
//Adding cache item "Key-2" dependant on another cache item.
_cache.Add("Key-2", "dependant item", new KeyDependency(cacheKeys), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal);
//Removing/Deleting/Updating key: "Key-1" will automatically make all of its dependant keys removed, here it's "Key-2"
Console.WriteLine("Removing Key-1");
Object removedObject = _cache.Remove("Key-1");
Console.WriteLine("value /" + removedObject.ToString() + "/ removed");
if (_cache.Contains("Key-2"))
{
Console.WriteLine("ERROR: cache Key: key-2 not removed,/n Please read Help from NCache for further details or contact support@alachisoft.com");
}
else
{
Console.WriteLine("Cache Key: Key-2 does not exist, item removed once the base key was removed from Cache");
}
See Also
Using File Dependency | Using Custom Dependency | Using CacheSyncDependency | Using SqlCacheDependency | Using DbCacheDependency


Topic: File Dependency

File Dependency

We can set the validity of the cache item based on an external file(s). When this resource changes, the cached object becomes obsolete and is removed from the cache. In FileDependency object, a File/Directory path is provided. Cache object also expires if the path is used to create a new File/Directory.
The following steps demonstrate how to use file based dependency.
Add the following namespaces in your project:
using Alachisoft.NCache.Web.Caching;
using Alachisoft.NCache.Runtime;
using Alachisoft.NCache.Runtime.Dependencies;
The following code explains the implementation.
Cache _cache = NCache.InitializeCache("mycache");
_cache.Clear();
//Adding cache item "dependantItemOnFile" dependant on file C:/NCache.txt
_cache.Add("dependantItemOnFile", "dependant", new FileDependency("C://NCache.txt"), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal);
if (_cache.Contains("dependantItemOnFile"))
{
Console.WriteLine("Cache Key: dependantItemOnFile exists");
}
//Wait for file removal, deletion or modification to show File based dependency
Console.WriteLine("Remove/Rename/Modify file C://NCache.txt Press Enter when done");
Console.ReadKey();
if (_cache.Contains("dependantItemOnFile"))
{
Console.WriteLine("ERROR: Cache Key: dependantItemOnFile not removed,Please read Help from NCache for further details or contact support@alachisoft.com");
}
else
{
Console.WriteLine("Cache Key: dependantItemOnFile does not exist, item removed since the file C://NCache.txt was either Removed, Renamed or Modified");
}
See Also
Using Key Dependency | Using Custom Dependency | Using CacheSyncDependency | Using SqlCacheDependency | Using DbCacheDependency


Topic: Aggregate Dependency

Aggregate Dependency

NOTE: This feature is not available in NCache Express and Professional edition.
Aggregate Cache Dependency associates one cached item with a collection of dependency objects which can be CacheDependency objects, DBCacheDependency objects or any combination of these. The AggregateCacheDependency monitors a collection of dependency objects so that when any of them changes, the cached object becomes obsolete and is removed from the cache.
Aggregate Cache Dependency allows you to associate multiple dependencies of different types with a single cached item. For example, you can associate key dependency and file dependency with an item using aggregate dependency by creating an instance of the AggregateCacheDependency class with each dependency added to it. You can then use a single Insert call to make the item dependent on the AggregateCacheDependency instance.
Add the following namespaces in your project:
using Alachisoft.NCache.Web.Caching;
using Alachisoft.NCache.Runtime;
using Alachisoft.NCache.Runtime.Dependencies;
The following code explains the implementation.
Cache _cache = NCache.InitializeCache("mycache");
_cache.Clear();
Customer customer = new Customer();
customer.name = "David";
customer.customerID = 1001;
CacheItem cItem = new CacheItem(customer);
//Adding a key to create Dependency on
_cache.Add("Customer:David:1001", cItem);
//Customer Steve is dependant on David
customer = new Customer();
customer.name = "Steve";
customer.customerID = 1002;
//Initializing Aggregate Dependency; CacheItem dependant on File and Key
AggregateCacheDependency aggregateDependency = new AggregateCacheDependency();
aggregateDependency.Dependencies.Add(new FileDependency("C:\\customer.config"));
aggregateDependency.Dependencies.Add(new KeyDependency("Customer:David:1001"));
cItem = new CacheItem(customer);
cItem.Dependency = aggregateDependency;
_cache.Add("Customer:Steve:1002", cItem);
//Updating Key Customer:David:1001
customer = new Customer();
customer.name = "David";
customer.customerID = 1001;
cItem = new CacheItem(customer);
_cache.Insert("Customer:David:1001", cItem);
//Key will be removed since it's dependent Key has been updated
if (!_cache.Contains("Customer:Steve:1002"))
{
Console.WriteLine("Cache Key: Customer:Steve:1002 does not exist, item removed once the base key or file is removed/deleted/updated from Cache");
}
else
{
Console.WriteLine("ERROR: cache Key: Customer:Steve:1002 not removed,/n Please read Help from NCache for further details or contact support@alachisoft.com");
}
See Also
Using File Dependency | Using Custom Dependency | Using CacheSyncDependency | Using SqlCacheDependency | Using DbCacheDependency


Topic: Custom Dependency

Custom Dependency

NOTE: This feature is not available in NCache Express and Professional edition.
You can have your own custom dependencies. In this way, you can expire items from the cache in a number of flexible ways where your own expiration logic meets your business requirements. NCache provides an abstract class ExtensibleDependency that is the base for all the dependencies. All you need to do is to inherit your dependency class from this class and override its HasChanged property. The following sample code creates a new dependency. The dependency polls the Northwind database and expires all the Products for which units in stock are less than 100.
Include the following namespaces in your application:
using Alachisoft.NCache.Runtime.Dependencies;
using Alachisoft.NCache.Web.Caching;
[Serializable]
public class CustomDependency : ExtensibleDependency
{
private string _connString;
private int _productID;
public override bool Initialize() { return false; }
public CustomDependency(int productID, string connString)
{
_connString = connString;
_productID = productID;
}
internal bool DetermineExpiration()
{
if (GetAvailableUnits(_productID) < 100)
return true;
return false;
}
internal int GetAvailableUnits(int productID)
{
OleDbDataReader reader = null;
OleDbConnection connection = new OleDbConnection(_connString);
connection.Open();
int availableUnits = -1;
try
{
OleDbCommand cmd = connection.CreateCommand();
cmd.CommandText = String.Format(CultureInfo.InvariantCulture,
"Select UnitsInStock From Products" +
" where ProductID = {0}", productID);
reader = cmd.ExecuteReader();
if (reader.Read())
{
availableUnits = Convert.ToInt32(reader["UnitsInStock"].ToString());
}
reader.Close();
return availableUnits;
}
catch (Exception)
{
return availableUnits;
}
}
public override bool HasChanged
{
get
{
return DetermineExpiration();
}
}
}
Here is how CustomDependency will be used:
Cache _cache = NCache.InitializeCache("mycache");
string connString = "Provider=SQLOLEDB.1;Data Source=localhost;User ID=sa;password=;Initial Catalog=Northwind";
CustomDependency hint = new CustomDependency(123, connString);
_cache.Add("myKey", "myVal", new CacheDependency(hint), Cache.NoAbsoluteExpiration, new TimeSpan(0,0,10), CacheItemPriority.High);
See Also
Using Key Dependency | Using File Dependency | Using CacheSyncDependency | Using SqlCacheDependency | Using DbCacheDependency


Topic: SQL Cache Dependency

SQL Yukon Dependency

NOTE: This feature is not available in NCache Express and Professional edition.
While working with databases in a multiuser environment, updates in the databases are very frequent. When cache is involved, you need to keep cached items synchronized with the database. One possible solution is that, on every update, database itself notifies the cache and cache expires the out of synch items. Sql Yukon Dependency is provided by NCache for this purpose. Item expires if result of the command (based on command text) changes. SQLYukonDependency is only available in NCache CLR 2.0 and requires SQL Server 2005 or above.
Following is the step-by-step guide for using SQLCacheDependency.
Enabling Database Notification:
Enable the service broker in SQL Server 2005 or above before NCache can use SqlCacheDependency. This allows SQL Server 2005 to send event notifications to NCache to let it know that data has changed in the database.
[SQL]
ALTER DATABASE Northwind SET ENABLE_BROKER;
GO
To verify that the broker is running you can check properties in the databaseserver using SQL Management studio or run the following query:
select is_broker_enabled from sys.databases where name = '<dbname>'
Make sure that you get "1" for the database you intend to use.
Database Permissions :
If you are not a database owner (dbo) then please enable following permissions in order to use NCache SQL cache dependency. Database permissions are defined for two different modes: Default mode and Custom mode. In Default mode SQLDependency will create the SQL Service and Queue at run time. Custom mode is used by those clients who want to use SQLDependency without Service and Queue creation rights. In this case SQLDependency will not create the SQL Service and Queue at run time and clients are supposed to create it for each NCache process.
For Default Mode:
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO <database_principal>
GRANT CREATE QUEUE TO <database_principal>
GRANT CREATE SERVICE TO <database_principal>
GRANT CREATE PROCEDURE TO <database_principal>
For Custom Mode:
CREATE QUEUE "NCacheSQLQueue-[IP-Address]";
CREATE SERVICE "NCacheSQLService-[IP-Address]"
ON QUEUE "NCacheSQLQueue-[IP-Address]"
([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]);
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO [User Name];
GRANT RECEIVE ON "NCacheSQLQueue-[IP-Address]" TO [User Name];
GRANT RECEIVE ON QueryNotificationErrorsQueue TO [User Name] ;
GRANT SEND ON SERVICE :: "NCacheSQLService-[IP-Address]" to [User Name] ;
Note:
  • Replace [IP-Address] with node ip address and [User Name] with database user name.
  • In a clustered environment, users are supposed to create SQL Service and Queue per NCache process.
  • You can also create required SQL Service and Queue using script "NCacheServiceQueue.sql" located at "%Install Directory%/NCache/bin/resources".
Using Dependency:
  1. Create a .Net test application.
  2. Add the following namespaces in your project:
    using Alachisoft.NCache.Web.Caching;
    using Alachisoft.NCache.Runtime.Dependencies;
    using Alachisoft.NCache.Runtime;
  3. Declare a variable "_cache" in the code and initialize it with "sqlDependencyCache", and clear it if this cache was used previously.
    Cache _cache = NCache.InitializeCache("sqlDependencyCache");
    _cache.Clear();
  4. Create a String "connectionString" containing information to connect with SQL database e.g.
    String connectionString = "Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;";
  5. Create a dependency and add it to the cache.
    CacheDependency sqlSync = new SqlCacheDependency(connectionString, "SELECT ProductID FROM dbo.Products WHERE ProductID = 006");
    _cache.Insert("ProductID:006", "my Item", sqlSync, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal);
  6. Now update the key "6" of the Database table using the following SQL command.
    [SQL]
    UPDATE Products SET ProductName = 'Modified Product' WHERE ProductID =6
  7. This invalidates cacheKey Dependant-ProductID6 " and is removed by NCache.
    Note : If SQL Server goes down/restarts, all dependencies become invalid and are removed from the cache .
See Also
Using DbCacheDependency


Topic: Oracle Cache Dependency

Oracle Cache Dependency

NOTE: This feature is not available in NCache Express and Professional edition.
While working with databases in a multiuser environment, updates in the databases are very frequent. When cache is involved, you need to keep cached items synchronized with the database. One possible solution is that, on every update, database itself notifies the cache and cache expires the out of synch items. Oracle Dependency is provided by NCache for this purpose. Item expires if result of the command (based on command text) changes. Oracle Dependency is only available for Oracle database 10g release 2 or later. Also make sure that Oracle Data Providers for .NET (version 10.1.0.2.0 or later) is installed.
Following is the step-by-step guide for using OracleCacheDependency.
Enabling Database Notification:
Grant CHANGE NOTIFICATION privilege to the user to create a notification registration. Following statement grants the CHANGE NOTIFICATION privilege to the user.
[SQL]
"grant change notification to scott"
Using Dependency:
  1. Create a .Net test application.
  2. Add the following namespaces in your project:
    using Alachisoft.NCache.Web.Caching;
    using Alachisoft.NCache.Runtime.Dependencies;
    using Alachisoft.NCache.Runtime;
  3. Declare a variable "_cache" in the code and initialize it with "sqlDependencyCache", and clear it if this cache was used previously.
    Cache _cache = NCache.InitializeCache("oracleDependencyCache");
    _cache.Clear();
  4. Create a String "connectionString" containing information to connect with Oracle database e.g.
    String connectionString = "User Id=scott;Password=tiger;Data Source=oracle";
  5. Create a dependency and add it to the cache.
    CacheDependency orclSync = new OracleCacheDependency(connectionString, "SELECT CustomerID FROM Customers WHERE CustomerID = 006");
    _cache.Insert("Customer:David:006", "my Item", orclSync, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal);
  6. Now update the key "6" of the Database table using the following Oracle command.--[SQL]
    UPDATE Customers SET Customer Name = 'Modified Customer' WHERE CustomerID =6
  7. This invalidates cacheKey " Dependant-CustomerID6 " and is removed by NCache.
Note: In Oracle 10g, database change notifications are only object based. This means that change notifications will be fired if any row is modified in object. Therefore we have to check rowID to confirm if the row changed is the one for which the event is registered. RowID's cannot be retrieved unless explicitly included in query. Therefore customer has to include rowID in query that he/she is registering with OracleDependecy, otherwise change notification will be fired if any row is modified in table.
When rowID is included in query like: select rowID, productID, productname, unitprice from Products where ProductID = 220; NCache will save the rowID of rows for which change notification is registered. When it receives any change notification, NCache will compare the rowIDs to determine whether the row changed is the one for which the rowID is registered. Otherwise NCache will have no way to check this and items for which change notification is registered will be removed if any row in table changes.
In Oracle 11g both object based and query based (default) notifications are provided. In query based notifications; change of the modified row will be notified only if the change notification is registered for it.
See Also
Using DbCacheDependency


Topic: DBCache Dependency

DBCache Dependency

NOTE: This feature is not available in NCache Express and Professional edition.
DBCacheDependency is used to keep the cache items synchronized with any of the database. Prior to its use, you need to enable notifications for the underlying database. For details, see Enabling Notifications For SQL Server , Enabling Notifications For DB2 and Enabling Notifications For Oracle . This is a row based dependency. Cache key is associated with primary key value of the table. Thus an item expires only if the row with that primary key gets changed.
While using DBCacheDependency for SQL Server, you need to use 'Sql versions' of commands, connections, readers etc. available under 'System.Data.SqlClient' namespace in your client application. For Oracle and DB2, you need to use 'OleDb versions' of commands, connections, readers etc., available under 'System.Data.OleDb' namespace.
Following is the step-by-step guide for using DBCacheDependency. The example given is for SQL Server, however, Oracle and DB2 databases can also be used with little modifications.
  1. Enable Notifications for Products table in Northwind database. See Enabling Notifications For SQL Server .
  2. Create an ASP.NET Application inside Visual Studio.NET by the name DataCachingUsingNCache.
  3. Add a new Web Form named DataCacheSample.aspx to your project and include the following namespaces.
    using Alachisoft.NCache.Web.Caching;
    using Alachisoft.NCache.Runtime;
    using Alachisoft.NCache.Runtime.Dependencies;
  4. Add a nested class Product inside the code behind.
    [Serializable]
    class Product
    {
    .....
    }
  5. Declare a private variable "_cache" in the code behind of the DataCacheSample as.
    private Cache _cache;
  6. Add the following code in Page_Load event of the DataCacheSample as.
    protected void Page_Load( object sender, EventArgs e)
    {
    if (_cache == null ) { _cache = NCache.InitializeCache( "mycache" ); }
    }
  7. On the Design view tab for the Web Form, add a Web Form button to the DataCacheSample page. Change the ID property of this button to FetchFromDB, and then change the Text property to Fetch From Database.
  8. Add a second Web Form button. Change the ID property to FetchFromCache, and then change the Text property to Fetch From Cache.
  9. Add a Web Form label. Change the ID property to Status, and then clear the Text property.
  10. On the Design view tab, double-click the FetchFromDB button to open the FetchFromDB_Click event in the code-behind page.
  11. Add the following code to the FetchFromDB_Click event:
    protected void FetchFromDB_Click(object sender, System.EventArgs e)
    {
    string connectionString = "Data Source=local host; initial catalog=northwind;User ID = sa; password =;";
    string QueryString = "SELECT ProductID, ProductName, SupplierID, CategoryID, UnitPrice FROM dbo.Products where productid < 11";
    DataSet ds = new DataSet ();
    //Create the connection and pass in the ConnectionString
    SqlConnection mySqlConn = new SqlConnection(connectionString);
    SqlCommand sqlCmd = new SqlCommand(QueryString, mySqlConn);
    mySqlConn.Open();
    SqlDataReader sqlReader = sqlCmd.ExecuteReader();
    List <Product> products = new List <Product>();
    while (sqlReader.Read())
    {
    Product product = new Product();
    product.ProductID = sqlReader.GetInt32(0);
    product.ProductName = sqlReader.GetString(1);
    product.SupplierID = sqlReader.GetInt32(2);
    product.CategoryID = sqlReader.GetInt32(3);
    product.UnitPrice = sqlReader.GetDecimal(4);
    DBCacheDependency dependency = DBDependencyFactory.CreateSqlCacheDependency(connectionString,"Primary Key:dbo.Products");
    _cache.Insert(product.ProductID+":dbo.Products",product,dependency,
    Cache.NoAbsoluteExpiration,Cache.NoSlidingExpiration,Alachisoft.NCache.Runtime.CacheItemPriority.Default);
    products.Add(product);
    }
    //Set the DataGrid's DataSource to the "products" list
    DataGrid1.DataSource = products;
    mySqlConn.Close();
    //Display the status
    Status.Text = products.Count+ " products fetched from database.";
    DataGrid1.DataBind();
    }
  12. On the Design view tab for the DataCacheSample.aspx page, double-click the FetchFromCache button to open the FetchFromCache_Click event in the code-behind page.
  13. Add the following code to the FetchFromCache_Click event:
    protected void FetchFromCache_Click(object sender, EventArgs e)
    {
    List<Product> products = new List<Product>();
    for (int i = 0; i < 11; i++)
    {
    object cachedProduct = _cache.Get(i + ":dbo.Products");
    if(cachedProduct == null){ continue; }
    Product product = cachedProduct as Product;
    products.Add(product);
    }
    DataGrid1.DataSource = products;
    DataGrid1.DataBind();
    Status.Text = products.Count + " products fetched from cache.";
    }
  14. On the Build menu in the Visual Studio .NET IDE, click Build to build the project.
  15. To run the code, right-click the DataCacheSample.aspx page in Solution Explorer, and then click View in Browser.
  16. Click the FetchFromDB button; the Status label should display "10 products fetched from database." and the DataGrid control is populated. All products are stored in cache.
  17. Click the FetchFromCache button; the Status label should display "10 products fetched from cache." and the DataGrid control is populated.
  18. Modify one of the displayed records in the Northwind database by using SQL Query Analyzer or another tool. After you modify the record, cached data for that row is invalidated.
  19. Click the FetchFromCache button again. The Status label will display the message "9 products fetched from cache." and 9 products are populated. The modified record in database was removed from cache.
See Also
Enabling Notifications For SQL Server | Enabling Notifications For DB2 | Enabling Notifications For Oracle | Using Sql Yukon Dependency


Topic: Enabling Notifications For SQL Server

Enabling Notifications For SQL Server

NOTE: This feature is not available in NCache Express and Professional edition.
For enabling notifications for SQLServer tables, you need to follow these steps:
  • Create a table 'ncache_db_sync' having four fields (cache_key VARCHAR, cache_id VARCHAR, modified BIT and work_in_progress BIT). Script to create the table is as follows:
    //Create table'ncache_db_sync'
    CREATE TABLE ncache_db_sync(
    cache_key VARCHAR(256),
    cache_id VARCHAR(256),
    modified BIT DEFAULT(0),
    work_in_progress BIT DEFAULT(0),
    PRIMARY KEY(cache_key, cache_id) );
  • Create UPDATE and DELETE triggers, for every table on which notification is required. They set the 'modified' field of corresponding row in the ncache_db_sync table to 1.To carry out the task, see the following sample script that creates trigger on 'Products' table:
    //create trigger
    CREATE TRIGGER myTrigger
    ON dbo.Products
    FOR DELETE, UPDATE
    AS
    UPDATE ncdbs
    SET modified = 1
    from ncache_db_sync ncdbs
    inner join Deleted old on cache_key = (Cast((old.ProductID) as VarChar)
+ ':dbo.Products' );
Note: cache_key must be the same key that is used to add corresponding record in the cache.
Now, As soon as an item is added to the cache with dependency, a row will be created in table 'ncache_db_sync' for this cache key. We'll have to make sure that the format of cache key while adding into cache is exactly same as defined in the corresponding trigger. For our example, cache key for product id 10 should be like, "10:dbo.Products".
Add the following namespaces in your application:
using Alachisoft.NCache.Runtime.Caching;
using Alachisoft.NCache.Runtime.Dependencies;
Following code demonstrates how to add items with dependency.
Cache _cache = NCache.InitializeCache("myreplicatedcache");
_cache.ExceptionsEnabled = true;
try
{
string connectionString = "Provider=SQLOLEDB;Data Source=localhost;Database=northwind;User Id=sa;Password=;";
ProductsFactory productsFactory = new ProductsFactory(connectionString);
Collection<Products> products = productsFactory.FindByCategoryID(8);
foreach (Products product in products)
{
Alachisoft.NCache.Runtime.Dependencies.DBCacheDependency dependency = Alachisoft.NCache.Runtime.Dependencies.DBDependencyFactory.CreateOleDbCacheDependency(connectionString, product.ProductID + ":dbo.Products");
//cache key for product id 10 will be "10:dbo.Products"
mycache.Insert(product.ProductID + ":dbo.Products", product, dependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, Alachisoft.NCache.Runtime.CacheItemPriority.Default);
}
}
catch (Exception ex)
{
//throw it.
}
On execution of the above code, a few rows will be added into the table 'ncache_db_sync'. Table 'ncache_db_sync' should now look like:
As we can see the value for column 'modified' is false for all rows. This means that the cached items in myreplicatedcache for these cache_keys are still valid. As soon as we modify a row for, lets say, product id 10 in products table, it will set modified value as true in its respective row.
This means that the cached item for cache_key "10:dbo.Products" in myreplicatedcache is no more valid and this should be invalidated.
On clean interval, NCache DbCacheDependency does the following:
  1. Sets the work_in_progress flag for those rows where modified flag is set. And fetches all those rows.
  2. Removes all the keys from the cache as they all are invalid now.
  3. After successfully removing all the keys from the cache, all those rows where work_in_progress flag is set are removed from the 'ncache_db_sync' table.
If a node crashes while it was removing items from the cache, the next node in the cluster will start process from step one.
See Also
Enabling notifications for Oracle tables | Enabling notifications for DB2 tables


Topic: Enabling Notifications For Oracle

Enabling Notifications For Oracle

NOTE: This feature is not available in NCache Express and Professional edition.
For enabling notifications for Oracle tables, follow these steps:
  • Create a table 'ncache_db_sync' having four fields (cache_key VARCHAR2, cache_id VARCHAR2, modified NUMBER and work_in_progress NUMBER). Script to create the table is as follows:
//Create table'ncache_db_sync'
CREATE TABLE NCACHE_DB_SYNC (
CACHE_KEY VARCHAR2(256) NOT NULL ENABLE,
CACHE_ID VARCHAR2(256) NOT NULL ENABLE,
MODIFIED NUMBER(2,1) DEFAULT 0 NOT NULL ENABLE,
WORK_IN_PROGRESS NUMBER(2,1) DEFAULT 0 NOT NULL ENABLE,
PRIMARY KEY (CACHE_KEY, CACHE_ID) ENABLE
);
  • Create UPDATE and DELETE triggers, for every table on which notification is required. They set the 'modified' field of corresponding row in the ncache_db_sync table to 1.
To carry out the task, see the following sample script that creates trigger on 'Products' table:
//create trigger
create or replace trigger MYTRIGGER
AFTER
update or delete on PRODUCTS
REFERENCING OLD AS oldRow
for each row
BEGIN
UPDATE NCACHE_DB_SYNC
SET modified = 1
WHERE cache_key = (:oldRow.ProductID || ':dbo.Products' );
END TRIGGER;
Note: cache_key must be the same key that is used to add the corresponding record in the cache.
Here is an example for Oracle Dependency
Cache mycache = NCache.InitializeCache("myreplicatedcache");
mycache.ExceptionsEnabled = true;
try
{
string connectionString ="Provider=OraOLEDB.Oracle;
Data Source=(DESCRIPTION =(ADDRESS =(PROTOCOL = TCP)(HOST = qctest6)(PORT = 1521))(CONNECT_DATA =(SERVER = DEDICATED) (SERVICE_NAME = Northwind))); User Id=Scott; Password=;";
ProductsFactory productsFactory = new ProductsFactory(connectionString);
Collection<Products> products = productsFactory.FindByCategoryID(8);
foreach (Products product in products)
{
String itemKey += ":dbo.Products";
Alachisoft.NCache.Runtime.Dependencies.CacheDependency dep =
DBDependencyFactory.CreateOleDbCacheDependency(connectionString, itemKey);
//cache key for product id 10 will be "10:dbo.Products"
CacheItem cItem=new CacheItem(product);
cItem.Dependency=dep;
mycache.Insert(product.ProductID + ":dbo.Products", cItem.Value, cItem.Dependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default);
}
}
catch (Exception ex)
{
//throw it.
}
On clean interval, NCache DBCacheDependency does the following:
  1. Sets the work_in_progress flag for those rows where modified flag is set. And fetches all those rows.
  2. Removes all keys from the cache as they all have expired now.
  3. After successfully removing all the keys from the cache, all those rows where work_in_progress flag is set are removed from the 'ncache_db_sync' table.
If a node crashes while it was removing items from the cache, the next node in the cluster will start process from step one.
See Also
Enabling notifications for SQLServer tables | Enabling notifications for DB2 tables


Topic: Enabling Notifications For DB2

Enabling Notifications For DB2

NOTE: This feature is not available in NCache Express and Professional edition.
For enabling notifications for DB2 tables, you need to follow these steps:
  1. Create a table 'ncache_db_sync' having four fields (cache_key VARCHAR2, cache_id VARCHAR2, modified NUMBER and work_in_progress NUMBER). Script to create the table is as follows:
    //Create table'ncache_db_sync'
    CREATE TABLE ncache_db_sync(
    cache_key VARCHAR(256),
    cache_id VARCHAR(256),
    modified BIT DEFAULT(0),
    work_in_progress BIT DEFAULT(0),
    PRIMARY KEY(cache_key, cache_id));
  2. Create UPDATE and DELETE triggers, for every table on which notification is required. They set the 'modified' field of corresponding row in the ncache_db_sync table to 1. To carry out the task, see the following sample script that creates trigger on 'Products' table:
    //create triggers
    CREATE TRIGGER myUpdateTrigger
    AFTER UPDATE ON Products
    REFERENCING OLD AS o
    FOR EACH ROW
    UPDATE ncache_db_sync
    SET modified = 1
    WHERE cache_key = (:o.ProductID || ':Products');
    CREATE TRIGGER myDeleteTrigger
    AFTER DELETE ON Products
    REFERENCING OLD AS o
    FOR EACH ROW
    UPDATE ncache_db_sync
    SET modified = 1
    WHERE cache_key = (:o.ProductID || ':Products');
    Note: cache_key must be the same key that is used to add the corresponding record in the cache.
On clean interval, NCache DBCacheDependency does the following:
  1. Sets the work_in_progress flag for those rows where modified flag is set. And fetches all those rows.
  2. Removes all keys from the cache as they all have expired now.
  3. After successfully removing all keys from the cache, all those rows where work_in_progress flag is set are removed from the 'ncache_db_sync' table.
If a node crashes while it was removing items from the cache, the next node in the cluster will start process from step one.
See Also
Enabling notifications for SQLServer tables | Enabling notifications for Oracle tables


Topic: Enabling Database Cache Dependency in NHiberate

Enabling Database Cache Dependency in NHiberate

NOTE: This feature is not available in NCache Express and Professional edition.
To enable Database Cache Dependency in NHibernate items, you need to define <ncache> configuration section in the application's configuration file (it may be app.config or web.config file) and enable database notifications on the database.
To enable DBCacheDependency in NHibernate, do the following:
  • Include the following namespaces in your application:
using Alachisoft.NCache.Runtime.Dependencies;
using Alachisoft.NCache.Web.Caching;
  • Provide dbSync type in <ncache> section as follows:
    <ncache>
    <dbSync type = "sqlDependency"/>
    <class name = "nhibernator.BLL.Customer">
    <CacheKey format = "Customer:CustomerID:[pk]"/>
    <sqlDependency sql = "select ContactName from dbo.Customers where CustomerID =?"/>
    </class>
    <class name = "nhibernator.BLL.Order">
    <CacheKey format = " [pk]:Order"/>
    <sqlDependency sql = "select ContactName from dbo.Orders where OrderID=?"/>
    </class>
    </ncache>
    <ncache> section contains following configurable options to enable Database Cache Dependency:
  • dbsync: The value for dbSync type is either "sqlDependency" or "dbDependency". sqlDependency is a mechanism for synchronizing your cache with SQL Server 2005 database through .NET events. dbDependency allows you to synchronize your cache with any OLEDB compliant database through a configurable polling interval.
  • CacheKey: You can specify cache-key format here. The example above shows "Customer:CustomerID:[pk]" which would translate into "Customer:CustomerID:1000" if the CustomerID value of the object is 1000.
  • sqlDependency: If you specify "sqlDependency" value, then you must also specify the <sqlDependency=""/> tag for individual classes in <class> section. You specify a "select" SQL statement to identify a row in SQL Server 2005 database that corresponds to this cached item. Then, whenever that row is updated or removed, this cached item is also removed. The "?" in the command will be replaced with the primary key of the mapped table at runtime.
  • Enable database notifications on the database except when you are using SQL Server 2005. For further details see Enabling Database Notifications for SQL Server , Enabling Database Notifications for Oracle and Enabling Database Notifications for DB2 .
See Also
Expiring cached items | Using NCache with NHibernate


Topic: Database Dependencies with CAB

Database Dependencies with CAB

NOTE: This feature is not available in NCache Express and Professional edition.
Alachisoft.NCache.EnterpriseLibrary.Caching.Expirations contains few classes which can be used for cache dependencies with caching application block. These classes are DbDependency and SqlYukonDependency. DbDependency holds Db dependency data and is later used by NCache to create a polling based Db dependency object. While SqlYukonDependency holds the SQL2005 dependency data and is only available for SQL Server 2005.
To use DBDependency, it is required to enable the notifications for database. For details, see Enabling Notifications For SQL Server , Enabling Notifications For DB2 and Enabling Notifications For Oracle . This is a row based dependency. The cache key is associated with the table's primary key value. Thus an item expires only if the row with that primary key gets changed.
DBDependency:
Following is the step-by-step guide for using DBDependency. The example given is for SQL Server, however, Oracle and DB2 databases can also be used.
  1. Enable Notifications for Products table in Northwind database. See Enabling Notifications For SQL Server .
  2. Create an ASP.NET Application inside Visual Studio.NET by the name DataCachingUsingNCache.
  3. Register NCache as Custom Cache Manager for MS Enterprise Library 4.1 such that 'theCache' is used as a backing store. See Register NCache With CAB
  4. Include the following namespaces in your application:
    using Alachisoft.NCache.Runtime.Caching;
    using Alachisoft.NCache.Runtime.Dependencies;
  5. Add a new Web Form named DataCacheSample.aspx to your project.
  6. Add a nested class Product inside the code behind.
    [Serializable]
    class Product
    {
    public Product() { }
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public int SupplierID { get; set; }
    public int CategoryID { get; set; }
    public decimal UnitPrice { get; set; }
    }
  7. Declare a private variable "_cache" in the code behind of the DataCacheSample as.
    private CacheManager _cache;
  8. Add the following code in Page_Load event of the DataCacheSample as.
    protected void Page_Load( object sender, EventArgs e)
    {
    if (_cache == null ) { _cache = CacheFactory.GetCacheManager( "NCacheManager" ); }
    }
  9. On the Design view tab for the Web Form, add a DataGrid to the DataCacheSample page.
  10. Add a Web Form button. Change the ID property of this button to FetchFromDB, and then change the Text property to Fetch From Database.
  11. Add a second Web Form button. Change the ID property to FetchFromCache, and then change the Text property to Fetch From Cache.
  12. Add a Web Form label. Change the ID property to Status, and then clear the Text property.
  13. On the Design view tab, double-click the FetchFromDB button to open the FetchFromDB_Click event in the code-behind page.
  14. Add the following code to the FetchFromDB_Click event:
    protected void FetchFromDB_Click( object sender, System.EventArgs e)
    {
    string connectionString = "Server=localhost;initial catalog=northwind;User ID = sa; password =;" ;
    string commandText = "SELECT ProductID, ProductName, SupplierID, CategoryID, UnitPrice FROM dbo.Products where productid < 11" ;
    DataSet ds = new DataSet();
    //Create the connection and pass in the ConnectionString
    SqlConnection mySqlConn = new SqlConnection(connectionString);
    SqlCommand sqlCmd = new SqlCommand(commandText, mySqlConn);
    mySqlConn.Open();
    SqlDataReader sqlReader = sqlCmd.ExecuteReader();
    List<Product> products = new List<Product>();
    while (sqlReader.Read())
    {
    Product product = new Product();
    product.ProductID = sqlReader.GetInt32(0);
    product.ProductName = sqlReader.GetString(1);
    product.SupplierID = sqlReader.GetInt32(2);
    product.CategoryID = sqlReader.GetInt32(3);
    product.UnitPrice = sqlReader.GetDecimal(4);
    Alachisoft.NCache.EnterpriseLibrary.Caching.Expirations.DbDependency dependency =
    Alachisoft.NCache.EnterpriseLibrary.Caching.Expirations.DbDependency(connectionString, product.ProductID + ":dbo.Products" );
    _cache.Add(product.ProductID + ":dbo.Products" , product, dependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, Alachisoft.NCache.Runtime.CacheItemPriority.Normal);
    products.Add(product);
    }
    //Set the DataGrid's DataSource to the "products" list
    DataGrid1.DataSource = products;
    mySqlConn.Close();
    //Display the status
    Status.Text = products.Count+ " products fetched from database." ;
    DataGrid1.DataBind();
    }
  15. On the Design view tab for the DataCacheSample.aspx page, double-click the FetchFromCache button to open the FetchFromCache_Click event in the code-behind page.
  16. Add the following code to the FetchFromCache_Click event:
    protected void FetchFromCache_Click(object sender, EventArgs e)
    {
    List<Product> products = new List<Product>();
    for (int i = 0; i < 11; i++)
    {
    object cachedProduct = _cache.GetData(i + ":dbo.Products");
    if(cachedProduct == null){ continue;
    }
    Product product = cachedProduct as Product;
    products.Add(product);
    }
    DataGrid1.DataSource = products;
    DataGrid1.DataBind();
    Status.Text = products.Count + " products fetched from cache.";
    }
  17. On the Build menu in the Visual Studio .NET IDE, click Build to build the project.
  18. To run the code, right-click the DataCacheSample.aspx page in Solution Explorer, and then click View in Browser.
  19. Click the FetchFromDB button; the Status label should display "10 products fetched from database." and the DataGrid control is populated. All products are stored in cache.
  20. Click the FetchFromCache button; the Status label should display "10 products fetched from cache." and the DataGrid control is populated.
  21. Modify one of the displayed records in the Northwind database by using SQL Query Analyzer or another tool. After you modify the record, cached data for that row is invalidated.
  22. Click the FetchFromCache button again. The Status label displays the message "9 products fetched from cache." and 9 products are populated. The modified record in database was removed from cache.
    Note: If Status is still "10 products fetched from cache.", repeat step 21. As the Clean Interval may not have elapsed yet.
SQLYukonDependency:
For SQLYukonDependency to work with Caching application block, we need to do a minor change in the above code. We will use the class Alachisoft.NCache.EnterpriseLibrary.Caching.Expirations.SqlYukonDependency instead of Alachisoft.NCache.EnterpriseLibrary.Caching.Expirations.DBDependency. So the code snippet in step 16 of above example should be changed like following.
protected void FetchFromDB_Click(object sender, System.EventArgs e)
{
string connectionString = "Server=localhost;initial catalog=northwind;User ID = sa; password =;";
string commandText = "SELECT ProductID, ProductName, SupplierID, CategoryID, UnitPrice FROM dbo.Products where productid < 11";
DataSet ds = new DataSet();
//Create the connection and pass in the ConnectionString
SqlConnection mySqlConn = new SqlConnection(connectionString);
SqlCommand sqlCmd = new SqlCommand(commandText, mySqlConn);
mySqlConn.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
List<Product> products = new List<Product>();
while (sqlReader.Read())
{
Product product = new Product();
product.ProductID = sqlReader.GetInt32(0);
product.ProductName = sqlReader.GetString(1);
product.SupplierID = sqlReader.GetInt32(2);
product.CategoryID = sqlReader.GetInt32(3);
product.UnitPrice = sqlReader.GetDecimal(4);
string sqlCommand = "select ProductID, ProductName, SupplierID, CategoryID, UnitPrice from dbo.Products where ProductID="+product.ProductID;
Alachisoft.NCache.EnterpriseLibrary.Caching.Expirations.SqlYukonDependency dependency =
Alachisoft.NCache.EnterpriseLibrary.Caching.Expirations.SqlYukonDependency(connectionString, sqlCommand);
_cache.Add(product.ProductID + ":dbo.Products", product, Alachisoft.NCache.Runtime.CacheItemPriority.Normal, null, dependency );
products.Add(product);
}
//Set the DataGrid's DataSource to the "products" list
DataGrid1.DataSource = products;
mySqlConn.Close();
//Display the status
Status.Text = products.Count+ " products fetched from database.";
DataGrid1.DataBind();
}
Note: If SQL Server goes down/restarts, all dependencies become invalid and are removed from the cache.
See Also
Using Key Dependency | Using File Dependency | Using Custom Dependency | Using SqlCacheDependency | Using DbCacheDependency


Topic: Clean Interval

Clean Interval

Clean interval is the periodic interval after which the expired items are removed from the cache. You can change clean interval for a cache by one of following two ways.
NCache Manager:
Clean interval of a cache can be specified on Policies Tab of Cluster/Local Cache view window.
Config.ncconf:
Clean interval of a cache can also be specified through Config.ncconf as follows.
<cache-config name="mypartitionedcache" inproc="False" config-id="1" last-modified="6/20/2010 3:50:34 PM">
<eviction-policy enabled="True" default-priority="normal" policy="priority" eviction-ratio="0.25"/>
<cleanup interval="15sec"/>
</cache-config>
See Also
Configure Local Cache | Configure Cluster


Topic: Event Notifications

Event Notifications

NOTE: This feature is not available in NCache Express and Professional edition.
NCache allows client applications to register to be notified whenever add, insert or remove operation is performed against any or selected cache keys, or when some custom event occurs. Similarly, NCache provides events that are fired based upon cluster status. This section is about availing such notifications.
In This Section
Using General Purpose Events
Explains the use of General Purpose Notifications in clusters for add, insert, remove, and clear operations.
Item Specific Events
Describes notifying all the subscribers of item specific notification event when a single or multiple cache items are updated or removed from the cache.
Using Custom Events
Describes how a producer application can call a single method that invokes handlers on all the subscribers of the custom notification event.
Cache Generated Events
Explains writing event handlers to respond to notifications about the cluster status.
See Also
Using Read-through and Write-through
Shows how to transparently fetch the required data from the master datasource if it is not available in the cache and vice versa.
Using Resync Expired Items
Shows how to keep expired items in a queue for immediate access. This expired data reloads from the datasource when updated.


Topic: General purpose Notifications

General Purpose Events

NOTE: This feature is not available in NCache Express and Professional edition.
NCache notifies client applications whenever an add, insert, remove or clear operation is done against the cache. These are cluster-wide notifications and both .NET and Java applications can receive them.
Note: Before using general purpose notifications you have to enable them from NCache Manager. See How to Enable .
Add the following namespaces in your application for using events:
using Alachisoft.NCache.Web.Caching;
using Alachisoft.NCache.Runtime;
Cache Item Removed Notification
  1. Write event-handler procedure having event-handling code. For example, the following code shows the key which is being removed from the cache, in a message box.
    public void onCacheItemRemoved (string key, object o, CacheItemRemovedReason r)
    {
    MessageBox.Show(key + "is Removed from the cache");
    }
  2. Subscriber of the event needs to register itself to get notifications. Secondly, it has to specify event handler that must be called by CacheItemRemovedCallback delegate.
    _cache.ItemRemoved += new CacheItemRemovedCallback(this.onCacheItemRemoved);
    When an item is removed from the cache, the onCacheItemRemoved method is called.
Cache Item Added Notification
  1. Create event handler to respond when an item is added to the cache. For example, the following code shows the key information that is being added to the cache, in a message box.
    public void onCacheItemAdded (string key)
    {
    MessageBox.Show(key + "is Added to the cache ");
    }
  2. Subscriber of the event needs to register itself to get the notification. Secondly, it has to specify the event handler that must be called by CacheItemAddedCallback delegate.
    _cache.ItemAdded += new CacheItemAddedCallback(this.onCacheItemAdded);
    When an item is added to the cache, the onCacheItemAdded method is called.
Cache Item Updated Notification
  1. Create event handler to respond when an item is inserted to the cache. For example, the following code shows key information that is being inserted to the cache, in a message box.
    public void onCacheItemUpdated(string key)
    {
    MessageBox.Show(key + "is Inserted to the cache");
    }
  2. Subscriber of the event needs to register itself to get the notification. Secondly, it has to specify event handler that must be called by CacheItemUpdatedCallback delegate.
    _cache.ItemUpdated += new CacheItemUpdatedCallback(this.onCacheItemUpdated);
    When an item is removed from the cache, the onCacheItemUpdated method is called.
Cache Cleared Notification
  1. Create event handler to respond when cache is cleared. For example, the following code informs client application that cache has cleared, through a message box.
    public void onCacheCleared()
    {
    MessageBox.Show("cache is cleared");
    }
  2. Subscriber of the event needs to register itself to get notification. Secondly, it has to specify event handler that must be called by CacheClearedCallback delegate.
    _cache.CacheCleared += new CacheClearedCallback(this.onCacheCleared);
    When an item is removed from the cache, the onCacheCleared method is called.
See Also
Item Specific Events | Using Custom Events | Cache Generated Events | Using Read-through and Write-through | Using Resync Expired Items


Topic: Item Specific Events

Item Specific Events

NOTE: This feature is not available in NCache Express and Professional edition.
NCache allows client applications to register interested events for selected cache keys. Whenever, cached items associated with these keys are updated or removed from the cache, an event notification is sent to those clients who had registered an interest for them. These notifications are cluster-wide and both .NET and Java applications can receive them.
Add the following namespaces in your application for using events:
using Alachisoft.NCache.Web.Caching;
using Alachisoft.NCache.Runtime;
Register for selective notification
Cache.RegisterKeyNotificationCallback method registers the CacheItemUpdatedCallback and/or CacheItemRemovedCallback for a key or list of keys.
_cache.RegisterKeyNotificationCallback( string key, CacheItemUpdatedCallback updateCallback, CacheItemRemovedCallback removeCallback)
Following code example adds a key into the cache and registers the notifications for that key.
public void AddToCache()
{
Cache _cache = NCache.InitializeCache("mycache");
_cache.Insert("cache-key-sel-notification", "some-value", null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default);
_cache.RegisterKeyNotificationCallback("cache-key-sel-notification", new CacheItemUpdatedCallback(OnItemUpdated), new CacheItemRemovedCallback(OnItemRemoved));
}
void OnItemUpdated(string key)
{
//Item is updated. Do something
}
void OnItemRemoved(string key, object value, Alachisoft.NCache.Web.Caching.CacheItemRemovedReason reason)
{
//Item is removed. Do something
}
Unregister from selective notification
Cache.UnRegisterKeyNotificationCallback method unregisters the CacheItemUpdatedCallback and/or CacheItemRemovedCallback already registered for the specified key or set of keys.
_cache.UnRegisterKeyNotificationCallback( string key, CacheItemUpdatedCallback updateCallback, CacheItemRemovedCallback removeCallback)
Following code example unregisters the notifications for key that was registered in above example.
_cache.UnRegisterKeyNotificationCallback( "cache-key-sel-notification" ,OnItemUpdated, OnItemRemoved);
See Also
Using General Purpose Events | Using Custom Events | Cache Generated Events | Using Read-through and Write-through | Using Resync Expired Items


Topic: Getting notified when an item is removed

Getting notified when an item is removed

NOTE: This feature is not available in NCache Express and Professional edition.
NCache provides the CacheItemRemovedCallback delegate. It defines the signature to use when you write event handlers to respond when an item is deleted from the cache. NCache also provides the CacheItemRemovedReason enumeration to respond to the cause of removal appropriately.
To notify an application when an item is deleted from the cache
  1. Add the following namespaces in your application for using events:
    using Alachisoft.NCache.Web.Caching;
    using Alachisoft.NCache.Runtime;
  2. Create a local variable that raises the event for the CacheItemRemovedCallback delegate. For example, the following code creates an onRemove local variable of type CacheItemRemovedCallback.
    private static CacheItemRemovedCallback onRemove = null;
  3. Create an event handler procedure that responds when item is removed from the cache.
    public void RemovedCallback(string key, object value, CacheItemRemovedReason callbackreason)
    {
    MessageBox.Show(callbackreason);
    }
  4. Create an instance of the CacheItemRemovedCallback delegate that calls the event handler.
    onRemove = new CacheItemRemovedCallback (this.RemovedCallback);
  5. Add item to the Cache by either using Add method or Insert method and specify the local variable of type CacheItemRemovedCallback, created in step one. Following code uses the Insert method to add an item to the cache with a key "Key1" and a cacheItem as value.
    Cache _cache = NCache.InitializeCache("thecache");
    CacheItem cacheItem = new CacheItem ("some-value");
    cacheItem.ItemRemoveCallback = onRemove;
    _cache.Add("Customer:David:1001", cacheItem, DSWriteOption.None, null);
    _cache.Remove("Customer:David:1001", cacheItem, DSWriteOption.None, null);
    When the item added in step four is removed from the Cache for any reason, the RemovedCallback method is called, and the code within it can be accessed to render new content to a requesting client or to notify your application in a way you choose as appropriate.
See Also
Using General Purpose Events | Item Specific Events | Using Custom Events | Cache Generated Events | Using Read-through and Write-through | Using Resync Expired Items


Topic: Getting notified when an item is updated

Getting notified when an item is updated

NOTE: This feature is not available in NCache Express and Professional edition.
NCache provides the CacheItemUpdatedCallback delegate. It defines the signature to use when you write event handlers to respond when an item is updated in the cache.
To notify an application when an item is updated in the cache
  1. Add the following namespaces in your application for using events:
    using Alachisoft.NCache.Web.Caching;
    using Alachisoft.NCache.Runtime;
  2. Create a local variable that raises the event for the CacheItemUpdatedCallback delegate. For example, the following code creates an onUpdate local variable of type CacheItemUpdatedCallback.
    private static CacheItemUpdatedCallback onUpdate = null ;
    Create an event handler procedure that responds when item is updated in the cache.
    public void UpdateCallback(string key, object value)
    {
    //Item is updated. Do something
    }
  3. Create an instance of the CacheItemUpdatedCallback delegate that calls the event handler.
    onUpdate = new CacheItemUpdatedCallback (this.UpdateCallback);
  4. Add item to the Cache by either using Add method or Insert method and specify the local variable of type CacheItemUpdatedCallback, created in step one. Following code uses the Insert method to add an item to the cache with a key "Key1" and a cacheItem as value.
    Cache _cache = NCache.InitializeCache("thecache");
    CacheItem cacheItem = new CacheItem ("Updated-value");
    cacheItem.ItemUpdateCallback = onUpdate;
    _cache.Add("Customer:David:1001", cacheItem, DSWriteOption.None, null);
    _cache.Insert("Customer:David:1001", cacheItem, DSWriteOption.None, null);
    When the item added in step four is updated in the Cache the UpdateCallback method is called, and the code within it can be accessed to render new content to a requesting client or to notify your application in a way you choose as appropriate.
See Also
Using General Purpose Events | Item Specific Events | Using Custom Events | Cache Generated Events | Using Read-through and Write-through | Using Resync Expired Items


Topic: Custom Notifications

Custom Notifications

NOTE: This feature is not available in NCache Express and Professional edition.
NCache now provides the ability to generate custom notifications. A producer application can call a single method that invokes handlers on all the subscribers of the custom notification event. In a clustered environment, custom notifications are quite convenient mean of communication among the participants of the cluster. Even in local environment, a producer consumer style communication between applications is easily achieved using this facility.
Using custom notifications is a two step process. One is a producer end of notification and other is a consumer end.
Add the following namespaces in your application for using events:
using Alachisoft.NCache.Web.Caching;
using Alachisoft.NCache.Runtime;
Send Custom Notifications
Producers will raise notifications by simply calling.
_cache.RaiseCustomEvent("NotificationID", DateTime.Now);
The first parameter of the method is application defined notification code/id. This parameter can be used to logically distinguish between notification types on the consumer end, it can be thought of an opcode. The second parameter is the operand of the opcode, which again is application defined.
Register to receive Custom Notifications
On the consumer end there is a little more work to be done then just a method call. Cache provides a CustomEvent of type CustomEventCallback, which can be subscribed by the consumer end of the notifications. Here is an example on how to do that
_cache.CustomEvent += new CustomEventCallback(this.OnApplicationEvent);
_cache.RaiseCustomEvent("NotificationID", DateTime.Now);
public void OnApplicationEvent(object notifId, object data)
{
switch((string)notifId)
{
case "NotificationID":
HandleItem((ItemData)data);
break;
}
}
The last line subscribes to the Custom Notification event of the Cache. Note that, if the consumer handler for a synchronous notification raises a notification that in turn causes the producer to raise the same event synchronously, a deadlock due to infinite recursion may be imminent. It is, therefore, recommended that you carefully plan the flow of notifications while using synchronous notifications.
See Also
Using General Purpose Notifications | Using Node Events


Topic: Cache Generated Event

Cache Generated Event

NOTE: This feature is not available in NCache Express and Professional edition.
NCache provides events which are fired when a node joins or leaves the cluster or when cache stops. Applications can register interest for these events and are therefore notified when such events occur. Both .NET and Java clients can receive such notifications.
In this section
Member Joined
Explains notifying an application when a node joins the Cache cluster.
Member Left
Instructs how to notify an application when a node leaves the Cache cluster.
Cache Stopped
Explains how to notify an application when a Cache stops.


Topic: Member Joined Event

Member Joined Event

NOTE: This feature is not available in NCache Express and Professional edition.
NCache provides the MemberJoinedCallback delegate. It defines the signature to use when you write event handlers to respond when a new node joins the cluster.
Notify application when a node joins
  1. Add the following namespaces in your application for using events:
    using Alachisoft.NCache.Web.Caching;
    using Alachisoft.NCache.Runtime;
  2. Create an event handler procedure that will be called by MemberJoinedCallback when a node joins the cache cluster. For example, the following code prints the node information that joins the cache cluster.
    public void OnCacheMemberJoined(NodeInfo nodeinfo)
    {
    Console.Writeline("Node Joined With IPAddress" +
    nodeinfo.IPAddress.ToString() +
    "and port number:" + nodeinfo.Port);
    }
    Note:The parameter of type NodeInfo is defined in namespace Alachisoft.NCache.Web.Net. It returns the IPAddress and Port number of the joined node.
  3. Create an instance of the MemberJoinedCallback delegate that calls the event handler. The following code calls the method created in step two.
    Cache _cache = NCache.InitializeCache("myCache");
    _cache.MemberJoined = new MemberJoinedCallback(this.OnCacheMemberJoined);
    When a new node joins the cache cluster the OnCacheMemberJoined method is called.
See Also
Using General Purpose Events | Item Specific Events | Using Custom Events | Cache Generated Events | Using Read-through and Write-through | Using Resync Expired Items


Topic: Member Left Event

Member Left Event

NOTE: This feature is not available in NCache Express and Professional edition.
NCache provides the MemberLeftCallback delegate. It defines the signature to use when you write event handlers to respond when a node leaves the cluster.
Notify application when a node leaves
  1. Add the following namespaces in your application for using events:
    using Alachisoft.NCache.Web.Caching;
    using Alachisoft.NCache.Runtime;
  2. Create an event handler procedure that will be called by MemberLeftCallback when a node leaves the cache cluster. For example, the following code prints the node information when a node leaves the cache cluster.
    public void OnCacheMemberLeft(NodeInfo nodeinfo)
    {
    Console.Writeline("Node Left With IPAddress" +
    nodeinfo.IPAddress.ToString() +
    "and port number:" + nodeinfo.Port);
    }
    Note: The parameter of type NodeInfo is defined in namespace Alachisoft.NCache.Web.Net. It returns the IPAddress and Port number of the leaving node.
  3. Create an instance of the MemberLeftCallback delegate that calls the event handler. The following code calls the method created in step two.
    Cache _cache = NCache.InitializeCache("myCache");
    _cache.MemberLeft = new MemberLeftCallback(this.OnCacheMemberLeft);
    When a node leaves the cache cluster, the OnCacheMemberLeft method is called.
See Also
Using General Purpose Events | Item Specific Events | Using Custom Events | Cache Generated Events | Using Read-through and Write-through | Using Resync Expired Items


Topic: Cache Stopped Event

Cache Stopped Event

NOTE: This feature is not available in NCache Express and Professional edition.
NCache provides the CacheStoppedCallback delegate. It defines the signature to use when you write event handlers to respond when the running cache stops.
Notify application when cache stops
  1. Add the following namespaces in your application for using events:
    using Alachisoft.NCache.Web.Caching;
    using Alachisoft.NCache.Runtime;
  2. Create an event handler procedure that will be called by CacheStoppedCallback when cache stops. For example, the following code prints cache information that is being stopped.
    public void OnCacheStopped(string cacheid)
    {
    Consol.Writeline(cacheid + "is stopped now");
    }
  3. Create an instance of the CacheStoppedCallback delegate that calls the event handler. The following code calls the method created in step two.
    Cache _cache = NCache.InitializeCache("mycache");
    _cache.CacheStopped = new CacheStoppedCallback(this.OnCacheStopped);
    When a cache stops running, the OnCacheStopped method is called.
See Also
Using General Purpose Events | Item Specific Events | Using Custom Events | Cache Generated Events | Using Read-through and Write-through | Using Resync Expired Items


Topic: Read-through and Write-through Caching

Read-through and Write-through Cache Providers

NOTE: This feature is not available in NCache Express and Professional edition.
While working with datasources, it is important to transparently fetch required data from the master datasource if it is not available in the cache and vice versa. Read-Through and Write-through are provided by NCache for this purpose. Now you can add multiple Read-Through and Write-through providers with your applications.
Following section describes the required steps to enable read-through and write-through Cache Providers.
In this section
Enabling Read-Through Cache Providers
Describes how you can enable Read-Through Caching using NCache Manager in few simple steps.
Enabling Write-Through Cache Providers
Describes how you can enable Write-Through Caching using NCache Manager in few simple steps.
See Also
Implementing IReadThruProvider
Explains implementation of IReadThuProvider and list of methods required to be defined by the classes implementing this provider on server end.
Implementing IWriteThruProvider
Explains implementation of IWriteThruProvider and list of methods required to be defined by the classes implementing this provider on server end.
IReadThruProvider IWriteThruProvider Deployment
Explains the deployment of IReadThuProvider and IWriteThuProvider.


Topic: Enabling Read-through Cache Provider

Enabling Read-through Cache Provider

NOTE: This feature is not available in NCache Express and Professional edition.
To enable Read-through caching, you need to implement IReadThruProvider and specify them in the cache properties. NCache Manager provides an interface for specifying them in the cache properties. For enabling read-through caching, follow the steps given below:
  1. From the start programs, launch NCache Manager.
  2. Open the project containing cache or cluster for which you want to configure the read-through caching.
  3. From the explorer, select the cache or cluster. In the right pane, cluster/cache view will be opened.
  4. From the view, select the Backing Source tab .
  5. Check the Enable Read-Through on this cache check box.
  6. Click Add button and browse the Assembly that contains the class implementing IReadThruProvider and then select class name from the list. The Assembly implementing IReadThruProvider must contain the reference of Alachisoft.NCache.Runtime.dll.
  7. Deploy appropriate assemblies to the cache servers using Deploy Provider button from same tab view.
  8. You can provide some additional parameters (like datasource file name) if required from the same screen.
  9. Add following namespaces in your project:
    using Alachisoft.NCache.Web.Caching;
    using Alachisoft.NCache.Runtime.DatasourceProviders;
    using Alachisoft.NCache.Runtime;
  10. Now you can make direct calls to NCache to get the required items. If NCache does not have already loaded items, then it will use "LoadFromSource" method in specified data access class to load the items from a datasource. The code to access the cache should look like;
    Cache mycache = NCache.InitializeCache("myreplicatedcache");
    object product = mycache.Get("Customer:David:1001", "XmlReadThruProvider" , DSReadOption.ReadThru);
    If you do not want to give provider name in API, you can provide it in client.ncconf. If provider name is not provided in both API and client.ncconf, default provider will automatically be used.
    <cache id = "myreplicatedcache" client-cache-id = "" default-readthru-provider = "XmlReadThruProvider"
    default-writethru-provider = "XmlWriteThruProvider">
    <server name = "20.200.20.5">
    </cache>
    NCache logs the warnings in Application event log in case of an exception during loading the assemblies.
See Also
Configure Cluster Cache | Implementing IReadThruProvider


Topic: Enabling Write-through Cache Provider

Enabling Write-through Cache Provider

NOTE: This feature is not available in NCache Express and Professional edition.
To enable Write-through caching, you need to implement IWriteThruProvider and specify them in the cache properties. NCache Manager provides an interface for specifying them in the cache properties. For enabling write-through caching, follow the steps given below:
  1. From the start programs, launch NCache Manager.
  2. Open the project containing cache or cluster for which you want to configure the write-through caching.
  3. From the explorer, select the cache or cluster. In the right pane, cluster/cache view will be opened.
  4. From the view, select the Backing Source tab .
  5. For enabling Write-through caching, check the Enable Write-Through on this cache check box on the same tab.
  6. Click Add button and browse the Assembly that contains the class implementing IWriteThruProvider and then select class name from the list. The Assembly implementing IWriteThruProvider must contain the reference of Alachisoft.NCache.Runtime.dll.
  7. For enabling the Write-Behind caching, check the checkbox under Write-Behind column.
  8. Deploy appropriate assemblies to the cache servers using Deploy Provider button from same tab view.
  9. You can provide some additional parameters (like datasource file name) if required from the same screen.
  10. Add following namespaces in your project:
    using Alachisoft.NCache.Web.Caching;
    using Alachisoft.NCache.Runtime.DatasourceProviders;
    using Alachisoft.NCache.Runtime;
  11. The code to add data in a cache should look like:
    Cache mycache = NCache.InitializeCache("myreplicatedcache");
    Product product = new Product();
    CacheItem citem = new CacheItem (product);
    cache.Add(textBox.Text, citem, DSWriteOption.WriteThru, null);
    If you do not want to give provider name in API, you can provide it in client.ncconf. If provider name is not provided in both API and client.ncconf, default provider will automatically be used.
    <cache id = "myreplicatedcache" client-cache-id = "" default-readthru-provider = "XmlReadThruProvider"
    default-writethru-provider = "XmlWriteThruProvider">
    <server name = "20.200.20.5">
    </cache>
    NCache logs the warnings in Application event log in case of an exception during loading the assemblies.
See Also
Configure Cluster | Implementing IWriteThruProvider


Topic: Queries & LINQ

Queries & LINQ

NOTE: This feature is not available in NCache Express and Professional edition.
NCache provides object querying support for both .NET and Java clients. This section explains the process of using queries in .NET. It also illustrates query syntax for simplifying the overall task.
In This Section
Using Queries in .NET
Explains procedure of querying objects in .NET environment.
Query Syntax
Explains SQL like syntax that NCache API uses for querying objects.
Using LINQ
Shows how to run the queries using LINQ.
See Also
Using Bulk Operations
Describes performing bulk operations to add, insert or remove collection of items in a single method call. It helps speeding up the process and minimizes cluster traffic.
Using Data Grouping
Presents distributing related objects in 'logical' groups.
Using Resync Expired Items
Shows how to keep expired items in a queue for immediate access. This expired data reloads from the datasource when updated.


Topic: Queries

Queries

NOTE: This feature is not available in NCache Express and Professional edition.
Your application typically uses a cache as a Hashtable where everything is stored based on a key and you must have this key to fetch an item. This is like having a relational database where you can use primary key only to find data. This works fine in many situations but a real life complex application often needs to find data based on attributes other than just the primary key. And, since you're keeping a lot of your data in the cache, it would be very useful if you could search the cache in this manner as well. NCache provides this facility. NCache provides an Object Query Language (OQL) to let you search the cache. You have to make API calls and specify a search based on OQL in order to fetch collection of objects from the cache. NCache requires all searchable attributes to be indexed. See Indexing Searchable Attributes in .NET for details on indexing. Following API is available to search the cache:
public ICollection Search(string query, IDictionary parameters)
public IDictionary SearchEntries(string query, IDictionary parameters)
Query: Query string but instead of values '?' will be specified by user.
Parameters: Key-value pairs of attribute-names and their values. Both attribute-names and their values will be saved in string format.
Cache Search Returning Keys
The following code searches the cache and returns a collection of keys. Then, it iterates over all the returned keys and individually fetches the corresponding cached items from the cache.
Include the following namesapce in your application:
using Alachisoft.NCache.Web.Caching;
public class Program
{
public static void Main (string[] args)
{
Cache _cache = NCache.InitializeCache("myreplicatedcache");
String query = "SELECT NCacheQuerySample.Business.Product WHERE this.ProductID > ?";
Hashtable values = new Hashtable();
values.Add("ProductID",100);
// Fetch the keys matching this search criteria
ICollection keys = _cache.Search(query, values);
if (keys.Count > 0)
{
IEnumerator ie = keys.GetEnumerator();
while (ie.MoveNext())
{
String key = (String)ie.Current;
Product prod = (Product)NCache.Cache.Get(key);
HandleProduct(prod);
Console.WriteLine("ProductID: {0}", prod.ProductID);
}
}
_cache.Dispose();
}
}
The benefit of this approach is that the query returns keys only. Then, the client application can determine which key it wants to fetch. The drawback of this approach is that if you're going to fetch most of the items from the cache anyway, then you'll end up making a lot of trips to the cache. And, if the cache is distributed, this may eventually become costly.
Cache Search Returning Items
In some situations when you intend to fetch all or most of the cached items associated with cache keys, it is better to fetch all the keys and items in one call. Below is an example for this. It searches the cache and returns a dictionary containing both keys and values. This way, all the data based on the search criteria is fetched in one call to NCache. This is much more efficient way of fetching all the data from the cache.
Include the following namesapce in your application:
using Alachisoft.NCache.Web.Caching;
public class Program
{
public static void Main (string[] args)
{
Cache _cache = NCache.InitializeCache("myreplicatedcache");
String query = "SELECT NCacheQuerySample.Business.Product WHERE this.ProductID > ?";
Hashtable values = new Hashtable();
values.Add("ProductID", 100);
// Fetch the keys matching this search criteria
IDictionary dict = _cache.SearchEntries(query, values);
if (dict.Count > 0)
{
IDictionaryEnumerator ide = dict.GetEnumerator();
while (ide.MoveNext())
{
String key = (String)ide.Key;
Product prod = (Product)ide.Value;
HandleProduct(prod);
Console.WriteLine("Key = {0}, ProductID: {1}", key, prod.ProductID);
}
}
_cache.Dispose();
}
}
See Also
Indexing Searchable Attributes in .NET | Object Query Language Syntax


Topic: Indexing Searchable Attributes in .NET

Indexing Searchable Attributes in .NET

NOTE: This feature is not available in NCache Express and Professional edition.
NCache requires all searchable attributes to be indexed. This is because, without indexing, NCache would have to traverse the entire cache in order to find items. This could be very costly operation with potential of slowing down the entire cache.
NCache provides its own indexing mechanism. You can identify objects in .NET assemblies that you want to index. NCache uses .NET Reflection to extract data from the indexed attributes and builds its internal index. Then, when you query the cache with Cache.Search() or Cache.SearchEntries(), NCache uses these indexes to quickly find the desired objects and returns them to you.
Defining Indexes
NCache Manager provides a user friendly interface for defining indexes. Following example demonstrates procedure of defining indexes on attributes.
Suppose that cache contains Customer object where the definition of Customer is as below:
[Serializable]
public class Customer
{
public string CustomerID;
public string Country;
public Customer(string id, string country)
{
this.CustomerID = id;
this.Country = country;
}
}
Follow these steps to define indexes for the attributes of "Customer":
  • Stop the Cache if it is running.
  • From the tabbed view, select 'Query Indexes' tab as shown in the figure below.
  • Click 'Add' button from the Query Indexes tab, you'll see the 'Select Query Indices' dialog. Click 'Browse' button to add assembly which contains the definition of the Customer.
  • From the list of 'Selected Assemblies', select Customer class and add it to the List of selected Classes using 'Add Class' button.
  • From the 'Select Query Indexes' dialog, mark the attribute(s) of the Customer class that you want to be indexed.
  • Press 'OK' button to complete the process.
  • The following screen appears, showing the attributes selected for the indexing.
  • Apply Configuration changes to the cache .
See Also
Using Queries in .NET


Topic: Object Query Language Syntax

Object Query Language Syntax

NOTE: This feature is not available in NCache Express and Professional edition.
NCache supports SQL-like language called Object Query Language (OQL). Syntax of the language is explained with the help of examples below:
Using Equal Operator:
string queryString = "select NCacheQuerySample.Business.Product where this.Category = ?" ;
Hashtable values = new Hashtable();
values.Add("ProductID", 10);
ICollection keys = _cache.Search(queryString, values);// Return Keys
IDictionary dict = _cache.SearchEntries(query, values);// Return Keys and values
Using Multiple Operators:
string queryString = "select NCacheQuerySample.Business.Product where this.ProductID < ? AND this.Category = ?" ;
Hashtable values = new Hashtable();
values.Add("ProductID", 10);
values.Add("Category", 4);
ICollection keys = _cache.Search(queryString, values);// Return Keys
IDictionary dict = _cache.SearchEntries(query, values);// Return Keys and values
Using IN Operator:
string queryString = "select NCacheQuerySample.Business.Product where this.ProductID IN (?,?,?);
ArrayList list = new ArrayList();
list.Add(10);
list.Add(4);
list.Add(7);
Hashtable values = new Hashtable();
values.Add("ProductID", list);
ICollection keys = _cache.Search(queryString, values);// Return Keys
IDictionary dict = _cache.SearchEntries(query, values);// Return Keys and values
Using LIKE Operator:
string queryString = "select NCacheQuerySample.Business.Product where this.ProductName LIKE ?;
ArrayList list = new ArrayList();
list.Add("Ch*"); //returns all entries that start with "Ch".
Hashtable values = new Hashtable();
values.Add("ProductName", list);
ICollection keys = _cache.Search(queryString, values);// Return Keys
IDictionary dict = _cache.SearchEntries(query, values);// Return Keys and values
The following operators are supported in NCache queries:
Category | Operator
<Query> | = , == , != , <> , < , > , <=, >=, IN, LIKE , NOT LIKE
Logical Operators | AND , OR , NOT
Aggregate Functions | Sum, Count, AVG, Min, Max
Miscellaneous | DateTime.Now , DateTime ("any date time compatible string")
See Also
Using Queries


Topic: NCache LINQ

LINQ with NCache

NOTE: This feature is not available in NCache Express and Professional edition.
LINQ is a set of new programming semantics that allows you to unify the way of accessing data of any kind. Data can be found in collection of domain objects, XML document, object graph, tree structure, Linked list etc. LINQ unify the way of accessing data in all sources of information you can deal with, while writing your code.
So basically, LINQ helps you in:
  • Unifying the way of accessing data from different data sources (Objects, database, XML etc).
  • It shields you from learning the specification details of each data source.
We integrate LINQ with NCache by implementing a class named "NCacheQuery", which further implements the interface called "IQueryable" provided by .NET framework. This integration allows you to run LINQ queries on your cached items. For executing LINQ queries on your cached items you are supposed to define an object implementing IQueryable interface and pass an instance of cache which contains the object as shown below:
IQueryable<Product> products = new NCacheQuery<Product>(_cache);
NCache is integrated with LINQ in such a way that no code change is required except that you will have to add a new assembly reference and namespace in your application rest of the code will work without any change. NCache only support single entity search, multiple entities or joins are not supported.
Include the following namespace in your application for LINQ support:
using Alachisoft.NCache.Linq;
The following code shows how to implement the NCacheQuery class which further implements IQueryable interface. The code also shows the LINQ query based on NCache Query Language running on a cached data.
namespace NCacheLINQ
{
class Program
{
static void Main (string[] args)
{
IQueryable<Product> products = new NCacheQuery<Product>(_cache);
try
{
var result1 = from product in products
where product.ProductID > 10
select product;
if (result1 != null)
{
foreach (Product p in result1)
{
Console.WriteLine("ProductID : " + p.ProductID);
}
}
else
{
Console.WriteLine("No record found.");
}
}
catch (Exception)
{
Console.WriteLine(_error);
}
Console.WriteLine("Press Enter to continue..");
Console.ReadLine();
}
}
}
There are some LINQ operators which are not supported by NCache queries, those are:
  • NCache queries does not support nested queries.
  • LINQ operator ORDERBY is not supported by NCache queries as SQL Server has an in-built orderby operator.
  • LINQ operator GROUPBY is not supported by NCache queries as SQL Server has an in-built groupby operator.
  • Join operations are not supported by NCache queries.
  • User has to go through the trouble of indexing the data first, through NCache Manager.
The following operators are supported in NCache queries:
Category | Operator
<Query> | = , == , != , <> , < , > , <=, >=, IN, LIKE , NOT LIKE
Logical Operators | AND , OR , NOT
Aggregate Functions | Sum, Count, AVG, Min, Max
Miscellaneous | DateTime.Now , DateTime ("any date time compatible string")
See Also
Indexing Attributes for LINQ


Topic: Indexing Attributes for LINQ

Indexing Attributes for LINQ

NOTE: This feature is not available in NCache Express and Professional edition.
NCache requires all searchable attributes to be indexed. This is because, without indexing, NCache would have to traverse the entire cache in order to find items. That is a very costly operation with potential of slowing down the entire cache.
NCache provides its own indexing mechanism through which you can identify objects in .NET assemblies that you want to index. NCache uses .NET Reflection to extract data from the indexed attributes and builds its internal index. Then, when you query the cache, NCache uses those indexes to quickly find the desired objects and returns them to you.
Defining Indexes
NCache Manager provides a user friendly interface for defining indexes. Following example demonstrates procedure of defining indexes on attributes.
Suppose that cache contains Customer object where the definition of Customer is as below:
[Serializable]
public class Customer
{
public string CustomerID;
public string Country;
public Customer(string id, string country)
{
this.CustomerID = id;
this.Country = country;
}
}
Follow the steps given below to define indexes for the attributes of Customer:
  • Stop the Cache if it is running.
  • From the tabbed view, select 'Query Indexes' tab as shown in the figure below.
  • Click 'Add' button from the Query Indexes tab, you'll see the 'Select Query Indices' dialog. Click 'Browse' button to add assembly which contains the definition of the Customer.
  • From the list of 'Selected Assemblies', select Customer class and add it to the List of selected Classes using 'Add Class' button.
  • From the 'Select Query Indexes' dialog, mark the attribute(s) of the Customer class that you want to be indexed.
  • Press 'OK' button to finish the process.
  • The following screen appears, showing the attributes selected for the indexing.
  • Apply Configuration changes to the cache .
See Also
NCache LINQ


Topic: Continuous Query

Continuous Query

NOTE: This feature is not available in NCache Express and Professional edition.

NCache provides Continuous Query support for both .NET and Java clients. Continuous Query is a technique of registering queries on a cache server and associating list of related events with them in order to get the latest result. It notifies about the changes occured in query result set and therefore, client applications don't need to re-query the data for updates. This process is ideal for the scenarios where application repeats a specific query and would benefit from always having an up-to-date query result set.
Continuous Query is also capable of notifying an ongoing stream of events related to the specific query result set. Here cache monitors the result set of a query for any Add/Update/Remove event and notifies the application accordingly, which eventually helps in maintaining an up-to-date copy of data all the time.
Continuous Query offers a list of events that are fired when any add, update or delete operation is performed on data set which in return affects the query result set. Applications can register interest for these events and are therefore notified whenever the query result set changes.
NCache also provides you the Object Query Language (OQL) to let you search the cache. You have to make API calls and specify a search based on this OQL in order to register/unregister and fetch collection of objects from the cache. NCache requires all searchable attributes to be indexed. See Indexing Searchable Attributes in .NET for details about indexing.
Include the following namespace in your application:
using Alachisoft.NCache.Web.Caching;
See Also
Indexing Searchable Attributes in .NET | Using Continuous Query


Topic: Indexing Searchable Attributes in .NET

Indexing Searchable Attributes in .NET

NOTE: This feature is not available in NCache Express and Professional edition.
NCache requires all searchable attributes to be indexed. This is because, without indexing, NCache would have to traverse the entire cache in order to find the items. That is a very costly operation with potential of slowing down the entire cache.
NCache provides its own indexing mechanism. You can identify the objects in your .NET assemblies that you want to index. NCache uses .NET Reflection to extract data from the indexed attributes and builds its internal index. Then, when you query the cache with cache.SearchCQ() and cache.SearchEntriesCQ(), NCache uses these indexes to quickly find the desired objects and returns them to you.
Defining Indexes
NCache Manager provides a user friendly interface for defining indexes. Following example demonstrates procedure of defining indexes on attributes.
Suppose that cache contains Person object where the definition of Person is as below:
[Serializable]
public class Person
{
public string CustomerID;
public int Age;
public Person(string id, int age)
{
this.CustomerID = id;
this.Age = age;
}
}
Follow these steps to define indexes for the attributes of Person:
  • Stop the Cache if it is running.
  • From the tabbed view, select 'Query Indexes' tab as shown in the figure below.
  • Click 'Add' button from the Query Indexes tab, you'll see the 'Select Query Indices' dialog. Click 'Browse' button to add assembly which contains the definition of the Person.
  • From the list of 'Selected Assemblies', select Person class and add it to the List of selected Classes using 'Add Class' button.
  • From the 'Select Query Indexes' dialog, mark the attribute(s) of the Person class that you want to be indexed.
  • Press 'OK' to complete the process.
  • The following screen appears, showing the attributes selected for the indexing.
  • Apply Configuration changes to the cache .
See Also
Using Continuous Query | Continuous Query


Topic: Using Continuous Query

Using Continuous Query

NOTE: This feature is not available in NCache Express and Professional edition.
Following is a list of methods needs to be defined by the class for implementing Continuous Query and a brief description of their purpose.
  • Instance of ContinuousQuery class and notification registration:
An instance of a ContinuousQuery class is required for all methods. It holds information regarding a unique string query i.e. "command text" and Hashtable values i.e. "command parameters". It also contains event notifications for Add, Update and Remove operations. To activate a Continuous Query, you need to register event notifications for that particular Continuous Query instance.
Note: For every continuous query instances, at least one notification must be registered.
Following event handler procedures should be created that will be called by Add, Update and Remove callbacks whenever a result set changes. If user is not interested in some callback, "null" can be passed for that particular callback:
ContinuousQuery query = new ContinuousQuery(queryString, values);
query.RegisterAddNotification(new ContinuousQueryItemAddedCallback(query_ItemAdded));
query.RegisterUpdateNotification(new ContinuousQueryItemUpdatedCallback(query_ItemUpdated));
query.RegisterRemoveNotification(new ContinuousQueryItemRemovedCallback(query_ItemRemoved));
static void query_ItemRemoved(string key)
{
Console.WriteLine("Removed");
}
static void query_ItemUpdated(string key)
{
Console.WriteLine("Updated");
}
static void query_ItemAdded(string key)
{
Console.WriteLine("Added");
}
  • void RegisterCQ(ContinuousQuery query);
Register continuous query method is used to activate "Continuous Query" on server. This method can be called many times for the same query for registering/un-registering various callbacks. Cache.RegisterCQ method is used only for registering the notifications and it does not return any result set to the client application.
_cache.RegisterCQ(query);
  • void UnRegisterCQ(ContinuousQuery query);
Unregister Continuous Query method is used to unregister the callbacks from cache when a user is no more interested in notifications for changes in a query result set.
_cache.UnRegisterCQ(query);
  • ICollection SearchCQ(ContinuousQuery query);
Search Continuous Query method comprises of two functionalities, ‘RegisterCQ’ which activates the continuous query on server (if it is not already activated) and ‘SearchCQ’ which searches the cache and returns a collection of keys to the client application. The benefit of this approach is that it only returns keys. Then, the client application can determine the keys to be fetched. The drawback of this approach is that if user is going to fetch most of the items from the cache anyway, he will end up making a lot of trips to the cache. And, if the cache is distributed, this may eventually become costly.
ICollection keys = _cache.SearchCQ(query);
if (keys.Count > 0)
{
IEnumerator ie = keys.GetEnumerator();
while (ie.MoveNext())
{
String key = (String)ie.Current;
Person prs = (Person)NCache.Cache.Get(key);
HandlePerson(prs);
Console.WriteLine("Age: {0}", prs.Age);
}
}
  • IDictionary SearchEntriesCQ(ContinuousQuery query);
Search Entries Continuous Query method is almost similar to the Cache.SearchCQ method but it searches the cache and returns a dictionary containing both keys and values. It will keep pre-fetched data locally and will immediately return the data on demand. It runs the query on the dataset and returns a Dictionary containing both keys and values. This way, all the data based on the query is fetched in one call. This is much more efficient way of fetching the data from the cache.
IDictionary dict = _cache.SearchEntriesCQ(query);
if (dict.Count > 0)
{
IDictionaryEnumerator ide = dict.GetEnumerator();
while (ide.MoveNext())
{
String key = (String)ide.Key;
Person prs = (Person)ide.Value;
HandlePerson(prs);
Console.WriteLine("Key = {0}, Age: {1}", key, prs.Age);
}
}
Example ContinuousQuery:
Here is how your class should look like:
Cache _cache = NCache.InitializeCache("myreplicatedcache");
string queryString = "SELECT ClassLibrary1.Person WHERE this.Age >= ?";
Hashtable values = new Hashtable();
values.Add("Age", 25);
ContinuousQuery query = new ContinuousQuery(queryString, values);
query.RegisterAddNotification(new ContinuousQueryItemAddedCallback(query_ItemAdded));
query.RegisterUpdateNotification(new ContinuousQueryItemUpdatedCallback(query_ItemUpdated));
query.RegisterRemoveNotification(new ContinuousQueryItemRemovedCallback(query_ItemRemoved));
The following operators are supported in NCache Continuous queries:
Category | Operator
<Query> | = , == , != , <> , < , > , <=, >=, IN, LIKE , NOT LIKE
Logical Operators | AND , OR , NOT
Aggregate Functions | Sum, Count, AVG, Min, Max
Miscellaneous | DateTime.Now , DateTime ("any date time compatible string")
See Also
Indexing Searchable Attributes in .NET | Continuous Query


Topic: Server Side API Programming

Server Side API Programming

This tutorial is a practical guide for programmers who want to utilize powerful features of Server side NCache to create high performance and scalable .NET applications. This includes working examples and code snippets to utilize various features of NCache efficiently.
In This Section
Cache Startup Loader
Explains how to use Cache Startup Loader.
Read-through, Write-through, Write-behind
Shows how to transparently fetch the required data from the master datasource if it is not available in the cache and vice versa.
Dynamic Compact Serialization
Explains making application data types Compact Serializable and use them in your application with NCache.
Data Sharing between .Net and Java
Explains how to share data between .Net and Java clients at runtime.
Bridge Conflict Resolver
Explains how to use Conflict Resolver.
Custom Cache Dependency
Depicts how you can use custom dependencies by defining your own expiration logics.


Topic: Cache Startup Loader

Cache Startup Loader

NOTE: This feature is not available in NCache Express and Professional edition.
While It is not always the case when a user should enter data in cache manually. Under some special scenarios it is important that cache is preloaded with base data before a user starts using it. NCache allows this pre-load of cache by giving user the feature of Cache Startup Loader.
Following section describes the required steps to enable Cache Startup Loader.
In this section
Using Cache Startup Loader
Explains the API references and namespaces required for implementing Cache Startup Loader.
Enabling Cache Startup Loader
Describes how you can enable Cache Startup Loader through NCache Manager in few simple steps.
Implementing ICacheLoader
Explains implementation of ICacheLoader and list of methods required to be defined by the classes implementing this loader.
See Also
Configure Cluster Cache
Helps you configure Clustered Cache.


Topic: Using Cache Startup Loader

Using Cache Startup Loader

NOTE: This feature is not available in NCache Express and Professional edition.
Namespace:
For enabling Cache Startup Loader, your program needs a reference of the assembly Alachisoft.NCache.Runtime.dll that contains interface Alachisoft.NCache.Runtime.CacheLoader.ICacheLoader provided by NCache. The class implementing this interface allows framework to load data from the master datasource in the cache. Thus, the class needs to include the logic for loading the data from the datasource.
Following namespaces are required in your project for using ICacheLoader:
using Alachisoft.NCache.Runtime.CacheLoader;
using Alachisoft.NCache.Runtime.Caching;
ICacheLoader Interfaces:
In order to use ICacheLoader in your application, implement the following interface:
public void Init(System.Collections.IDictionary parameters);
public bool LoadNext(ref System.Collections.Specialized.OrderedDictionary data, ref object index);
public void Dispose();
See Also
Configure Cluster Cache | Implementing ICacheLoader


Topic: Enabling Cache Startup Loader

Enabling Cache Startup Loader

NOTE: This feature is not available in NCache Express and Professional edition.
Configuring Startup Loader in NCache Manager:
To enable Cache Startup Loader, you need to implement ICacheLoader and specify it in the cache properties. NCache Manager provides an interface for specifying it under the cache properties. For Cache Startup Loader, follow these steps:
  1. From the start programs, launch NCache Manager.
  2. Open the project containing cache or cluster for which you want to configure the Cache Startup Loader.
  3. From the explorer, select the cache or cluster. In the right pane, cluster/cache view will be opened.
  4. From the view, select the Cache Loader tab .
  5. Check the Enable Cache-Startup Loader check box.
  6. Click Browse button and browse the Assembly that contains the class implementing ICacheLoader and then select class name from the list. The Assembly implementing ICacheLoader must contain the reference of Alachisoft.NCache.Runtime.dll.
  7. You can provide some additional parameters (like chunkSize etc.) if required.
  8. You can specify number of retries if any cache operation fails.
  9. You can also specify retry interval between each retry. This value is in sec's.
  10. Deploy the appropriate assemblies to the cache servers using the Deploy Cache Loader button on a same tab view.
Deployment:
For deployment details, please visit Deploying Cache Loader page.
See Also
Configure Cluster Cache | Implementing ICacheLoader


Topic: Implementing ICacheLoader Interfaces

Implementing ICacheLoader Interfaces

NOTE: This feature is not available in NCache Express and Professional edition.
Implementing ICacheLoader
Following is a list of methods needs to be defined by the class implementing interface and a brief description of their purpose.
  • void Init(IDictionary parameters);
This method performs tasks like allocating resources, acquiring connections etc. When the cache is initialized and Cache Startup Loader is enabled, it calls Init method to notify the client that cache has initialized and you may initialize your data source too. The parameters passed as an argument contains all the parameters (if any) that were specified using NCache Manager cache/cluster views. These parameters can be utilized in many ways. For example, connection string of a datasource can be specified as a parameter through NCache Manager. Whenever cache will be initialized, the connection to the datasource could be made using this connection string passed as an argument. Thus, it provides a flexible way to change the datasource dynamically without requiring code changes.
  • void Dispose();
This method performs tasks like releasing the resources etc. When Cache is stopped or LoadNext returns false, it calls the Dispose() method to notify the client that the task has completed or cache has stopped now and you can free the resources related to your datasource.
  • public bool LoadNext(ref System.Collections.Specialized.OrderedDictionary data, ref object index);
This method should contain logic to load object(s) from the master datasource. After Init call, framework calls LoadNext method in a loop till LoadNext returns false. This method receives an OrderedDictionary reference that user needs to set and populate with its respective data. Another ref variable is index. User must set it to be starting index in given OrderedDictionary. This function allows user to add data in chunks, or add it as a single operation. If user wants to add data in chunks, he must return True back to caller framework, indicating that this method should be called again. User should return false, to end Startup loading of data by the framework.
Using ICacheLoader:
Here is how your class should look like for ICacheLoader:
namespace CacheLoaderApp
{
class CacheLoader : ICacheLoader
{
private string _connString = @"Server=stagingServer2; initial catalog=Northwind; User ID=sa; password=xxxxxx;";
private SqlConnection _connection;
#region ICacheLoader Members
public void Init(System.Collections.IDictionary parameters)
{
_connection = new SqlConnection(_connString);
_connection.Open();
}
public bool LoadNext(ref System.Collections.Specialized.OrderedDictionary data, ref object index)
{
int nextIndex = 0;
if (index != null)
{
nextIndex = (int)index;
}
SqlCommand command = new SqlCommand("SELECT * FROM Customers WHERE CustomerID > " + nextIndex.ToString() + " AND CustomerID < " + (nextIndex + 10).ToString());
SqlDataReader reader = command.ExecuteReader();
if (!reader.HasRows)
return true;
while (reader.Read())
{
Customer customer = new Customer();
customer.CustomerID = reader["CustomerID"].ToString();
customer.ContactName = reader["ContactName"].ToString();
customer.Country = reader["Country"].ToString();
ProviderCacheItem provideritem = new ProviderCacheItem(customer);
provideritem.Dependency = new KeyDependency("customer:1");
provideritem.AbsoluteExpiration = System.DateTime.Now.AddSeconds(30);
data.Add("Customer:" + customer.CustomerID, provideritem);
}
index = nextIndex + 10;
reader.Close();
return false;
}
public void Dispose()
{
if (_connection != null)
_connection.Close();
}
#endregion
}
}
NCache logs the warnings in Application event log in case of an exception during loading the assemblies.
See Also
Enabling Cache Startup Loader


Topic: Read-through and Write-through Caching

Read-through and Write-through Caching

NOTE: This feature is not available in NCache Express and Professional edition.
While working with datasources, it is important to transparently fetch the required data from the master datasource if it is not available in the cache and vice versa. Read-Through and Write-through are provided by NCache for this purpose. Now you can add multiple Read-Through and Write-through providers with your applications.
Following section describes the required steps to enable read-through and write-through Cache Providers.
In this section
Using Read-Thru Provider
Explains implementation of IReadThuProvider and list of methods required to be defined by the classes implementing this provider.
Using Write-Thru Provider
Explains implementation of IWriteThruProvider and list of methods required to be defined by the classes implementing this provider.
See Also
Enabling Read-Through Cache Providers
Describes how you can enable Read-Through Caching using NCache Manager in few simple steps.
Enabling Write-Through Cache Providers
Describes how you can enable Write-Through Caching using NCache Manager in few simple steps.
IReadThruProvider IWriteThruProvider Deployment
Explains the deployment of IReadThuProvider and IWriteThuProvider.


Topic: Read-through Cache Provider

Read-through Cache Provider

NOTE: This feature is not available in NCache Express and Professional edition.
Namespace:
For enabling Read-through caching, you need reference of the following assembly in your application:
Alachisoft.NCache.Runtime.dll
This assembly contains class implementing Alachisoft.NCache.Runtime.DatasourceProviders.IReadThruProvider interface provided by NCache. The class implementing this interface gets the notification requests to load the data from the master datasource if its not available in the cache. Thus, the class needs to include the logic for loading the data from the datasource to the cache.
Following namespaces are required in your project for using Read-Thru provider:
using Alachisoft.NCache.Web.Caching;
using Alachisoft.NCache.Runtime.DatasourceProviders;
using Alachisoft.NCache.Runtime;
Read-Through Interfaces:
In order to use Read-Thru cache provider in your application, implement the following methods:
public void Start(System.Collections.IDictionary parameters);
public void Stop();
public void LoadFromSource(string key, out ProviderCacheItem cacheItem);
public Dictionary <string, ProviderCacheItem> LoadFromSource(string [] keys);
See Also
Implementing IReadThruProvider


Topic: Enabling Read-through Cache Provider

Enabling Read-through Cache Provider

NOTE: This feature is not available in NCache Express and Professional edition.
Configuring Read-Through Provider:
To enable Read-through caching, you need to implement IReadThruProvider and specify them in the cache properties. NCache Manager provides an interface for specifying them in the cache properties. For enabling read-through caching, follow the steps given below:
  1. From the start programs, launch NCache Manager.
  2. Open the project containing cache or cluster for which you want to configure the read-through caching.
  3. From the explorer, select the cache or cluster. In the right pane, cluster/cache view will be opened.
  4. From the view, select the Backing Source tab .
  5. Check the Enable Read-Through on this cache check box.
  6. Click Add button and browse the Assembly that contains the class implementing IReadThruProvider and then select class name from the list. The Assembly implementing IReadThruProvider must contain the reference of Alachisoft.NCache.Runtime.dll.
  7. Deploy appropriate assemblies to the cache servers using Deploy Provider button from same tab view.
  8. You can provide some additional parameters (like datasource file name) if required from the same screen.
Deployment:
For deployment details, kindly visit Deploying Read-Thru/Write-Thru provider page.
See Also
Implementing IReadThruProvider


Topic: Implementing IReadThruProvider

Implementing IReadThruProvider

NOTE: This feature is not available in NCache Express and Professional edition.
Implementing Interface:
Following is a list of methods needs to be defined by the classes implementing interface and a brief description of their purpose.
  • void Start(IDictionary parameters);
This method is responsible for performing tasks like allocating resources, acquiring connections etc. When cache is initialized and read-through caching is enabled, it calls Start method to notify the client that cache has initialized and you may initialize your data source too. The parameters passed as an argument contains all the parameters (if any) that were specified using NCache Manager cache/cluster views. These parameters can be utilized in many ways. For example, connection string of a datasource can be specified as a parameter through NCache Manager. Whenever cache will be initialized, the connection to the datasource could be made using this connection string passed as an argument. Thus, it provides a flexible way to change the datasource dynamically without requiring code changes.
public void Start(System.Collections.IDictionary parameters)
{
String connectionString = "Data Source=Localhost//SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True" ;
connection = new SqlConnection (connectionString);
connection.Open();
}
  • void Stop();
This method is responsible for performing tasks like releasing the resources etc. When Cache is stopped it calls Stop() method to notify the client that the cache has stopped now and you can free the resources related to your datasource.
public void Stop()
{
connection.Close();
}
  • void LoadFromSource(string key, out Alachisoft.NCache.Runtime.Caching.ProviderCacheItem cacheItem);
This method should contain logic to load an object from the master datasource. Whenever a request for an item comes but item is not found in the cache, then cache calls the LoadFromSource method and passes the 'key' as an argument. It is the responsibility of a cache to return the object against the passed key from the master datasource. The other argument of this method is ProviderCacheItem.
ProviderCacheItem contains the following parameters:
  • AbsoluteExpiration/SlidingExpiration value for an item,
  • Dependency for cached item,
  • Group/SubGroup identifier for a cached item,
  • ItemPriority for an item to be evicted,
  • ResyncItemOnExpiration is a Boolean parameter, used for automatic reload of a cache item if required. If ResyncItemOnExpiration is enabled and cache item expires, it passes keys of the expired items to reload fresh items from the master datasource. In this way the required item remains in cache with updated values,
  • ResyncProviderName is a provider name which reloads the item,
  • Tags for a cached item and
  • Value for a cached item.
public void LoadFromSource(string key, out ProviderCacheItem provideritem)
{
SqlCommand command = new SqlCommand("SELECT * FROM Products WHERE ProductName = " + key);
SqlDataReader reader = command.ExecuteReader();
reader.Read();
Product product = new Product();
product.ProductName = reader["ProductName"];
product.Supplier = reader["Supplier"];
product.Categories = reader["Categories"];
ProviderCacheItem provideritem = new ProviderCacheItem(product);
provideritem.Dependency = new KeyDependency("Product:1");
provideritem.AbsoluteExpiration = System.DateTime.Now.AddSeconds(30);
provideritem.Value = product;
}
  • Dictionary<string, ProviderCacheItem> LoadFromSource(string[] keys);
This method should contain logic to load array of objects from the master datasource. Whenever a request for items comes but items are not present in the cache, then cache calls LoadFromSource method and passes array of keys as argument.
public Dictionary<string, ProviderCacheItem> LoadFromSource(string[] keys)
{
Dictionary<string, ProviderCacheItem> source = new Dictionary<string, ProviderCacheItem>();
for (int i = 0; i < keys.Length; i++)
{
SqlCommand command = new SqlCommand("SELECT * FROM Products WHERE ProductName = " + keys[i]);
SqlDataReader reader = command.ExecuteReader();
reader.Read();
Product product = new Product();
product.ProductName = reader["ProductName"];
product.Supplier = reader["Supplier"];
product.Categories = reader["Categories"];
provideritem = new ProviderCacheItem(product);
provideritem.Dependency = new KeyDependency("Product:1");
provideritem.AbsoluteExpiration = System.DateTime.Now.AddSeconds(30);
source.Add(keys[i], provideritem));
}
}
Using Read-Thru Provider:
After implementing the above interface, you can make direct calls to NCache to get required items. If NCache does not have already loaded the items, it will use "LoadFromSource" method in specified data access class to load items from datasource. The code to access the cache should look like;
Cache _cache = NCache.InitializeCache("myreplicatedcache");
object product = _cache.Get("ALFKI", "XmlReadThruProvider", DSReadOption.ReadThru);
If you do not want to give the provider name in the API, you can provide it in client.ncconf. If provider name is not provided in both API and client.ncconf, default provider will automatically be used.
<cache id = "myreplicatedcache" client-cache-id = "" default-readthru-provider = "XmlReadThruProvider" default-writethru-provider = "XmlWriteThruProvider">
<server name = "20.200.20.5">
</cache>
NCache logs the warnings in Application event log in case of an exception during loading the assemblies.
See Also
SqlCacheDependency | Enabling Read-through Caching


Topic: Write-through Cache Provider

Write-through Cache Provider

NOTE: This feature is not available in NCache Express and Professional edition.
Namespace:
For enabling Write-through caching, you need reference of following assembly in your application:
Alachisoft.NCache.Runtime.dll
This assembly contains class implementing Alachisoft.NCache.Runtime.DatasourceProviders.IWriteThruProvider interface provided by NCache. The class implementing this interface gets notification requests to save data back to the master datasource whenever new data is added to the cache. Thus, the class needs to include the logic for writing data from cache to the master datasource.
Following namespaces are required in your project for using Write-Thru provider:
using Alachisoft.NCache.Web.Caching;
using Alachisoft.NCache.Runtime.DatasourceProviders;
using Alachisoft.NCache.Runtime;
Write-Through Interfaces:
In order to use Write-Thru/Write-Behind provider in your application, implement the following methods:
public void Start(System.Collections. IDictionary parameters);
public void Stop();
public bool AddToSource(string key, object value);
public System.Collections.Hashtable AddToSource(string[] keys, object[] vals);
public bool UpdateSource(string key, object value);
public System.Collections.Hashtable UpdateSource( string [] keys, object [] vals);
public bool RemoveFromSource(string key);
public System.Collections.Hashtable RemoveFromSource(string[] keys);
public bool Clear();
See Also
Implementing IReadThruProvider


Topic: Enabling Write-through Cache Provider

Enabling Write-through Cache Provider

NOTE: This feature is not available in NCache Express and Professional edition.
Configuring Write-Through Provider:
To enable Write-through caching, you need to implement IWriteThruProvider and specify them in the cache properties. NCache Manager provides an interface for specifying them in the cache properties. For enabling write-through caching, follow these steps:
  1. From the start programs, launch NCache Manager.
  2. Open the project containing cache or cluster for which you want to configure the write-through caching.
  3. From the explorer, select the cache or cluster. In the right pane, cluster/cache view will be opened.
  4. From the view, select the Backing Source tab .
  5. You can provide some additional parameters (like datasource file name) if required from the same screen.
  6. For enabling Write-through caching, check the Enable Write-Through on this cache check box.
  7. Click Add button and browse the Assembly that contains the class implementing IWriteThruProvider and then select class name from the list.
  8. The Assembly implementing IWriteThruProvider must contain the reference of Alachisoft.NCache.Runtime.dll.
  9. Deploy appropriate assemblies to the cache servers using Deploy Provider button from same tab view.
  10. For enabling Write-Behind caching, check the checkbox under Write-Behind column.
Deployment:
For deployment details, kindly visit Deploying Read-Thru/Write-Thru provider page.
See Also
Configure Clustered Cache | Implementing IWriteThruProvider


Topic: Implementing IWriteThruProvider

Implementing IWriteThruProvider

NOTE: This feature is not available in NCache Express and Professional edition.
Implementing Interface:
Following is a list of methods needs to be defined by the class implementing interface and a brief description of their purpose.
  • void Start(IDictionary parameters);
This method is responsible for performing tasks like allocating resources, acquiring connections etc. When the cache is initialized and read-through caching is enabled, it calls Start method to notify the client that cache has initialized and you might initialize your data source too. The parameters passed as an argument contains all the parameters (if any) that were specified using NCache Manager cache/cluster views. These parameters can be utilized in many ways. For example, connection string of a datasource can be specified as a parameter through NCache Manager. Whenever cache will be initialized, the connection to the datasource could be made using this connection string passed as an argument. Thus, it provides a flexible way to change the datasource dynamically without requiring code changes.
public void Start(System.Collections. IDictionary parameters)
{
String connectionString = "Data Source=Localhost//SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True" ;
connection = new SqlConnection (connectionString);
connection.Open();
}
  • void Stop();
This method is responsible for performing tasks like releasing the resources etc. When Cache is stopped it calls Stop() method to notify the client that the cache has stopped now and you can free the resources related to your datasource.
public void Stop()
{
connection.Close();
}
  • bool AddToSource(string key, object value);
This method is responsible for adding an object to the datasource. Both the key and the value are passed as parameters. Object will not be added to cache if it fails to add in the data source.
public bool AddToSource(string key, object value)
{
Products product = ( Products )values;
SqlCommand command = new SqlCommand ( "INSERT INTO Products values " + "('" + keys + "'," + product.SupplierID + "," + product.CategoryID + ",null,null,null,null, null, 1, connection " );
command.ExecuteReader();
}
  • Hashtable AddToSource(string[] keys, object[] vals);
This method is responsible for adding array of objects to the datasource. Arrays of keys and values are passed as parameters. Objects that fail to add, will not be added to the data source.
public System.Collections.Hashtable AddToSource(string[] keys, object[] vals)
{
for (int i = 0; i < keys.Length; i++)
{
Products product = (Products)vals[i];
SqlCommand command = new SqlCommand("INSERT INTO Products values " + "('" + keys[i] + "'," + product.Supplier + "," + product.Category + ",null,null,null,null, null, 1, connection ");
command.ExecuteReader();
}
}
  • bool UpdateSource(string key, object val);
This method is responsible for updating an object in the datasource. Both, keys and values are passed as parameters. Object will not be updated in cache if it fails to update in the data source.
public bool UpdateSource( string key, object value)
{
Product product = ( Product )vals;
SqlCommand command = new SqlCommand ( "UPDATE Products SET ProductName = '" + product.ProductName + "' WHERE ProductName = '" + keys + "'" );
command.ExecuteReader();
return true;
}
  • Hashtable UpdateSource(string[] keys, object[] vals);
This method is responsible for updating array of objects in the datasource. Arrays of keys and values are passed as parameters. Object will not be updated in cache if it fails to update in the data source.
public System.Collections.Hashtable UpdateSource( string [] keys, object [] vals)
{
for ( int i = 0; i < keys.Length; i++)
{
Product product = (Product )vals[i];
SqlCommand command = new SqlCommand ( "UPDATE Products SET ProductName = '" + product.ProductName + "' WHERE ProductName = '" + keys[i] + "'" );
command.ExecuteReader();
}
}
  • bool RemoveFromSource(string key);
This method is responsible for removing an object from datasource. Key is passed as parameter. Object will not be removed from cache if it fails to remove from the data source.
public bool RemoveFromSource( string key)
{
SqlCommand command = new SqlCommand ( "DELETE FROM Products WHERE ProductName = " + keys);
command.ExecuteReader();
}
  • Hashtable RemoveFromSource(string[] keys);
This method is responsible for removing array of objects from datasource. Array of keys is passed as parameter. Object will not be removed from cache if it fails to remove from the data source.
public System.Collections.Hashtable RemoveFromSource(string[] keys)
{
for (int i = 0; i < keys.Length; i++)
{
SqlCommand command = new SqlCommand("DELETE FROM Products WHERE ProductName = " + keys[i]);
command.ExecuteReader();
}
}
  • bool Clear();
This method is responsible for clearing datasource. Cache will not be cleared if it fails to clear the data source.
public bool Clear()
{
SqlCommand command = new SqlCommand ( "DELETE * From Products" );
command.ExecuteReader();
}
Using Write-Thru Provider:
The code to access the cache should look like:
Cache mycache = NCache.InitializeCache("myreplicatedcache");
Product product = new Product();
CacheItem citem = new CacheItem (product);
cache.Add(textBox.Text, citem, DSWriteOption.WriteThru, null);
If you do not want to give provider name in API, you can provide it in client.ncconf. If provider name is not provided in both API and client.ncconf, default provider will automatically be used.
<cache id = "myreplicatedcache" client-cache-id = "" default-readthru-provider = "XmlReadThruProvider" default-writethru-provider = "XmlWriteThruProvider">
<server name = "20.200.20.5">
</cache>
NCache logs the warnings in Application event log in case of an exception during loading the assemblies.
See Also
SqlCacheDependency | Enabling Write-through Caching


Topic: Dynamic Compact Serialization

Dynamic Compact Serialization

NOTE: This feature is not available in NCache Express and Professional edition.
Its a process of producing a compact form of serialized object for performance improvement which results in faster network trips. As name illustrates, compact serialized file is compact in form of data and process. The idea behind the compact serialization is that every 'known type' (a known type is a type that is registered with the framework) is assigned a unique 2-bytes type handle by the framework, which lets the deserializer uniquely identify the 'known types'.
For example, suppose the framework assign a handle 0 to System.Int32. Then the serializer writes the 2-byte handle followed by 4 bytes of object value to the stream. Deserializer reads the handle, figures out the object type, and then creates and populates the object with its value. On other hand the native serialization writes the complete type information with object data. NCache Sophisticatedly over comes these issues of native sterilization in the following ways:
  • Here serialized object does not contain complete type information and assemblies. It only contains an object value and a unique 2-byte handle. This unique 2-byte handle is used as a reference to uniquely identify the type details while deserializing an object. In this way the size of the object reduces.
  • Compact serialization also avoids the reflection which also reduces the overhead.
  • The above two features reduces the IO operations.
  • As the object size decreases, it will automatically faster the network trips and eventually the cost decreases.
  • Small object size and fast network traffic increases the application performance.
For using Compact Serialization, you need to define a default public constructor (parameter less) in a compact serializable type and register that type with NCache Manager. NCache now supports Custom Generic Types. All generic types with any number of arguments can be serialized through compact serialization. If a client doesn't want to add generic types and its parameters though UI, then he has the option to add them through IGenericTypes class.
Note:
  • An object registered in Data Sharing can’t be registered in Compact Serialization at the same time.
In This Section
Registering compact types with NCache
Explains how you can register compact types with NCache.
See Also
Configure Cluster Cache
Helps you configure Clustered Cache.


Topic: Using Compact Types

Using Compact Types

NOTE: This feature is not available in NCache Express and Professional edition.
NCache has enhanced this feature to support dynamic compact serialization which allows users to use this feature without any code change. In earlier versions users had to implement the interfaces which are not required anymore in this version. To use Compact Serializable types with NCache Configure Cache with NCache Manager and then register your compact serializable types with NCache.
Registering Compact Serializable Types
You can register types one by one through 'Add Types' button. Perform the following steps to register your types with configured cache:
  • Stop the cache if it is running.
  • Click on the 'Compact Serialization' tab which will open up the following screen.
  • Click 'Add Types' button. A 'Select Compact Classes' dialog will appear.
  • Browse for the assembly file that contains the compact types by clicking the 'Browse' button as shown in the figure.
  • Select the classes you want to register with the cache from the loaded classes list.
  • Press 'Add Class' button to add the classes in the selected classes list.
  • Click 'Ok' button.
  • Newly added types will start appearing in the list box under the 'Compact Serialization' tab having Compact Type and Platform information.
  • 'Remove' button will delete the selected type from the registered types list.
  • This shows all the added types. Now arguments can be added with generic types by selecting specific type and then clicking on 'Add <T>' button.
Registering Generic Compact Types Through Generic Type Handler
This is the other way for registering generic compact types through "Generic Type Handler". With Generic Type Handler user can add all the Generic types at once by implementing our interface. This saves time and effort. Here is a sample code for this.
public class CustomGenericType<T,K,V>
{
}
public class SetGenerics: IGenericTypeProvider
{
Type[] types = new Type[6];
#region IGenericTypeProvider Members
Type[] IGenericTypeProvider.GetGenericTypes()
{
types[0]=typeof(Dictionary<string, Customer>);
types[1]=typeof(List<int>);
types[2]=typeof(CustomGenericType<Employee, Product, Customer>);
types[3]=typeof(CustomGenericType<Employee, Product, int>);
types[4]=typeof(CustomGenericType<Employee, string, byte>);
types[5]=typeof(CustomGenericType<string, Customer, bool>);
return types;
}
#endregion
}
For registering types follow these steps.
  • Click 'Generic Type Handler' button. A 'Select Compact Classes' dialog box will appear.
  • Browse for the assembly file that implements this interface and contains compact types by clicking the 'Browse' button as shown in the figure.
  • Click 'Ok' button. All the added types will be listed as shown blow.
  • Apply changes to the cache .


Topic: Data Sharing

Data Sharing

NOTE: This feature is not available in NCache Express and Professional edition.
NCache is providing both .net and java clients and there is a possibility of sharing same cache data among various clients either from same or different platforms. To make this sharing possible NCache has designed Data Sharing feature which not only allows the users to share cache content between various platforms but also provides the facility of class versioning within a same platform. Data sharing is a technique which dynamically serializes the objects at run time and makes it available for use in a very efficient way (in terms of time and cost).
Data sharing also supports class versioning as discussed above. Class can have various versions associated with it having unique identifiers. Every new change in a class is saved as a new version of the class. Through Data Sharing, different class versions can share cache contents among them at run time.
Data sharing is defined as the process of converting the state of an object (of any type) to some persistent state so that it can be understandable by clients from different platforms. This is the process which allows user to dynamically serialize an object to make it portable for different platforms/versions. In this way user can make persistent data state, so that it can be saved on a remote location and can be easily accessible for all clients.
The most common methods available in market for data sharing are XML based which is comparatively a slower solution. NCache introduces an efficient technique for Data Sharing that is binary serialization of objects at runtime.
Data Sharing is a very magnificent feature for all those clients who are using both NCache .net and NCache java editions but have some limitation as listed below:
  • Custom generic types are now supported but generic types can not be shared.
  • In case of multiple versions, user needs to define default version for Read-Thru/Write-Thru and CacheLoader.
  • An object registered in Data Sharing can’t be registered in Compact Serialization at the same time.
The following mapping should be considered while serializing a .Net/Java class:
Note: Users should only map Java attributes to .Net attributes incase of unsigned types.
In This Section
Configuring Data Sharing
Explains how you can register shared types with NCache.
See Also
Configure Cluster Cache
Helps you configure Clustered Cache.


Topic: Using Data Sharing

Using Data Sharing

NOTE: This feature is not available in NCache Express and Professional edition.
NCache introduces this feature to support data sharing between various versions of an object either from same platform or different platforms. To use Data Sharing with NCache, Configure cache with NCache Manager and then share your data among different clients.
Perform the following steps to make classes portable:
  • Stop the Cache if it is running.
  • Click on the 'Data Sharing' tab which will open up the following screen:
  • Click on 'Add Shared Types' button. A 'Select Data Sharing Classes' dialog will appear, as shown below.
  • You are required to specify Shared Type name in 'Name' field.
  • Browse for the assembly/jar which contains the class you want to share in cache. All the selected assemblies will be shown in the 'Loaded Classes' pane containing their respective classes.
  • Select the class you want to add in the selected classes list.
  • Use 'Add Class' button to add the selected classes.
  • All the selected classes will be listed in the 'List of selected Classes' pane with their Class Name, Version and Type.
  • Click 'OK' to continue.
  • All the classes contained in the selected 'Shared Type' will be shown here.
  • Bottom pane lists the 'Attributes Union List' and 'Selected Class Attributes' in their respective panes.
  • Class Attributes are already mapped with the Attribute Union List. This mapping is done at run time. You can see the class mapping by clicking on the particular class.
  • Here you can remap the attributes of the selected class with Attribute Union List using dropdown list.
  • You can add a new 'Shared Type' and a version to an existing Shared Type by right clicking on it.
  • Shared Type configurations can be import and export in XML file using "Import" and "Export" button. The configurations will be saved in XML file.
  • Once the mapping of attributes is done, apply changes to the cache .


Topic: Bridge Conflict Resolver

Bridge Conflict Resolver

NOTE: This feature is not available in NCache Express and Professional edition.
There are situations when a bridge tries to replicate an operation for a key that already exist in the cache. Conflict Resolver is introduced to resolve the conflict between existing operations and operation replicated from bridge to the cache. It decides which key to apply on the cache depending upon defined rules. By default the decision will be made on “Time Based” rule, which keeps the latest key on a cache. Users can also define their own rules for conflict resolver.
Following section describes the required steps to enable Bridge Conflict Resolver.
In this section
Using Bridge Conflict Resolver
Explains the API references and namespaces required for implementing Bridge Conflict Resolver.
Enabling Bridge Conflict Resolver
Describes how you can enable Bridge Conflict Resolver through NCache Manager in few simple steps.
Implementing IBridgeConflictResolver
Explains implementation of IBridgeConflictResolver and list of methods required to be defined by the class implementing this loader.
See Also
Configure Cluster Cache
Helps you configure Clustered Cache.


Topic: Using Bridge Conflict Resolver

Using Bridge Conflict Resolver

NOTE: This feature is not available in NCache Express and Professional edition.
Namespace:
For enabling Bridge Conflict Resolver, your program needs a reference to the assembly Alachisoft.NCache.Runtime.dll that contains interface Alachisoft.NCache.Runtime.Bridge.IBridgeConflictResolver provided by NCache. The class implementing this interface allows framework to resolve the conflict between existing operations and operation replicated from bridge to cache. Thus, the class needs to include the logic for Conflict Resolution between bridge and cache.
Following namespace is required in your project for using IBridgeConflictResolver:
using Alachisoft.NCache.Runtime.Bridge;
IBridgeConflictResolver Interface:
In order to use IBridgeConflictResolver in your application, implement the following interface:
public void Init(System.Collections.IDictionary parameters);
public ConflictResolution Resolve(ProviderBridgeItem oldEntry, ProviderBridgeItem newEntry);
public void Dispose();
See Also
Configure Cluster Cache | Implementing IBridgeConflictResolver


Topic: Enabling Bridge Conflict Resolver

Enabling Bridge Conflict Resolver

NOTE: This feature is not available in NCache Express and Professional edition.
Configuring Conflict Resolver in NCache Manager:
To enable Bridge Conflict Resolver, you need to implement IBridgeConflictResolver and specify it in the cache properties. NCache Manager provides an interface for specifying it under the cache properties. For Bridge Conflict Resolver, follow these steps:
  1. From the start programs, launch NCache Manager.
  2. Open the project containing cache or cluster for which you want to configure the Bridge Conflict Resolver.
  3. From the explorer, select the cache or cluster. In the right pane, cluster/cache view will be opened.
  4. From the view, select the Conflict Resolver tab .
  5. Check the Enable Conflict Resolver check box.
  6. Click Browse button and browse the Assembly that contains the class implementing IBridgeConflictResolver and then select class name from the list. The Assembly implementing IBridgeConflictResolver must contain the reference of Alachisoft.NCache.Runtime.dll.
  7. You can provide some additional parameters if required.
  8. Deploy the appropriate assemblies to the cache servers using the Deploy Conflict Resolver button on a same tab view.
Deployment:
For deployment details, kindly visit Deploying Conflict Resolver page.
See Also
Configure Cluster Cache | Implementing IBridgeConflictResolver


Topic: Implementing IBridgeConflictResolver Interface

Implementing IBridgeConflictResolver Interface

NOTE: This feature is not available in NCache Express and Professional edition.
Implementing IBridgeConflictResolver
Following is a list of methods needs to be defined by the class implementing interface and a brief description of their purpose.
  • void Init(IDictionary parameters);
This method performs tasks like allocating resources, acquiring connections etc. When the cache is initialized and finds that the Conflict Resolvers is enabled, it calls the Init method to notify the client that cache is initializing and you may initialize your conflict resolver too. The parameters passed as an argument contains all the parameters (if any) that were specified using NCache Manager cache/cluster views. These parameters can be utilized in many ways.
  • void Dispose();
This method performs tasks like releasing the resources etc. When Cache is stopped or the task is completed, it calls the Dispose() method to notify the client that you can free the resources related to your task.
  • ConflictResolution Resolve(ProviderBridgeItem oldEntry, ProviderBridgeItem newEntry);
This method should contain the logic to resolve the conflict occur while replicating an operation from bridge for a key that already exists in the cache. Whenever any conflict occurs, cache call BridgeConflictResolution to decides which operation to apply on the cache depending upon rules implemented in it. It takes two parameters/entries, both are of ProviderBridgeItem type. ProviderBridgeItem contains the following parameters:
  • BridgeItemVersion contains version of an item.
  • Key contains key of an item.
  • Value of an item contains value of an item.
  • BridgeItemOpCodes contains conflicted operation.
Using IBridgeConflictResolver:
Here is how your class should look like for IBridgeConflictResolver:
namespace BridgeConflictResolverImpl
{
public class BridgeConflictResolverImpl : IBridgeConflictResolver
{
private bool _enableLogging;
private TextWriter _textLogger;
#region IBridgeConflictResolver Members
public void Init(System.Collections.IDictionary parameters)
{
if (parameters.Contains("logging"))
{
_enableLogging = Convert.ToBoolean(parameters["logging"]);
}
if (_enableLogging)
{
_textLogger = new StreamWriter("bridgeResolverLog.txt");
_textLogger.WriteLine("Initializing bridg Conflict Resolver");
}
}
public ConflictResolution Resolve(ProviderBridgeItem oldEntry, ProviderBridgeItem newEntry)
{
ConflictResolution conflictResolution = new ConflictResolution();
switch (oldEntry.BridgeItemVersion)
{
case BridgeItemVersion.OLD:
{
conflictResolution.ResolutionAction = ResolutionAction.ReplaceWithNewEntry;
}
break;
case BridgeItemVersion.LATEST:
{
conflictResolution.ResolutionAction = ResolutionAction.KeepOldEntry;
}
break;
case BridgeItemVersion.SAME:
{
if (oldEntry.OpCode == BridgeItemOpCodes.Remove)
{
conflictResolution.ResolutionAction = ResolutionAction.ReplaceWithNewEntry;
}
else
{
conflictResolution.ResolutionAction = ResolutionAction.KeepOldEntry;
}
}
break;
}
if (_enableLogging)
_textLogger.WriteLine("Resolve Key {0} and decision taken {1}", oldEntry.Key, conflictResolution.ResolutionAction.ToString());
return conflictResolution;
}
public void Dispose()
{
if (_enableLogging)
{
_textLogger.WriteLine("Closing logger");
_textLogger.Close();
}
}
#endregion
}
}
NCache logs the warnings in Application event log in case of an exception during loading the assemblies.
See Also
Enabling Bridge Conflict Resolver


Topic: Custom Dependency

Custom Dependency

NOTE: This feature is not available in NCache Express and Professional edition.
You can have your own custom dependencies. In this way, you can expire items from the cache in a number of flexible ways where your own expiration logic meets your business requirements. NCache provides an abstract class ExtensibleDependency that is the base for all the dependencies. All you need to do is to inherit your dependency class from this class and override its HasChanged property. The following sample code creates a new dependency. The dependency polls the Northwind database and expires all the Products for which units in stock are less than 100.
using Alachisoft.NCache.Runtime.Dependencies;
[Serializable]
public class CustomDependency : ExtensibleDependency
{
private string _connString;
private int _productID;
public override bool Initialize() { return false; }
public CustomDependency(int productID, string connString)
{
_connString = connString;
_productID = productID;
}
internal bool DetermineExpiration()
{
if (GetAvailableUnits(_productID) < 100)
return true;
return false;
}
internal int GetAvailableUnits(int productID)
{
OleDbDataReader reader = null;
OleDbConnection connection = new OleDbConnection(_connString);
connection.Open();
int availableUnits = -1;
try
{
OleDbCommand cmd = connection.CreateCommand();
cmd.CommandText = String.Format(CultureInfo.InvariantCulture,
"Select UnitsInStock From Products" +
" where ProductID = {0}", productID);
reader = cmd.ExecuteReader();
if (reader.Read())
{
availableUnits = Convert.ToInt32(reader["UnitsInStock"].ToString());
}
reader.Close();
return availableUnits;
}
catch (Exception)
{
return availableUnits;
}
}
public override bool HasChanged
{
get
{
return DetermineExpiration();
}
}
}
Using Custom Dependency:
Here is how CustomDependency will be used.
using Alachisoft.NCache.Web.Caching;
Cache _cache = NCache.InitializeCache("myCache");
string connString = "Provider=SQLOLEDB.1;Data Source=localhost;User ID=sa;password=;Initial Catalog=Northwind";
CustomDependency hint = new CustomDependency(123, connString);
_cache.Add("Product:1001", "Value", new CacheDependency(hint), Cache.NoAbsoluteExpiration, new TimeSpan(0, 0, 10), Alachisoft.NCache.Runtime.CacheItemPriority.Default);
See Also
Using Key Dependency | Using File Dependency | Using CacheSyncDependency | Using SqlCacheDependency | Using DbCacheDependency


Topic: Client Side ASP.NET Features

Client Side ASP.NET Features

This tutorial is a practical guide for programmers who want to utilize powerful features of ASP.NET with NCache to create high performance and scalable .NET applications. This includes working examples and code snippets to utilize various features of NCache efficiently.
In This Section
ASP.NET Sessions
Explains maintaining and synchronizing session state throughout a server farm using NCache Clustered Session.
ASP.NET Output Cache
Shows how to use output caching to cache the HTML output of dynamic requests to ASP.NET pages, hence speeding up the overall response process.
Content Optimization
NCache provides View State Caching and Java Script Minification support for content optimization.


Topic: ASP.NET Sessions

Clustered Session

You can quickly use clustered sessions in your existing ASP.NET applications without any code change and can immediately see a performance boost in your application. NCache provides high performance in-memory ASP.NET session clustering for web farms that is faster and more scalable than storing them in a database. It is faster because sessions are kept in memory and closer to the ASP.NET application. And, it is more scalable because sessions can be distributed to multiple servers in the farm that can better handle larger load than a database server.
With NCache, you can eliminate the need to use sticky sessions in your load balancer. This significantly improves your application scalability. NCache provides powerful dynamic clustering of sessions. You can replicate or distribute/partition sessions either locally on multiple web servers or on multiple dedicated session caching servers. NCache offers a rich set of features to grow you session clustering from small to large web farms.
In This Section
Using ASP.NET 2.0+ Sessions
Presents reading and writing ASP.NET session data from and to an NCache cache through Session State Store Provider.
Using sessions in geographically separated web farms
Describes using Location Affinity feature to maintain session state across different web farms on geographically separated locations.
Using Session Locking in NCache Session Store Provider
Describes how locking works in NCache Session Store Provider.


Topic: Store ASP.NET 2.0+ Sessions

Session State Store Provider

NCache Session State Provider is a custom SessionStateStoreProviderBase implementation for an ASP.NET application. This implementation reads and writes ASP.NET session data from and to the cache. This allows you to transparently save and retrieve ASP.NET session-state objects within a webfarm. SSP is a better approach than HttpModule for implementing the ASP.NET sessions. It is flexible and more reliable than HttpModule.
Note: This feature is available only for .NET Framework version 2.0 and later.
Configuration Steps
Please follow these steps for enabling NCache Session Store Provider to transparently save and retrieve ASP.NET session state.
1. Edit your application's web.config file and modify the <sessionState> section as given below. Place the following code under <System.Web> tag.
<assemblies>
<add assembly = "Alachisoft.NCache.SessionStoreProvider,
Version=x.x.x.x, Culture=neutral,
PublicKeyToken=CFF5926ED6A53769"/>
</assemblies>
<sessionState cookieless = "false"
regenerateExpiredSessionId = "true"
mode = "Custom"
customProvider = "NCacheSessionProvider"
timeout = "10">
<providers>
<add name = "NCacheSessionProvider"
type = "Alachisoft.NCache.Web.SessionState.NSessionStoreProvider"
sessionAppId = "1234"
cacheName = "myCache"
enableSessionLocking = "false"
sessionLockingRetry = "-1"
writeExceptionsToEventLog = "false"
enableLogs = "false"
enableDetailLogs = "false"
exceptionsEnabled = "false"/>
</providers>
</sessionState>
Note:
Replace version “x.x.x.x” with the actual NCache version that you have.
Following is the description of different key-value pairs specified above:
  • sessionAppId : Optional string attribute. Specifies an identifier to make sure that session id remains unique in case multiple applications are using same cache. Application id should be same for an application in a web farm. If no app id is specified nothing will be concatenated with session id.
  • cacheName: Required string attribute. Specifies the name of the cache to be used for caching session. If no cache name is specified, a configuration exception will be thrown.
  • enableSessionLocking: Optional Boolean attribute. If this flag is set, NCache Session Store Provider exclusively locks the session-store item for which multiple concurrent requests are made. The default is false. Read Session Locking in NCache Session Store Provider
  • sessionLockingRetry: Optional Integer attribute. If enableSessionLocking is true and this integer is not less than 0, NCache Session Store Provider will return empty session after sessionLockingRetry number of retries to acquire a lock. The default is -1. Read Session Locking in NCache Session Store Provider
  • writeExceptionsToEventLog : Optional Boolean attribute. If this flag is set, all the exceptions from cache API are written to event logs. The default is false.
  • enableLogs: Optional Boolean attribute. When this flag is set, store provider logs all error information. The log files are created in "$ncache-install/log-files/SessionStoreProvider/". The default is false.
  • enableDetailLogs: Optional Boolean attribute. When this flag is set, store provider logs all debugging information. The log files are created in "$ncache-install/log-files/SessionStoreProvider/". The default is false.
  • exceptionsEnabled: Optional Boolean attribute. Specifies whether exceptions from cache API are propagated to the page output. Setting this flag is especially helpful during development phase of application since exceptions provide more information about the specific causes of failure. The default is false.
2. Add <machinekey> entry under <system.web> section in web.config. It is required to generate ASP.NET session IDs in the same manner on all nodes. You can use the genmackeys utility available with NCache installation to generate the keys.
<machineKey
validationKey = "A01D6E0D1A5D2A22E0854CA612FE5C5EC4AECF24"
decryptionKey = "ACD8EBF87C4C8937"
validation = "SHA1"/>
See Also
Session Locking in NCache Session Store Provider | Using Session State Module | Using sessions in geographically separated web farms


Topic: Session Locking in NCache Session Store Provider

Session Locking in NCache Session Store Provider

ASP.NET applications are inherently multithreaded. Because requests which arrive in parallel are processed on concurrent threads drawn from a thread pool, it is possible that two or more requests targeting the same session will execute at the same time. (The classic example is when a page contains two frames, each targeting a different ASPX in the same application, causing the browser to submit overlapping requests for two pages.) To avoid data collisions and erratic behavior, the NCache Session Store Provider provides the functionality that exclusively locks the session-store item for a particular session when it begins processing the first request by calling GetItemExclusive method, causing other requests targeting the same session to wait for the lock to come free. When the request completes, the lock is released during the call to the SetAndReleaseItemExclusive method.
Because there's no harm in allowing concurrent requests to perform overlapping reads, the lock is typically implemented as a reader/writer lock-that is, one that allows any number of threads to read a session but that prevents overlapping reads and writes as well as overlapping writes.
If a locked session is encountered during the call to either GetItemExclusive or GetItem method, it will re-request the session data at half second interval until either the lock is released or the amount of time specified in the ExecutionTimeout property has elapsed. If the request times out, SessionStateModule calls the ReleaseItemExclusive method to free the session-store data and request the session-store data at that time.
However, this way of releasing the session-store data may lower the performance of applications that have huge amount of requests for the same session data. It is possible that a huge number of requests are waiting for the same session data to get free and any of them being able to acquire the next lock. To avoid this situation, NCache gives its users an option to specify the number of retries that SessionStateModule should make calls to either GetItemExclusive or GetItem method before returning an empty session. This number of retries can be configured by specifying "sessionLockingRetry" value in the NCache Session Store Provider section. By default Session Locking retries is disabled (i.e set to -1) and SessionStateModule will re-request the session data at half second interval until either the lock is released or the amount of time specified in the ExecutionTimeout property has elapsed.
See Also
Using Session State Module | Using Session State Store Provider | Using sessions in geographically separated web farms


Topic: Sessions in geographically separated web farms

Sessions in geographically separated web farms

NCache provides ability to manage ASP.NET session state across multiple web farms. This improves high availability and fault tolerance by allowing web farms to spread across multiple geographic regions. To achieve this, NCache provides Location Affinity feature for sessions.
To understand Location Affinity feature for sessions, consider the following scenario. Suppose that you have created multiple clustered caches, one for each geographical location. Each clustered cache has its own set of clients as a web farm. These clients will add, insert, and get sessions mostly from their own clustered cache. However, some time a user might be sent to the web farm of another geographical location. Now, NCache allows the user to access the same session, based on the original session id.
This is further explained with the help of following diagram:
This figure demonstrates the following ASP.NET session state scenario:
  1. A client makes a request that passes through the Global Load Balancer.
  2. Global Load Balancer passes the request to a Local Load Balancer based on current system load. Suppose, the session request is passed to Local Load Balancer 1.
  3. The Local Load Balancer1 passes the request to the server within a web farm, based on system load. Suppose request is passed to Web Server1. Once the request reaches Web Server1, CustomSessionIDManager adds a unique prefix for this ASP.NET session.
  4. After the server establishes the ASP.NET session, current session state is saved in primary cache for this web farm, in this case Replicated Cache1.
  5. When Global Load Balancer routes the same client to Web Farm2, web server analyzes the session prefix. With the help of this prefix it fetches the session from Clustered Cache1 even though it belongs to Web Farm1.
Note: This optimization is possible only in .Net 2.0 and later versions where a CustomSessionIDManager can add sid-prefix to session id. This sid-prefix helps in directing client to the cache holding the session.
To use Location Affinity, you have to specify one 'primary' and one or more 'secondary' caches for each web farm in web.config. The primary cache will be used for all local traffic and all secondary caches will be used when a user goes to different geography.
Enable Location Affinity for SessionStoreProvider
  • Add following section in web.config.
    <configSections>
    <section name = "ncache" type = "Alachisoft.NCache.Web.SessionStateManagement.NCacheSection,
    Alachisoft.NCache.SessionStateManagement, Version=x.x.x.x, Culture=neutral, PublicKeyToken=CFF5926ED6A53769"/>
    </configSections>
    <ncache>
    <sessionLocation>
    <primaryCache id = "London_Cache" sid-prefix = "LDC"/>
    <secondaryCache id = "NewYork_Cache " sid-prefix = "NYC"/>
    <secondaryCache id = "Tokyo_Cache" sid-prefix = "TKC"/>
    </sessionLocation>
    </ncache>
    Note:
  • Replace version “x.x.x.x” with the actual NCache version that you have.
  • The sid-prefix is a unique identifier that is appended by custom session-ID manager in the beginning of session-ID. sid-prefix length must be equal to 4.
  • Enable custom session-ID manager using the sessionIDManagerType attribute of the sessionState element in web.config.
    <sessionState cookieless = "false" regenerateExpiredSessionId = "true" mode = "Custom" customProvider = "NCacheSessionProvider" timeout = "60" sessionIDManagerType = "Alachisoft.NCache.Web.SessionStateManagement.CustomSessionIdManager, Alachisoft.NCache.SessionStateManagement">
    <providers>
    <add name = "NCacheSessionProvider" type = "Alachisoft.NCache.Web.SessionState.NSessionStoreProvider"
    sessionAppId = "1234" cacheName = "myCache" writeExceptionsToEventLog = "false" asyncSession = "false"
    enableLogs = "false"/>
    </providers>
    </sessionState>
    Note:
  • When Location Affinity is enabled, "CacheName" specified in <providers> section of web.config will be ignored.
  • Cookieless sessions are not supported.
See Also
Using Session State Module | Using Session State Store Provider


Topic: NCache Session State Module

NCache Session State Module

NCache Session State Module allows you to transparently save and retrieve ASP.NET session-state objects within a webfarm. As compared to ASP.NET Session State Module which is centralized in nature, NCache Session State Module is truly distributed. It benefits from clustered caching and thus, it implicitly avoids single point of failure. Also, when running cache as InProc, no extra cost is involved in retrieving session-state objects.
Configuration Steps
Please follow these steps for enabling NCache Session State Module to transparently save and retrieve ASP.NET session-state objects.
1. Edit your application's web.config file to add <appSettings> entry under <configuration> section.
<appSettings><add key = "CacheName" value = "myReplicatedCache"/>
<add key = "sessionAppId" value = "1234"/>
<add key = "exceptionsEnabled" value = "true"/>
<add key = "enableLogs" value = "false" />
<add key = "enableDetailLogs" value = "false"/>
<add key = "clearASPSession" value = "false"/>
<add key = "writeExceptionsToEventLog" value = "false"/>
</appSettings>
Following is the description of different key-value pairs specified above:
  • CacheName: Required string attribute. Specifies the name of the cache to be used for caching session. If no cache name is specified a configuration exception will be thrown.
  • sessionAppId : Optional string attribute. Specifies an identifier to make sure that session id remains unique in case multiple applications are using same cache. Application id should be same for an application in a web farm. If no app id is specified nothing will be concatenated with session id.
  • exceptionsEnabled: Optional Boolean attribute. Specifies whether exceptions from cache API are propagated to the page output. Setting this flag is especially helpful during development phase of application since exceptions provide more information about the specific causes of failure. By default it is false.
  • enableLogs: Optional Boolean attribute. When this flag is set, http module logs all error information. The log files are created in "$ncache-install/log-files/httpmodule/". The default is false.
  • enableDetailLogs: Optional Boolean attribute. When this flag is set, http module logs all debugging information. The log files are created in "$ncache-install/log-files/httpmodule/". The default is false.
  • clearASPSession: Optional Boolean attribute. If your website contains multiple App Domains and you allow user to go from one App to another either through Response.Redirect(url, false) or by providing a link on one of the pages, you must use this property. If this flag is not set, the regular ASP session store will also save session information. And, in case of InProc sessions, web server will start consuming memory. By default it is true. There are two possible scenarios when user is using custom module along with NCache:
Scenario 1:
If custom module is loaded before NCache's, custom module calls our Load function to load session from cache. In this case NCache will not load session information again. So it is custom http module responsibility to clear session before calling Load function.
Scenario 2:
If custom module is loaded after NCache's, clearAspSession should be set to false because NCache will clear session after updating the cache and custom module will get empty session. However custom module may have to clear session and then Load from cache again after NCache's module has already loaded session from cache.
  • writeExceptionsToEventLog : Optional Boolean attribute. If this flag is set, all the exceptions from cache API are written to event logs. The default is false.
2. Add <httpmodules> entry under <system.web> section in web.config.
<httpModules>
<add name = "NCacheWebSessionState" type = "Alachisoft.NCache.Web.SessionState.NSessionStateModule,
Alachisoft.NCache.SessionState, Version=x.x.x.x, Culture=neutral, PublicKeyToken=cff5926ed6a53769"/>
</httpModules>
Note: Replace version “x.x.x.x” with the actual NCache version that you have.
3. Add <machinekey> entry under <system.web> section in web.config. It is required to generate ASP.NET session IDs in the same manner on all nodes.
<machineKey validationKey = "A01D6E0D1A5D2A22E0854CA612FE5C5EC4AECF24" decryptionKey = "ACD8EBF87C4C8937" validation = "SHA1"/>
Special Considerations when Storing ASP.NET 1.1 Sessions in NCache
Session.Redirect(url, false)
You must specify "false" as the second argument in all your Session.Redirect calls. Otherwise, the new page will not see any changes which you have made to Session in the current page. The reason is that if you don't specify "false", ASP.NET terminates the response and does not invoke NSessionStateModule (NCache's Session State Module) for saving Session into the cache. And, when the new page retrieves Session from the cache, it gets the older copy which does not have your changes.
Session.Abandon()
If you make Session.Abandon() call, it does not delete the session from the cache in .NET 1.1. So, the preferred way of abandoning the session is by calling NSessionStateModule's Abandon call. However, you'll first have to get a handle to this NCache Session State Module from HttpApplication object. Below is sample code:
using Alachisoft.NCache.Web.SessionState;
//you may write the following code under logout button
NSessionStateModule sm = Application["NSessionStateModule"] as NSessionStateModule;
sm.Abandon(Session);
The reason for doing this, is that if you simply call Session.Abandon(), there is no way ASP.NET provides for NSessionStateModule to find this out. Therefore, it cannot take appropriate action.
Please note that this is not a problem in .NET 2.0 or later versions where you're able to use SSP.
Using Session in your own custom HttpModules
NCache provides an HttpModule (NSessionStateModule) to handle Session storage in the cache. This NSessionStateModul is called at AcquireRequestState and ReleaseRequestState events. However, if you've also developed an HttpModule and your event handlers are called before NSessionStateModule's event handlers are called, then your code is not likely to see the correct data in the Session object.
If your HttpModule is called before AcquireRequestState event handler of NSessionStateModule is called, then you'll see an empty session. And, to handle this situation, you'll need to use the following code at the beginning of your HttpModule's event handler:
using Alachisoft.NCache.Web.SessionState;
//you may write the following code under logout button
NSessionStateModule sm = Application["NSessionStateModule"] as NSessionStateModule;
sm.Load(HttpContext);
If your code is making changes to the Session object and wants to make sure these changes are seen by other ASP.NET pages, then you should call NSessionStateModule.Update(HttpContext) in the following way:
using Alachisoft.NCache.Web.SessionState;
//you may write the following code under logout button
NSessionStateModule sm = Application["NSessionStateModule"] as NSessionStateModule;
sm.Update(HttpContext);
This will ensure that everything is working properly.
Using Session.Clear()
Please note that if you're using Session.Clear(), NCache will remove this Session from the cache. Upon trying to save the Session content, NCache checks to see if Session is empty (Session.Count == 0). If that is the case, then it calls a cache.Remove(…).
See Also
Using Session State Store Provider | Using sessions in geographically separated web farms


Topic: ASP.NET Output Cache

Using Output Cache

NOTE: This feature is not available in NCache Express and Professional edition.
NCache provides extremely fast and reliable output caching feature for ASP.NET applications running in web farm environment, where regular output caching fails. Once a page is rendered by any of the web server in the web farm, it is available to all other servers due to clustered cache created by NCache. Your cached pages are highly available because clustered cache gives no single point of failure.
Steps to plug-in NOutputCache to your existing web applications are as follows:
  1. Register NOutputCache as the httpmodule inside <system.web> in web.config file.
    <httpModules>
    <add name = "Alachisoft.NCache.Web.NOutputCache" type = "Alachisoft.NCache.Web.NOutputCache.NOutputCache, Alachisoft.NCache.OutputCache, Version=x.x.x.x, Culture=neutral, PublicKeyToken=cff5926ed6a53769"/>
    </httpModules>
    Note: Replace version “x.x.x.x” with the actual NCache version that you have.
  2. Register 'ncache' configuration section in the <configSections> of the web.config as follows:
    <configSections>
    <section name = "ncache"
    type = "Alachisoft.NCache.Web.NOutputCache.NCacheSection, Alachisoft.NCache.OutputCache, Version=x.x.x.x, Culture=neutral, PublicKeyToken=cff5926ed6a53769"/>
    </configSections>
  3. Then add actual <ncache> section in <configuration> section of web.config holding information of pages to be cached.
    <ncache>
    <outputCacheSettings cacheName = "myReplicatedCache" clientCacheName = "" exceptionsEnabled = "true" logsEnabled = "false" enableDetailLogs = " false" enableClientCacheSync = "false">
    <outputCachePages>
    <add name = "/main.aspx" enabled = "true" requestType = "post" duration = "20" varyByParam = "cbxCustomerName" varyByHeader = "Connection" varyByCustom = "browser"/>
    </outputCachePages>
    </outputCacheSettings>
    </ncache>
    <ncache> section holds the following configurable options:
  • outputCacheSettings: Lets you specify cache settings for output caching.
  • cacheName: Required string attribute. Specifies the name of the cache that you have configured through NCache Manager. Your application will use this cache for caching specified pages. If no cache name is specified, a configuration exception will be thrown.
  • clientCacheName: Optional string attribute. Specifies client cache name which will enable client cache feature of NCache.
  • exceptionsEnabled: Optional Boolean attribute. Specifies whether exceptions from cache API are propagated to the page output. Setting this flag is especially helpful during development phase of application since exceptions provide more information about the specific causes of failure. The default is false.
  • enableLogs: Optional Boolean attribute. When this flag is set, all important events are logged including exceptions, cache initialized, disposed, and session not found etc. The default is false.
  • enableDetailLogs: Optional Boolean attribute. When this flag is set, the information that is useful for debugging purposes will be included in logs. The default is false.
  • enableClientCacheSync: If client cache is specified and this option is set to 'true', output cache will use Cache Sync Dependency feature of NCache to synchronize both level1 and level2 caches. On the other hand, if client cache is specified and this option is set to 'false', output cache will synchronize the operations on both caches at its own. The default is false.
  • outputCachePages: Holds information of the pages to be cached. All the options below are page-specific.
  • name: Required string attribute. Specifies the name of the page to be cached. If no name is specified, a configuration exceptions will be thrown.
  • enabled: Optional Boolean attribute. Specifies whether caching for the specified page is enabled or not. The default is true.
  • requestType: Optional string attribute. It is type of request for which page will be cached. It can be 'get', 'post' or 'get/post'. If no request type is specified page will be cached for only 'get'.
  • duration: Required integer attribute. Specifies duration (in seconds) after which the page will be expired from cache and upon next request it will be re-executed and cached again. If no duration is specified, a configuration exception will be thrown
  • varyByParams: Optional string attribute. Different versions of page output will be cached for each request that arrives with a different parameter(s) value. varyByParam specifies these parameters. Provide multiple parameters in the form of comma separated string. To vary by all parameters, use ' '. If no string is specified, page caching will not vary by parameters.
  • varyByHeader: Optional string attribute. To vary page caching by http headers, provide comma separated headers. To vary by all headers, use ' '. If no string is specified, page caching will not vary by headers.
  • varybyCustom: Optional string attribute. Provide if you wish to vary page caching by custom values. You cannot specify multiple custom strings using comma, they will be treated as one variable. The only custom string provided by ASP.NET is 'browser'. If you wish to provide your own custom string, you must override GetVaryByCustomString() method in Global.asax.
See Also
ASP.NET Sessions


Topic: Content Optimization

Content Optimization

This section explains the following topics for content optimization.
In This Section
View State Caching
Describes view state caching and how NCache caches view state.
Java Script Minification
Describes java script minification and how NCache minify JavaScript and CSS.
View State Caching and Java Script Minification Plugin
Describes View State Caching and Java Script Minification Plugin.


Topic: View State Caching

View State Caching

All ASP.NET applications have to deal with View State which is becoming a performance overhead. ViewState caching helps you cache View State on web servers and send a much smaller payload to the user's browser containing only a unique ID for this ViewState. As a result, your page performance improves and your Asp.net application also scales much better.
Why Cache View State?
View State is an encrypted text string containing the state of web form controls and widgets and is sent to the user's browser to preserve the state across post-backs. For forms with lot of controls, DataGrid control, or some other complex controls, the View State can become quite large. Here are some reasons why you should consider caching the View State.
  • View State is large (tens of kb) on large forms & DataGrid.
  • Large View State slows down page download time.
  • Large View State slows down post-back request time.
  • Can cache View State on web servers & send only a token to user.
  • View State cache is distributed to all web servers in the farm.
How NCache Caches View State?
View State is included in the response of a web request as a hidden form field called __VIEWSTATE. On all page visits during the save view state stage, the Page class gathers the collective view state for all of the controls in its control hierarchy and serializes the state to a base-64 encoded string.
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNzg0MDMxMDA1D2QWAmYPZBYCZg9kFgQCAQ9kFgICBQ9kFgJmD2QWAgIBDxYCHhNQcm V2aW91c0NvbnRyb2xNb2RlCymIAU1pY3Jvc29mdC5TaGFyZVBvaW50LldlYkNvbnRyb2xzLlNQQ29udHJ vbE1vZGUsIE1pY3Jvc29mdC5TaGFyZVBvaW50LCBWZXJzaW9uPTEyLjAuMC4wLCBDdWx0dXJlPW5ldXRy YWwsIFB1YmxpY0tleVRva2VuPTcxZTliY2UxMTFlOTQyOWMBZAIDD2QWDgIBD2QWBgUmZ19lMzI3YTQwM F83ZDA1XzRlMjJfODM3Y19kOWQ1ZTc2YmY1M2IPD2RkZAUmZ18yNDQ3NmI4YV8xY2FlXzRmYTVfOTkxNl 8xYjIyZGYwNmMzZTQPZBYCZg8PZBYCHgVjbGFzcwUbbXMtc2J0YWJsZWFsdCBtcy1zYnRhYmxlLWV4ZAU mZ181NmIxMzIzMV9kYjllXzRlYTZfOTc5ZF9iYWZlNDk3MDkyOWUPZBYCAgEPZBYCAgEPPCsADQEADxYE HgtfIURhdGFCb3VuZGceC18hSXRlbUNvdW50Av////8PZGQCAw9kFgQCDQ9kFgJmD2QWBmYPFgIeBFRle HQFJjxzcGFuIHN0eWxlPSdwYWRkaW5nLWxlZnQ6M3B4Jz48L3NwYW4+ZAICDw8WBB8EBQdNeSBTaXRlHg tOYXZpZ2F0ZVVybAUlaHR0cDovL3Rlc3Q3Ojc3MC9fbGF5b3V0cy9NeVNpdGUuYXNweGRkAgQPFgIfBAU 5PHNwYW4gc3R5bGU9J3BhZGRpbmctbGVmdDo0cHg7cGFkZGluZy1yaWdodDozcHgnPnw8L3NwYW4+ZAIP D2QWAmYPZBYCAgMPFgIfBAUBfGQCCQ9kFgICAQ9kFgJmD2QWAgIBDw9kFgIfAQUYbXMtc2J0YWJsZSBtc y1zYnRhYmxlLWV4ZAILD2QWAgIDD2QWAmYPZBYEAgIPZBYIAgEPFgIeB1Zpc2libGVoZAIDDxYCHwZoZA IFDxYCHwZoZAIHD2QWAmYPDxYGHhxQcmV2aW91c0F1dGhvcmluZ0l0ZW1WZXJzaW9uBQIxNR4aUHJldml vdXNBdXRob3JpbmdJdGVtT3duZXIFATEeHFByZXZpb3VzQXV0aG9yaW5nQ29udHJvbE1vZGULKwQBZGQC Aw8PFgIeCUFjY2Vzc0tleQUBL2RkAg8PZBYCAgEPZBYCZg9kFgICAw9kFgICAQ9kFgQCAQ8PFgIfBmhkF hwCAQ8PFgIfBmhkZAIDDxYCHwZoZAIFDw8WAh8GaGRkAgcPFgIfBmhkAgkPDxYCHwZoZGQCCw8PFgIfBm hkZAINDw8WAh8GaGRkAg8PDxYEHgdFbmFibGVkaB8GaGRkAhEPDxYCHwZoZGQCEw8PFgQfC2gfBmhkZAI VDw8WAh8GaGRkAhcPFgIfBmhkAhkPFgIfBmhkAhsPDxYCHwZnZGQCAw9kFgICAw8PFgQeGHBlcnNpc3Rl ZEVycm9yQWN0aW9uVHJlZWQeG3BlcnNpc3RlZEVycm9yQWN0aW9uVHJlZUlkc2RkZAIlD2QWAgIHDw8WA h8GaGQWAgIFD2QWAgIBDzwrAAkBAA8WAh4NTmV2ZXJFeHBhbmRlZGdkZAIvD2QWAgIED2QWDgIDDxYCHw ALKwQBZAIFDxYCHwALKwQBZAIHD2QWAmYPDxYCHwZoZGQCCQ9kFgJmDw8WAh8GaGRkAgsPZBYCZg8PFgI fBmhkZAIND2QWAmYPDxYCHwZoZGQCDw9kFgJmDw8WAh8GaGRkGAIFOWN0bDAwJG0kZ181NmIxMzIzMV9k YjllXzRlYTZfOTc5ZF9iYWZlNDk3MDkyOWUkY3RsMDEkZ3JpZA8UKwADPCsACgEIZgL/////DwL/////D 2QFRWN0bDAwJFBsYWNlSG9sZGVyVG9wTmF2QmFyJFBsYWNlSG9sZGVySG9yaXpvbnRhbE5hdiRUb3BOYX ZpZ2F0aW9uTWVudQ8PZAUKQWxsIGluIE9uZWQiMPVaPthHdSA3rH8zgoNOvWxd4w==" />
Once NCache caches this View State, it replaces the "id" and "value" fields with its own data. Here is an example of that.
< input type = "hidden" name = "__NCPVIEWSTATE" id = "__NCPVIEWSTATE" value = "vs:cf8c8d3927ad4c1a84da7f891bb89185" />
< input type = "hidden" name = "__VIEWSTATE" id = "__VIEWSTATE" value = "" />
Notice, how it is preserved the original "__VIEWSTATE" hidden field so everything works as if there was no View State. But, it has inserted its own "__NCPVIEWSTATE" field that it will read when a post-back request comes from the user to the web server. NCache uses the "value" as the key to fetch the corresponding original View State from the in-memory cache and serves it to the ASP.NET page so it can populate the web form with data from the View State.
And, since the in-memory cache is distributed and synchronized across all web servers, even if the post-back request goes to a different web server in the farm than the original server where the View State was created, NCache is able to find the View State value in the cache.
Note: It is recommended not to disable viewstate caching during peak hours because it may corrupt the viewstate of already opened pages.
See Also
Java Script Minification | View State Caching and Java Script Minification Plugin


Topic: Java Script Minification

Java Script Minification

All ASP.NET applications have to deal with extra overhead of loading multiple CSS and JavaScript files. Whenever a page is being rendered in the browser, the browser issues separate GET calls for each JavaScript file and each CSS file. And, this can easily result into many extra calls to IIS and slow down the response time of the ASP.NET pages.
Why Minify CSS and JavaScript Files?
JavaScript Minification is a process in which NCache reduces the size of all CSS and JavaScript files and also merges them into one or two files. As a result, a web browser only makes one or two extra calls to IIS when requesting a web page. Here are some reasons why you should minify JavaScript and CSS files:
  • Reduce number of HTTP requests a browser makes.
  • Set a futuristic date so browser caches files longer.
  • Minify JavaScript and CSS files and reduce their payload size.
  • Merge multiple JavaScript and CSS files into one.
  • Boost response time of web pages.
How does NCache Minify JavaScript and CSS?
NCache reduces the size of all JavaScript and CSS files by going through and removing all white spaces, tabs, and any other extra characters. It also reduces names of local variables and parameters but ensures that no logic is broken. Below is an example of a typical JavaScript function and then how it looks after it is minified.
function AddMPOverhang(leftOverhangId, rightOverhangId)
{
var leftOverhang=document.getElementById(leftOverhangId);
var rightOverhang=document.getElementById(rightOverhangId);
if (leftOverhang !=null && leftOverhang.style !=null)
{
leftOverhang.style.position='relative';
leftOverhang.style.bottom='-7px';
}
if (rightOverhang !=null && rightOverhang.style !=null)
{
rightOverhang.style.position='relative';
rightOverhang.style.bottom='-7px';
}
}
Below is the same JavaScript function after it has been minified.
function AddMPOverhang(C,D){var B=document.getElementById(C);var
A=document.getElementById(D);if(B!=null&&B.style!=null)
{B.style.position="relative";B.style.bottom="-7px"}if
(A!=null&&A.style!=null){A.style.position="relative";A.style.bottom="-7px"}}
In addition to reducing the size of all JavaScript and CSS files, NCache also merges multiple files into one, so the browser has to download only one or two files at most (one for JavaScript and one for CSS). This reduces the number of HTTP requests a browser has to make for loading an ASP.NET page and improves performance and scalability of web server farm.
Caching can be enabled on JavaScript and CSS files when a web page includes more then one JavaScript/CSS files. NCache caches the JavaScript and CSS files, reduces the size of all files and merge them into a single page (both CSS and JavaScript will be saved in separate files). In this case cached item doesn't expire automatically. To perish the content of JavaScript and CSS from cache, NCache provides you the following tool to clear the content:
clearcache cacheid/w[ebcontent]
This command will expire only the actual data while mapping remains in the cache.
See Also
View State Caching | View State Caching and Java Script Minification Plug in


Topic: View State Caching and Java Script Minification

View State Caching and Java Script Minification

Following are the two steps that you need to follow in order to use content optimization feature of NCache:
Step 1: Update/Configure app browser file:
  • Create an App browser file in your asp.net application. It will be created under the directory of App_browsers.
  • Plug page adapters in the app browser file as following:
    <browser refID ="Default">
    <controlAdapters>
    <adapter controlType = "System.Web.UI.Page" adapterType = "Alachisoft.NCache.Adapters.PageAdapter"/>
    </controlAdapters>
    </browser>
    Here page adapter is plugged at page level. You can also plug it at any control level for which you want to cache the view state.
Step 2: Update/Configure web.config file:
  • You need to add the following assembly reference in compilation section of web.config file.
    <compilation defaultLanguage = "c#" debug = "true">
    <assemblies>
    <add assembly = "Alachisoft.NCache.Adapters, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cff5926ed6a53769"/>
    </assemblies>
    </compilation>
  • You need to register a web config section which contains the settings/properties in web.config file.
    <configSections>
    <sectionGroup name = "ncContentOptimization">
    <section name = "settings" type = "Alachisoft.NCache.ContentOptimization.Configurations.ContentSettings" allowLocation = "true" allowDefinition = "Everywhere"/>
    </sectionGroup>
    </configSections>
  • Add the actual setting/configuration section as follows:
    <ncContentOptimization>
    <settings enableMinification = "true" enableViewstateCaching = "true"
    groupedViewStateWithSessions = "true"viewstateThreshold = "0" enableTrace = "true">
    <cacheSettings cacheName = "mycache">
    <expiration type="Sliding" duration = "300"/>
    </cacheSettings>
    </settings>
    </ncContentOptimization>
  • enableMinification: Enable/disable the Java script minification.
  • enableViewstateCaching: Enable/disable the ViewState caching.
  • gropuedViewStateWithSessions: Enable/disable grouped view state with sessions. By default this attribute is false.
  • viewstateThreshold: Sets minimum threshold size of view state in bytes. ViewStates which are smaller than threshold value will not be cached.
  • enableTrace: Enable/disable logging.
  • cacheName: Name of the cache.
  • expiration type: Sets the expiration type which can either be Sliding, Absolute or None.
  • duration: Sets expiration interval in minutes.
Register the http handler in the HttpHandlers section of web.config as following:
<add verb = "GET,HEAD" path = "NCResource.axd" validate = "false" type = "Alachisoft.NCache.Adapters.ContentOptimization.ResourceHandler, Alachisoft.NCache.Adapters, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cff5926ed6a53769"/>
Through querystring parameter "rpo=off", user can quickly turn off CSS and JS minification without modifying web.config. This facility is provided to the users to analyze the page load time with and without content optimization.
See Also
View State Caching | Java Script Minification


Topic: Client Side Third Party Integrations

Client Side Third Party Integrations

This tutorial is a practical guide for programmers who want to utilize powerful Third Party Integrations with NCache to create high performance and scalable .NET applications. This includes working examples and code snippets to utilize various features of NCache efficiently.
In This Section
NHibernate
Explains how you can plug-in NCache to your existing NHibernate application to use NCache with NHibernate.
EntLib 4.1+ Caching Block
Demonstrates how to use Caching Application Block.
Entity Framework
Shows how to plug EF caching provider with NCache.
.NET 4.0 System.Runtime.Caching
NCache provides integration with .NET cache provider 4.0. NCache also provides different Change Monitors (file based, key based, database dependency) for managing cache dependencies.


Topic: NHibernate

NHibernate

NCache provides a second level or process level distributed cache for NHibernate by implementing ICacheProvider and ICache interfaces. You can plug-in NCache to your existing NHibernate application without any code change. Just change your NHibernate configuration file to plug-in NCache as your cache provider and you're all set to start using distributed caching.
Follow these steps to use NCache with NHibernate:
  1. Register 'nhibernate' and 'ncache' configuration sections in the <configSections> of the web.config or app.config as follows:
    <configSections>
    <section name = "hibernate-configuration" type = "NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
    <section name = "ncache" type = "Alachisoft.NCache.Integrations.NHibernate.Cache.NCacheSection, Alachisoft.NCache.Integrations.NHibernate.Cache"/>
    </configSections>
  2. Define section details for <nhibernate> as follows:
    <hibernate-configuration xmlns = "urn:nhibernate-configuration-2.2">
    <session-factory>
    <property name = "cache.provider_class"> Alachisoft.NCache.Integrations.NHibernate.Cache.NCacheProvider, Alachisoft.NCache.Integrations.NHibernate.Cache </property>
    </session-factory>
    </hibernate-configuration>
  3. Define section details for <ncache> as follows:
<ncache>
<region name = "default">
<add key = "cacheName" value = "mycache"/>
<add key = "enableCacheException" value = "false"/>
<class name = "nhibernator.BLL.Customer">
<add key = "priority" value = "1"/>
<add key = "useAsync" value = "false"/>
<add key = "relativeExpiration" value = "180"/> or <add key = "staticExpiration" value = "100"/>
</class>
</region>
</ncache>
The above example of app.config or web.config contains the following options for you to configure. Each of them is explained below as well.
  • hibernate.cache.provider_class: This option lets you specify that NCache is your second level cache provider. You need to mention two classes which implement NHibernate.Cache.ICacheProvider and NHibernate.Cache.ICache interfaces respectively. This is how NHibernate knows how to call this second level cache.
  • The "region" attribute of the NCache determines the Cache in which the particular entity will be cached.
  • cacheName: This option is included inside the <ncache> tag and lets you specify name of the cache that you have configured through NCache Manager. All caches in NCache are named and this name allows NCache provider to connect to the right cache.
  • enableCacheException: This flag allows you to turn on exception handling which by default is turned off. This will throw an exception which you'll have to catch in your .NET application.
  • class: This lets you specify options specific to a .NET class. All the options below are class-specific. Class name must be the same as specified in the mapping file of the class ( .hbm.xml file).
  • priority: The priority you want to use for items cached. The possible values are from 1 to 6.
  • useAsync: This is a flag that tells the provider whether to use the standard synchronized "Add" and "Insert" or the asynchronous "AddAsync" and "InsertAsync" operations. The asynchronous operations immediately return control back to the client and queues up the operation in a background queue. Then, a background thread executes the command.
  • relativeExpiration: This value is specified as number of seconds. It indicates the idle-time expiration for your items, meaning how long your item can stay without being accessed.
Note:
  • Calling new Configuration() reads the <nhibernate> section only.
  • Calling no-parameter version of cfg.Configure() configures NHibernate from app.config if it contains <nhibernate-configuration>, otherwise hibernate.cfg.xml is used.
See Also
Enabling DbCacheDependency in Nhibernate


Topic: EntLib 4.1+ Caching Block

Using NCache with Enterprise Library 4.1 Caching Application Block (CAB)

Caching Application Block (CAB) is part of Enterprise Library from Microsoft. By default, it provides a stand-alone InProc cache. However, if you want to use NCache as a distributed cache for your application that is already using CAB, you can do so without any code change. You just have to make some changes in app.config.
This quick start allows you to get start with using NCache with Caching Application Block.
Step 1: Configure the Cache
Step 2: Register NCache with CAB
Step 3: Run your CAB based Application
See Also
Using NCache with NHibernate
Provides step by step guide along with sample code to use NHibernate with NCache.
Using DB Dependencies with Caching Application Block
Explains how to create DB dependencies with Caching application block.


Topic: Entity Framework Caching Integration

Entity Framework Caching Integration

NOTE: This feature is not available in NCache Express and Professional edition.
Entity Framework Caching Provider:
The ADO.NET Entity Framework is the way of developing a data access layer between application and database. It abstracts the relational data that is stored in a database and presents its conceptual schema to the application.
Entity Framework has implemented a public provider model which support 3rd-party databases, such as Oracle, MySQL, PostreSQL etc. Entity Framework utilize the stackable provider interface, which makes it possible to write a provider which will wrap another provider and intercept communication between Entity Framework and the original provider. NCache introduces the caching provider called EF Caching provider which acts between Entity Framework and the original provider.
The major reason behind the EF Caching provider is that EF involves retrieving of data from database. The database trip slows the application response; which can be rectified by caching the retrieved data from database to in-memory and presents it to the user from cache when queried. The caching provider acts between ADO.NET entity framework provider and the original data provider to cache the query responses. This means that the user can start caching queries just by plugging in NCache provider without changing/compiling the current code.
The caching provider can perform various functions, such as:
  • Managing connections, commands, transactions and data readers.
  • Monitoring queries and commands before they executes.
See Also
Enabling NCache in Entity Framework application | EF Caching Modes


Topic: Enabling NCache in Entity Framework application

Enabling NCache in Entity Framework application

NOTE: This feature is not available in NCache Express and Professional edition.
Following are the prerequisites to enable NCache in Entity Framework application:
1. You should have an Entity Framework application. (you can also use sample application for EFCaching from NCache sample applications from the following path:"Installeddirectory:/ProgramFiles/NCache/samples/clr20/EntityDataModelIntegrationDemo"
In every Entity Framework application, ADO.NET Entity Data Model is already added which automatically generates two files:
  • SSDL
  • Application (or web) configuration file
2. Microsoft Visual Studio 2008 with SP1.
3. Database Tool (e.g. MS SQL SERVER 2005, ORACLE)
Steps required to enable NCache in Entity Framework application:
Step 1: Add Reference:
Add "Alachisoft.Integrations.EntityFramework.CachingProvider" reference to your Entity Framework application. This .dll file is placed on the following path: "Installeddirectory:/ProgramFiles/NCache/integration/MSEntityFramework".
After adding the reference, changes are required in 3 different files:
Step 2: SSDL Configurations:
In SSDL file which is generated on adding ADO.NET Entity Data Model in Entity Framework application, required following changes:
[Below is the Sample change for Sql 2005 database]
In SSDL, the provider name is specified in the Provider attribute of the <Schema/> element as shown below:
[Existing Code]
<Schema Namespace = "NorthwindModel.Store" Alias = "Self" Provider = "System.Data.SqlClient" ProviderManifestToken = "2005" xmlns:store = "http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns = "http://schemas.microsoft.com/ado/2006/04/edm/ssdl">
In order to inject our NCache Entity frame Provider, we need to override the above highlighted attributes to plugin our provider. In SSDL, we put the name of the new provider in the Provider attribute and concatenate the previous provider with our provider manifest token in the ProviderManifestToken field, as shown below:
[Changed Code]
<Schema Namespace = "NorthwindModel.Store" Alias = "Self" Provider = "Alachisoft.Integrations.EntityFramework.CachingProvider" ProviderManifestToken = "System.Data.SqlClient;2005" xmlns:store = "http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns = "http://schemas.microsoft.com/ado/2006/04/edm/ssdl">
Step 3: Application (or web) Configurations:
Application (or web) configuration file which is generated on adding ADO.NET Entity Data Model in Entity Framework application, required following changes:
  1. Provider invariant name is also specified in the connection string of application (or web) configuration file:
    [Existing Code]
    <connectionStrings>
    <add name = "NorthwindEntities" connectionString = "metadata=res:///EF.csdl|res:///EF.ssdl|res:///EF.msl;
    provider= System.Data.SqlClient;
    provider connection string= &quot;
    Data Source=QCTEST2;Initial Catalog=Northwind;Integrated
    Security=True;MultipleActiveResultSets=True &quot; " providerName = "System.Data.EntityClient"/>
    </connectionStrings>
    Change provider name for our NCache Entity framework Provider and add provider wrapper information in provider connection string:
    [Changed Code]
    <connectionStrings>
    <add name = "NorthwindEntities"
    connectionString = " metadata=res:///EF.csdl|res:///EF.ssdl|res:///EF.msl; provider= Alachisoft.Integrations.EntityFramework.CachingProvider;
    provider connection string= &quot;
    wrappedProvider=System.Data.SqlClient;
    Data Source=QCTEST2;Initial Catalog=Northwind;Integrated
    Security=True;MultipleActiveResultSets=True &quot;" providerName = "System.Data.EntityClient"/>
    </connectionStrings>
  2. Also add the provider factory for initialization of NCache Entity framework Provider. The invariant attribute should be the same as the provider name in connection string and SSDL.
    <DbProviderFactories>
    <add name = "EF Caching Data Provider" invariant = "Alachisoft.Integrations.EntityFramework.CachingProvider" description = "Caching Provider Wrapper" type = "Alachisoft.NCache.Integrations.EntityFramework.EFCachingProviderFactory, Alachisoft.Integrations.EntityFramework.CachingProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cff5926ed6a53769"/>
    </DbProviderFactories>
  3. Following information should be added in appSettings of app.config/web.config :
    <appSettings>
    <add key = "app-id" value = "PersonNameApp2"/>
    <add key = "logging-level" value = "Debug"/>
    </appSettings>
  • App-id : This will be the identifier for current application. This ID will be used to read configuration from efcaching.ncconf
  • Logging-level : Determines the logging level for application. Our provider will log exceptions and errors only when level is set to Error. When the level is set to Debug, both exceptions/errors and other detailed information will be logged. Nothing will be logged if level is set to Off (default). Path at which log files will be generated: Default = <install-dir>/log-files/efcaching-logs/
  • For applying the above changes, application should be restarted after these changes are made.
NOTE: App-id for efcaching.ncconf should be same as in application (app.config) otherwise it will prompt an error)
Alternative method
Apart from specifying connection string in app.config/web.config, you can also specify the connection while creating ObjectContext or EntityConnection. While creating a connection string programmatically, you need to include the wrapper information in a connection string. Here is how you can create connection string and initialize ObjectContext or EntityConnection.
SqlConnectionStringBuilder sqlConnBuilder = new SqlConnectionStringBuilder ();
sqlConnBuilder.DataSource = "localhost" ;
sqlConnBuilder.InitialCatalog = "EFTestDB" ;
sqlConnBuilder.IntegratedSecurity = true ;
string conString = sqlConnBuilder.ToString();
EntityConnectionStringBuilder efConnBuilder = new EntityConnectionStringBuilder();
efConnBuilder.Provider = "EFCachingProvider" ;
efConnBuilder.ProviderConnectionString = @"wrappedProvider=System.Data.SqlClient;" + conString;
efConnBuilder.Metadata = "res:// /PersonName.csdl|res:// /PersonName.ssdl|res:// /PersonName.msl;" ;
EntityConnection connection = new EntityConnection(efConnBuilder.ToString());
For applying these changes, you need to rebuild the application.
Step 4: efcaching.ncconf Configurations:
Changes required in "efcaching.ncconf".
  1. Efcaching.ncconf is placed on the following path: "Installeddirectory:/Program Files/NCache/config".
  2. Provider Configuration contains cache and caching policy related information. Below are the changes required in efcaching.ncconf.
    <configuration>
    <app-config app-id = "PersonNameApp" mode = "analysis|caching">
  3. "Analysis" mode is used for monitoring the number of times each query executes and then it generates a report. Report contains the Query text and the call count for each query. This report can be used in Custom policy. No caching is done at this mode.
    <analysis-policy log-path = "" analysis-time = "60" cache-enable-threshold = "5" default-expiration-type = "absolute|sliding" default-expiration-time = "180" dbsyncdependency = "true"/>
  4. Log-path: Path at which analysis log files will be generated.
    Default = < install-dir > /log-files/efcaching-analysis-logs/
  5. For "Caching" mode, wrapping provider will cache the results of all the specified queries. Caching mode works on either cacheall policy or custom policy. Both policies have their own specifications. Whenever update is detected (either UPDATE, INSERT or DELETE) in a respective database, the provider invalidates affected cache entries by evicting all cached queries which were dependent on any of the updated tables.
    <cache-policy default-policy = "cacheall|custom" database = "none|oracle10i2|sqlserver" cache-id = "mycache" enabled = "true">
  6. For cacheall policy, it caches all the queries and their results.
    <cacheall-policy expiration-type = "absolute|sliding" expiration-time = "1800" dbsyncdependency = "true"/>
  7. For custom policy, it includes user-configurable list of queries that should be cached with their results. When custom policy is selected, only those query results will be cached for which the caching is enabled. You can also specify custom caching policy for all queries.
    <custom-policy>
    <query query-text = "" ["SELECT FROM Products"] | stored-procedure-name = "" ] caching = "true" expiration-type = "absolute"| sliding = "" expiration-time = "180" dbsyncdependency = "true"/>
    </custom-policy>
    </cache-policy></app-config></configuration>
  8. Incase of stored procedures, query text will be the name of a stored procedure, and there will be no default policy or database sync dependency. User can cache stored procedures result with expiration only, no database dependency is required here.
See Also
EF Caching Integration | EF Caching Modes


Topic: Entity Framework Caching Integration Modes

Entity Framework Caching Integration Modes

NOTE: This feature is not available in NCache Express and Professional edition.
Entity Framework Caching provider works under two modes. It can either be in "Caching" mode (caching the results of queries) or in "Analysis" mode (analyzing the queries). Provider can not work in both modes at the same time. Details of both the modes are given below:
Caching Mode:
It uses NCache for caching results of all queries that are executed on a database. Whenever update is detected (either UPDATE, INSERT or DELETE) in a respective database, the provider invalidates affected cache entries by evicting all cached queries which were dependent on any of the updated tables. Caching mode is further divided into two policies:
  1. Custom Caching: It includes user-configurable list of queries and cache the results of those queries only.
  2. CacheAll Caching: It caches all queries results.
Caching mode works on the following principles:
  • Only SELECT statements and stored procedures results will be cached.
  • If a SELECT statement or stored procedure do not yield any result, nothing will be cached.
  • User are supposed to select the target database that will be used to create database dependency. If no target database is selected, no database-dependency will be added.
  • Caching policies will be read from configuration file, when caching is started. If configuration file is updated, new policies will be applied for subsequent requests.
  • The provider will only cache those results which will be completely retrieved by the application. If query yielded more data then the application has read, before calling DbDataReader.Close(), nothing will be cached.
    Analysis Mode:
    This mode is used for monitoring the number of times each query executes and generates a result. This is a pass-through mode, no caching is done at this mode. In analysis phase following information will be collected:
  1. Query text: Select query.
  2. Call count: The number of times a query is called.
    Analysis mode works on the following principles:
  • Analysis can be started by changing the mode in configuration file from caching to analysis . During analysis mode, no result will be cached.
  • One analysis report will be generated on the following path: Default = <install-dir>/log-files/efcaching-logs/
  • Analysis report will be generated on the following conditions: When mode is changed.
  • When analysis time is over.
  • When application shutdown.
  • Analysis report will be generated in the following format:
    <analysis-report>
    <!--Call-count = 21-->
    <query query-text = "" ["SELECT FROM Products"] | [stored-procedure-name = ""]
    caching = "true"
    expiration-type = "absolute"| sliding = ""
    expiration-time = "180"
    dbsyncdependency = "true"/>
    </analysis-report>
  • The analysis report is similar as the custom policy syntax which will ease the user to use the same report in custom policy section.
  • The queries generated in the analysis report will be sorted in descending order of call-count, so that the least used queries will be listed at the end of the report. This will make it easier for user to copy a group of most frequently used queries and paste them in custom policy section.
See Also
EF Caching Integration | Enabling NCache in Entity Framework application


Topic: Cache Provider for .Net 4.0

Cache Provider for .Net 4.0

NCache provides integration with .NET cache provider 4.0. You can use ObjectCache implementation with your cache by referring the Cache Provider assembly from the following path:
Installed Directory/NCache/integration/DotNet4.0 Cache Provider
NCache provider gives you the support for all the properties of ObjectCache class except "regions".
Configuration Steps:
Following steps need to be followed for using cache provides in your application:
  • Create a new Clustered Cache or a Local Cache in NCache Manager with the name "mycache".
  • Start the cache "mycache".
  • Create an application inside Visual Studio.NET.
  • Add following references to your application from "Installed Directory/NCache/integration/DotNet4.0 Cache Provider" path:
    Alachisoft.NCache.ObjectCacheProvider
  • Include the following namespace in your project.
    using Alachisoft.NCache.ObjectCacheProvider;
  • Initialize your CacheProvider and pass your cache name to the provider as shown below.
    private ObjectCache _cache;
    private string _cacheId = "myCache" ;
    _cache = new CacheProvider(_cacheId);
  • Now you can perform all cache related operations on your cache using CacheProvider commands.
See Also
Features | ChanageMonitor


Topic: ChangeMonitor

ChangeMonitor

NCache provides its own implementation for ChanageMonitor class and does not support .net implementation for the same class. ChangeMonitor class is used as a base class for derived monitor classes that are specialized for particular cache implementations. These classes monitor the changes in the state of the data on which cache items depends to keep the cache items valid. Following are the different Change Monitors (file based, key based, database dependency) provided by NCache for managing cache dependencies.
NCacheEntryChangeMonitor Class:
This class represents an object that monitors changes to an entry. Entry based dependency associates one cached item with another item in the cache. It invalidates the dependent item when that particular item changes. Whenever that item is removed or updated from the cache, associated object will be expired. Entry based dependency is cascaded.
The following steps demonstrate how to use NCacheEntryChangeMonitor class.
string [] depKeys = ("key1", "key2", "key3"};
NCacheEntryChangeMonitor changeMonitor = new NCacheEntryChangeMonitor(depKeys);
ciPolicy = new CacheItemPolicy();
ciPolicy.ChangeMonitors.Add(changeMonitor);
_cache.Add(cItem, ciPolicy);
_cache.Add("Test key", "Key Value", CacheItemPolicy);
NCacheFileChangeMonitor Class:
This class represents an object that monitors changes to files. It sets the validity of the cache item based on an external file or files. When this resource changes, the cached object becomes obsolete and is removed from the cache. In this class a File/Directory path is provided. Cache object also expires if the path is used to create a new File/Directory.
The following steps demonstrate how to use NCacheFileChangeMonitor class.
string [] depFile = { "c:\NCache\file1.txt", "c:\NCache\file2.txt" };
NCacheFileChangeMonitor changeMonitor = new NCacheFileChangeMonitor(fileNames);
ciPolicy = new CacheItemPolicy();
ciPolicy.ChangeMonitors.Add(changeMonitor);
_cache.Add(cItem, ciPolicy);
_cache.Add("Test key", "Key Value", CacheItemPolicy);
NCacheSqlChangeMonitor Class:
This class provides change monitoring for SQL Server databases and cannot be inherited. While working with databases in a multiuser environment, updates in the databases are very frequent. NCacheSqlChangeMonitor sets the validity of the cache item based on database. In this case item expires if result of the command (based on command text) changes.
The following steps demonstrate how to use NCacheSqlChangeMonitor class.
string conString = @"Server=TEST7; Initial catalog=Northwind; User ID=sa; password= myPassword;" ;
string cmdString = "SELECT ProductID FROM dbo.products WHERE ProductID = 10" ;
NCacheSqlChangeMonitor changeMonitor = new NCacheSqlChangeMonitor(conString, cmdString);
ciPolicy = new CacheItemPolicy();
ciPolicy.ChangeMonitors.Add(changeMonitor);
_cache.Add(cItem, ciPolicy);
_cache.Add( "Test key" , "Key Value" , CacheItemPolicy);
NCacheOracleChangeMonitor Class:
This class provides change monitoring for Oracle Server databases. This class cannot be inherited. While working with databases in a multiuser environment, updates in the databases are very frequent. NCacheOracleChangeMonitor sets the validity of the cache item based on database. In this case item expires if result of the command (based on command text) changes.
The following steps demonstrate how to use NCacheOracleChangeMonitor class.
string conString = "Data Source = TORCL; User Id = myUsername; Password = myPassword" ;
string cmdString = "SELECT ProductID FROM dbo.products WHERE ProductID = 10" ;
NCacheOracleChangeMonitor changeMonitor = new NCacheOracleChangeMonitor(conString, cmdString);
ciPolicy = new CacheItemPolicy();
ciPolicy.ChangeMonitors.Add(changeMonitor);
_cache.Add(cItem, ciPolicy);
_cache.Add("Test key", "Key Value", CacheItemPolicy);
See Also
Features | Cache Provider for .Net 4.0


Topic: JAVA Programmer's Guide

JAVA Programmer's Guide

This section gives practical guide for programmers who want to use various features of NCache in java to develop high performance and scalable applications. It provides four different sets of features for programming with NCache. In order to use NCache API in java applications, following things are required to be done:
1. The java application must refer to the 'NCClient.jar' file. This file contains all APIs which are required to connect to the server and use cache.
2. Following files should be present in the install directory:
• NCActivate.jar
• NCClient.jar
• NCacheSessionProvider.jar (For JSP Sessions application)
• NCRuntime.jar
• NCSerialization.jar
3. The client.ncconf is read from the install directory of NCache. On Non-Windows platforms, the user must add "NCACHE_ROOT" environment variable specifying the install directory.
For example, in case of Linux, add following entry in the ".bash_profile" file:NCACHE_ROOT=<install-dir>
<install-dir> is the location where the client.ncconf is located.
For windows, client.ncconf is copied in "%INSTALL_DIR%/NCache/config/client.ncconf" and for Non-Windows, it is copied in "%INSTALL_DIR%/client.ncconf".
In This Section
Client Side API Programming
Provides a practical guide for client side features.
Server Side API Programming
Provides a practical guide for server side features.
Client Side JSP Features
Demonstrates the use and capabilities of client side JSP features.


Topic: Client Side API Programming

Client Side API Programming

This tutorial is a practical guide for programmers who want to utilize powerful features of NCache to create high performance and scalable Java applications. This includes working examples and code snippets to utilize various features of NCache efficiently.
In This Section
Initialize & Dispose Cache
Explains how to initialize and dispose Caches in different environments and how to specify Security credentials.
Access Multiple Caches in Single App
Explains how to initialize Multiple Caches in a single application.
Get Item
Explains using Cache API to find items from the cache.
Add/Update Item
Describes the procedure of adding and inserting/updating items in a cache.
Specify Expiration
Describes how certain cached items can be automatically removed from the cache when required.
Specify Priority
Explains adding items in the cache with priority settings.
Group/Subgroup
Presents distributing related objects in 'logical' groups.
Tags
Items can be added to the cache having multiple tags. Tag acts as an identifying marker to the cache items. So one can get items on the basis of Tags.
Named Tags
Explains how Named Tags work.
Lock/Unlock Item
Describes how to lock cached items to prevent multiple clients from updating the same data simultaneously.
Item Version
Demonstrates how item versioning works.
Streaming API
NCache provides you the facility of Streaming. Using streaming NCache binary data can be read or written from/to the cache using streams.
Bulk Operations
Describes performing bulk operations to add, insert or remove collection of items in a single method call. It helps speeding up the process and minimizes cluster traffic.
Async Operations
Explains utilizing notifications that arise as a result of add, insert or remove operations against all or selective cache items, or when cluster status changes.
Cache Dependency
Explains how to implement dependency of cached items on files, database table rows and other cached items.
Event Notifications
Explains utilizing notifications that arise as a result of add, insert or remove operations against all or selective cache items, or when cluster status changes.
Read-through, Write-through, Write-behind
Shows how to transparently fetch the required data from the master datasource if it is not available in the cache and vice versa.
Queries
Presents search API for querying objects from the cache using SQL like syntax.
Continuous Query
Explains how Continuous Query work.


Topic: Overview

How to setup development Environment?

Here we will discuss the step by step procedure for setting development environment for Eclipse and NetBeans.
For Eclipse
  1. File-> New -> Project.
  2. Select Java Project from range of generic projects.
  3. Enter the name of the project you want to create, e.g. NCache Test Project then press Next button.
  4. Select the Library tab, click "Add External Jars …".
  5. Go to path "C:\Program Files\NCache\Java\lib\" , considering the default installation location.
  6. Add NCClient.jar.
  7. Click Finish button.
  8. Now create a class file, by right click on src->new->Class.
  9. Enter the name of the class e.g MyClass.
  10. Check "public static void main(String[] args)".
  11. Click Finish button.
  12. Now import com.alachisoft.ncache.web.caching.*;
  13. There you go, you are all set up to begin NCache Development .
For Netbeans
  1. File->New Project.
  2. Select Java Application and click Next button.
  3. Enter the project name, e.g. NCache Test Application and click Finish button.
  4. In the Project window, under your newly created project hierarchy, right click on Libraries, then Properties.
  5. Click "Add Jar Files" then proceed to "C:\Program Files\NCache\Java\lib\" ,considering the default installation location.
  6. Select NCClient.jar.
  7. Now under your project hierarchy, under Source Packages, Find Main.java, double click it.
  8. Now add the line "import com.alachisoft.ncache.web.caching.*;" after package <your Project Name> and before the Main class.
  9. That's it, you're all set up and ready to go build your first NCache Java application in Netbeans environment.
See Also
Adding items with priority settings | Using Bulk Operations | Using Data Grouping


Topic: Initialize & Dispose Cache

Initialize & Dispose Cache

JSP, Web Services and J2EE
After you have configured the cache, embed NCache API calls in your application to use it. The first thing you need to do is to initialize the cache. The code for initializing the cache is as follows:
Using Initialize Method:
import com.alachisoft.ncache.web.caching.*;
Cache _cache = NCache.initializeCache("myCache");
Security Credentials passing & exceptions:
If security is enabled, only an authorized user can perform cache operations, provided those users exist under given domain in LDAP. Login credentials are required to belong to any WINDOWS Server, hosting the user login and running Active Directory services. User can give credential information in overloaded API's or in client.ncconf file. Now security parameters travel in the encrypted form.
Providing credentials in API
For API's initializeCache, startCache and stopCache, there are overloads that accept User ID and Password as parameters. They are then sent to the server for authentication and authorization.
// Initialize the cache.
NCache.initializeCache("myQSReplicatedCache", new Alachisoft.NCache.Web.Security.SecurityParams("john", "john123"), new Alachisoft.NCache.Web.Security.SecurityParams("sam", "sam123"));
Initializing Client Cache in Java Environment:
NCache is now providing support for Client Cache in Java environment. Users can initialize the Client Cache as follow:
// Initializing the client cache.
Cache _cache = NCache.initializeCache("myCache", "enabled");
To enable client cache in Java environment, users are supposed to specify “enabled” for clientCacheId in client.ncconf:
<cache id="clusteredcache" client-cache-id="enabled" client-cache-syncmode="optimistic" default-readthru-provider="" default-writethru-provider="" load-balance="True">
<server name="20.200.20.14"/>
</cache>
See Also
Adding items with priority settings | Using Bulk Operations | Using Data Grouping


Topic: Access Multiple Caches in Single Application

Access Multiple Caches in Single Application

Multiple caches can be initialized in a single application; there is no limit for number of caches in one application. Following is an example using multiple caches:
  1. Include the following import statements in your project:
    import com.alachisoft.ncache.web.caching.*;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    import java.io.Serializable;
    public class Customer implements Serializable
    {
    ....
    }
  4. Now insert the following code in the 'Main' of the project.
    Cache _cache1 = NCache.initializeCache("myCache");
    Cache _cache2 = NCache.initializeCache("myReplicatedCache");
    // Perform any of the operations provided by NCache on any of the cache initialized
    _cache1.clear();
    _cache2.clear();
    Customer customer = new Customer();
    customer.name = "David";
    customer.customerID = 1001;
    customer.setCity("London");
    customer.setContactNumber("+44-xxx-xxxx-xxxx");
    customer.setOrderInProcess(true);
    Customer customer1 = new Customer();
    customer1.name = "Alex";
    customer1.customerID = 1002;
    customer1.setCity("Chicago");
    customer1.setContactNumber("+44-xxx-xxxx-xxxx");
    customer1.setOrderInProcess(false);
    // Add Item to Cache
    NCache.getCaches().getCache("myCache").add("Customer:David:1001", customer);
    NCache.getCaches().getCache("myReplicatedCache").add("Customer:Alex:1002", customer1);
    // Get Items from Cache
    Object object_Customer = NCache.getCaches().getCache("myCache").get("Customer:David:1001");
    Object object_Customer1 = NCache.getCaches().getCache("myReplicatedCache").add("Customer:Alex:1002");
    Customer customerInformation = (Customer)object_Customer;
    System.out.println("Customer ID: " + customerInformation.customerID);
    System.out.println("Name: " + customerInformation.name);
    System.out.println("City: " + customerInformation.getCity());
    System.out.println("Contact Number: " + customerInformation.getContactNumber());
    System.out.println("Order placed: " + customerInformation.isOrderInProcess());
    System.out.println();
    customerInformation = (Customer)object_Customer1;
    System.out.println("Customer ID: " + customerInformation.customerID);
    System.out.println("Name: " + customerInformation.name);
    System.out.println("City: " + customerInformation.getCity());
    System.out.println("Contact Number: " + customerInformation.getContactNumber());
    System.out.println("Order placed: " + customerInformation.isOrderInProcess());
  5. Start both the caches.
  6. Run the project.
See Also
Adding items with priority settings | Using Bulk Operations | Using Data Grouping


Topic: Get Cache Item

Get Cache Item

Items can be retrieved from the cache by using Get method. Overloaded methods are also explained below:
Using Get Method:
Here is how you can retrieve items from the cache.
//returns null if item not found
Object myObject = _cache.get("Customer:Alex:1002");
if(myObject == null)
{
//item not found
}
To get latest Cache value of cache Item:
  1. Include the following import statements in your project:
    import com.alachisoft.ncache.web.caching.*;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    import java.io.Serializable;
    public class Customer implements Serializable
    {
    .....
    }
  4. Now insert the following code in 'Main' of the project.
Cache _cache = NCache.initializeCache("myCache");
_cache.clear();
Customer customer = new Customer();
customer.name = "David";
customer.Id = 1001;
// Add Item to Cache
_cache.add("Customer:David:1001", customer);
// Get the latest value with respect to key "Customer:David:1001"
CacheItem cItem = _cache.getCacheItem("Customer:David:1001");
if (cItem != null) // check if Item does exist
{
// do some operations
// ...
// Update the Cache Item, to change the item version, to perform the test
_cache.insert("Customer:David:1001", customer);
CacheItem cItem1 = _cache.getCacheItem("Customer:David:1001");
Customer customer1 = (Customer) cItem1.getValue();
System.out.println("Customer ID: " + customer1.Id);
System.out.println("Name: " + customer1.name);
}
5. Start the Local Cache 'myCache'.
6. Run the project.
See Also
Get with Locking | Get using logical groupings


Topic: Add/Update Item

Add/Update Item

You can add items in cache from anywhere in your Java application, provided cache has already been initialized. The value must be a Java serializable object otherwise NCache will throw a serialization exception. There are five methods provided in the Cache class which enable us to add objects or any piece of data into cache.
Using Add Method
Here is how you can add items to the cache. An "Add" method will add item to the cache only if that item does not already exist in the cache. Otherwise, it will throw an exception.
  1. Include the following import statements in your project:
    import com.alachisoft.ncache.web.caching.*;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    import java.io.Serializable;
    public class Customer implements Serializable
    {
    …
    }
  4. Now insert the following code in the 'Main' of the project.
    Cache _cache = NCache.initializeCache("myCache");
    _cache.clear();
    Customer customer = new Customer();
    customer.name = "David";
    customer.customerID = 1001;
    customer.setCity("London");
    customer.setContactNumber("+44-xxx-xxxx-xxxx");
    customer.setOrderInProcess(true);
    // Add Item to Cache
    _cache.add("Customer:David:1001", customer);
    Object object_Customer = _cache.get("Customer:David:100");
    Customer customerInformation = (Customer)object_Customer;
    System.out.println("Customer ID: " + customerInformation.customerID);
    System.out.println("Name: " + customerInformation.name);
    System.out.println("City: " + customerInformation.getCity());
    System.out.println("Contact Number: " + customerInformation.getContactNumber());
    System.out.println("Order placed: " + customerInformation.isOrderInProcess());
  5. Start the Local Cache 'myCache'.
  6. Run the project.
Using Insert Method
Furthermore, you can use Insert() to either add or update the item in the cache. Insert() method adds the item if it does not already exist in the cache. Otherwise, it updates the item.
  1. Include the following import statements in your project:
    import com.alachisoft.ncache.web.caching.*;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    import java.io.Serializable;
    public class Customer implements Serializable
    {
    …
    }
  4. Now insert the following code in the ' Main ' of the project.
    Cache _cache = NCache.initializeCache("myCache");
    _cache.clear();
    Customer customer = new Customer();
    customer.name = "David";
    customer.customerID = 1001;
    customer.setCity("London");
    customer.setContactNumber("+44-xxx-xxxx-xxxx");
    customer.setOrderInProcess(true);
    // Update Item to Cache
    _cache.insert("Customer:David:100", customer);
    Object object_Customer = _cache.get("Customer:David:100");
    Customer customerInformation = (Customer)object_Customer;
    System.out.println("Customer ID: " + customerInformation.customerID);
    System.out.println("Name: " + customerInformation.name);
    System.out.println("City: " + customerInformation.getCity());
    System.out.println("Contact Number: " + customerInformation.getContactNumber());
    System.out.println("Order placed: " + customerInformation.isOrderInProcess());
  5. Start the Local Cache 'myCache'.
  6. Run the project.
See Also
Adding items with priority settings | Using Bulk Operations | Using Data Grouping


Topic: Delete Items

Delete Items

Once you have a valid cache handle, you can do the "Delete" operations on a cache. This operation has many overloads and the basic overload takes only one parameter i.e. "key" as string.
Using Delete Method
A "Delete" method will delete item from the cache only if that item already exist in the cache. Exception will be thrown if the method is unable to delete the key from the cache.
  1. Include the following import statements in your project:
    import com.alachisoft.ncache.web.caching.*;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    import java.io.Serializable;
    public class Customer implements Serializable
    {
    ......
    }
  4. Now insert the following code in the 'Main' of the project.
    Cache _cache = NCache.initializeCache("myCache");
    _cache.clear();
    Customer customer = new Customer();
    customer.name = "David";
    customer.customerID = 1001;
    customer.setCity("London");
    customer.setContactNumber("+44-xxx-xxxx-xxxx");
    customer.setOrderInProcess(true);
    // Add Item to Cache
    _cache.add("Customer:David:1001", customer);
    // Delete the above Item from the Cache
    _cache.delete("Customer:David:1001");
  5. Start the Local Cache 'myCache'.
  6. Run the project.
See Also
Adding items with priority settings | Using Bulk Operations | Using Data Grouping


Topic: Expiring Cached Items

Expiring Cached Items

An expiration object can be associated with each item being added to the cache. When that expiration object invalidates (invalidation of expiration object is dependent on the provided parameters), the associated item is removed from the cache. NCache provides two types of expirations i.e. Absolute expiration and Sliding expiration.
  1. Include the following import statements in your project:
    import com.alachisoft.ncache.web.caching.*;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    import java.io.Serializable;
    public class Customer implements Serializable
    {
    …
    }
  4. Now insert the following code in the 'Main' of the project.
    Absolute Expiration:
    The time period at which the added object expires and is removed from the cache. If you are using sliding expiration, the absoluteExpiration parameter must be NoAbsoluteExpiration.
    Cache _cache = NCache.initializeCache("myCache");
    _cache.clear();
    Customer customer = new Customer();
    customer.name = "David";
    customer.customerID = 1001;
    customer.setCity("London");
    customer.setContactNumber("+44-xxx-xxxx-xxxx");
    customer.setOrderInProcess(true);
    Calendar calendar = Calendar.getInstance();
    calendar.add(calendar.MINUTE, 10);
    _cache.add("Customer:David:1001", customer, null, calendar.getTime(), Cache.NoSlidingExpiration, CacheItemPriority.Normal);
    Thread.sleep(1000*60*11);
    Object object_Customer = _cache.get("Customer:David:1001");
    Customer customerInformation = (Customer) object_Customer;
    System.out.println("Customer ID: " + customerInformation.customerID);
    System.out.println("Name: " + customerInformation.name);
    System.out.println("City: " + customerInformation.getCity());
    System.out.println("Contact Number: " + customerInformation.getContactNumber());
    System.out.println("Order placed: " + customerInformation.isOrderInProcess());
    Sliding Expiration:
    Time interval between the last accessed time of the added object and object expiration time. If this value is the equivalent of 10 minutes, the object expires and is removed from the cache 10 minutes after it is last accessed. If you are using absolute expiration, the slidingExpiration parameter must be NoSlidingExpiration.
    Cache _cache = NCache.initializeCache("myCache");
    _cache.clear();
    Customer customer = new Customer();
    customer.name = "David";
    customer.customerID = 1001;
    customer.setCity("London");
    customer.setContactNumber("+44-xxx-xxxx-xxxx");
    customer.setOrderInProcess(true);
    _cache.add("Customer:David:1001", customer, null, Cache.NoAbsoluteExpiration, new TimeSpan(10,0), CacheItemPriority.Normal);
    Thread.sleep(1000*60*10);
    Object object_Customer = _cache.get("Customer:David:1001");
    Customer customerInformation = (Customer) object_Customer;
    System.out.println("Customer ID: " + customerInformation.customerID);
    System.out.println("Name: " + customerInformation.name);
    System.out.println("City: " + customerInformation.getCity());
    System.out.println("Contact Number: " + customerInformation.getContactNumber());
    System.out.println("Order placed: " + customerInformation.isOrderInProcess());
  5. Start the Local Cache 'myCache'.
  6. Run the project.
Using Absolute and Sliding Expiration
While adding some item to the cache, you can provide a DateTime value which is translated into Absolute Expiration and the item is removed from the cache at the specified DateTime value. If you don't want to provide any Absolute Expiration, you can use an enumeration (NoAbsoluteExpiration) provided by NCache. Similarly, you can provide a TimeSpan value which is translated into Sliding Expiration and item is removed from the cache if the specified period of time has elapsed since it was last accessed. If you don't want to provide a Sliding Expiration, you can use an enumeration (NoSlidingExpiration) provided by NCache.
See Also
Using Cache Dependency | Adding items with priority settings | Using Bulk Operations | Using Data Grouping


Topic: Adding items with priority settings

Adding items with priority settings

The cache uses priorities when it has to evict objects; objects with a lower cost are removed from the cache before objects with a higher cost. You can add an item to the Cache with priority settings by using the priority parameter of the Add or Insert method. The following example uses the Add method to add an item to the Cache with a high priority.
  1. Include the following import statements in your project:
    import com.alachisoft.ncache.web.caching.*;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    import java.io.Serializable;
    public class Customer implements Serializable
    {
    …
    }
  4. Now insert the following code in 'Main' of the project.
    Cache _cache = NCache.initializeCache( "myCache" );
    _cache.clear();
    Customer customer = new Customer();
    customer.name = "David" ;
    customer.customerID = 1001 ;
    customer.setCity( " London " );
    customer.setContactNumber( "+44-xxx-xxxx-xxxx" );
    customer.setOrderInProcess( true );
    _cache.add("Customer:David:1001", customer, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.High);
    Object object_Customer = _cache.get("Customer:David:1001");
    Customer customerInformation = (Customer) object_Customer;
    System.out.println( "Customer ID: " + customerInformation.customerID);
    System.out.println( "Name: " + customerInformation.name);
    System.out.println( "City: " + customerInformation.getCity());
    System.out.println( "Contact Number: " + customerInformation.getContactNumber());
    System.out.println( "Order placed: " + customerInformation.isOrderInProcess());
  5. Start the Local Cache 'myCache'.
  6. Run the project.
See Also
Using Cache Dependency | Expiring Cached Items | Using Bulk Operations | Using Data Grouping


Topic: Group/Subgroup

Group/Subgroup

Data grouping is a way to manage related objects in logical 'groups'. Every object being added to the cache can be tagged with a group identifier. Objects with same group identifier logically belong to the same group, and can be identified by the group. The current version of NCache supports only two levels of grouping, a top level group and then its sub-groups. Include the following import statement in your project for using data groups:
import com.alachisoft.ncache.web.caching.*;
For Adding an item to a Data Group
The following code adds an item to data group 'sub-zero' inside group 'zero'.
Cache _cache = NCache.initializeCache("Cache");
Object value = "Can contain any Type";
_cache.add("Customer:David:1001", value, "my-group", "my-subGroup");
For Updating an item in a Data Group
The following code updates an item in data group 'sub-zero' inside group 'zero'.
Cache _cache = NCache.initializeCache("Cache");
Object value = "Can contain any Type";
_cache.insert("Customer:David:1001", value, "my-group", "my-subGroup");
For Retrieving list of Data Group Keys
The following code retrieves list of items included in group 'zero'.
Cache _cache = NCache.initializeCache("Cache");
Collection keys = _cache.getGroupKeys("my-group", "my-subGroup");
for(Object var : keys.toArray() )
{
System.out.print(var);
}
For Emptying a Data Group
The following code removes all items from data group 'sub-zero' inside group 'zero'.
Cache _cache = NCache.initializeCache("Cache");
_cache.removeGroupData("my-group", "my-subGroup");
See Also
Adding Items to the Cache | Deleting Items from the Cache | Getting notified when an item is removed


Topic: Tags

Tags

NCache provides facility of Tags which acts as an identifying mark for the cache items. By Using tags user can Associate one or more keywords with cache objects. Therefore, one can get and remove items on the basis of Tags.
Include the following import statement in your project before using Tags:
import com.alachisoft.ncache.runtime.caching.*;
Following code example explains how to use Tags:
Initialize cache and tags:
// Initialization Cache and Defining Tags
Cache _cache = NCache.initializeCache("Cache");
Object value = "Can contain any type";
Tag[] tagList = new Tag[6];
tagList[0] = new Tag("tag1");
tagList[1] = new Tag("tag2");
tagList[2] = new Tag("tag3");
tagList[3] = new Tag("tag4");
tagList[4] = new Tag("tag5");
tagList[5] = new Tag("tag6");
Add items to cache containing tags:
// Adding items having Tags
_cache.add("Key1", value, tagList);
_cache.add("Key2", value, tagList);
_cache.add("Key3", value, tagList);
Get keys from cache containing tag:
// Continuing previous...
// Here you can get keys having tags by three different methods.
Collection keys = _cache.getKeysByTag(tagList[0]);
Collection keys = _cache.getKeysByAllTags(tagList);
Collection keys = _cache.getKeysByAnyTag(tagList);
Get items from cache containing tag:
// Continuing previous...
// Here you can get items having tags by three different methods.
HashMap tagHashMap = _cache.getByTag(tagList[0]);
HashMap tagHashMap = _cache.getByAllTags(tagList);
HashMap tagHashMap = _cache.getByAnyTag(tagList);
Remove items from cache containing tag:
// Continuing previous ...
// Here you can remove items having tags by three different methods.
_cache.removeByTag(tagList[0]);
_cache.removeByAllTags(tagList);
_cache.removeByAnyTag(tagList);
See Also
Adding Items to the Cache | Deleting Items from the Cache | Getting notified when an item is removed


Topic: Named Tags

Named Tags

NCache provides feature of “Named Tags” through which user will be able to associate keyword(s) with the cache items. These keywords will act as an identifying mark for the cache items and will be used for querying the cache data.
"Named Tags" is the enhancement of "Tags". Consider a scenario where user needs to store an object in a textual form such as "xml", he will not be able to search that object using tags. The limitation of tags is that it can only have text values and only one attribute i.e. $Tag$. With named tags user will be able to store additional information (of any type) required to query the object stored as string.
Here users are supposed to provide the list of named tags, each having two parameters, "key" (name of a tag) as string and "value" (assigned value) as any primitive type. NCache then allows you to search your objects through these named tags.
“NamedTagsDictionary” class will be used to define Named Tags which will be added with the cache items for further use. Only String is allowed as a Named Tag “keys” and primitive data types are allowed as valid Named Tag “values”.
To use the Named Tags, include the following import statements in your project:
import com.alachisoft.ncache.runtime.caching.NamedTagsDictionary;
Initialize cache and Named Tags:
Cache mycache = NCache.initializeCache("mycache");
mycache.clear();
NamedTagsDictionary nameTag1 = new NamedTagsDictionary();
nameTag1.add("Name", "Alex");
nameTag1.add("Age", 25);
nameTag1.add("Salary", 10000.50);
Add item to cache with Named Tags:
mycache.add("key1", "Customer", nameTag1);
Insert item to cache with Named Tags:
mycache.insert("key-1", "Employee", nameTag1);
Using Query string for searching cache items with respect to Named Tags:
String queryString = "SELECT $Text$ WHERE this.Age = ? AND this.Name = ? AND this.Salary = ?";
HashMap values = new HashMap();
values.put("Age", 10);
values.put("Name", "alex");
values.put("Salary", 10000.25);
HashMap dict = _cache.searchEntries(queryString, values);
if (dict.size() > 0)
{
Iterator ide = dict.entrySet().iterator();
while (ide.hasNext())
{
Map.Entry entry = (Map.Entry)ide.next();
String key = (String) entry.getKey();
Person prs = (Person) entry.getValue();
HandlePerson(prs);
System.out.println("Key = " + key + ", Age: " + prs.Age);
}
}
Note:
Here $Text$ represents the textual data in a cache. If Named Tags are associated with some string value then this syntax can be used in queries. $Text$ is independent of client and can return values added by both .Net and Java clients. If Named Tags are associated with “int” or any other data type then specific syntax to that type will be used. For example for "int" data type System.Int32 will be used to query Named Tags.
See Also
Adding Items to the Cache | Deleting Items from the Cache | Getting notified when an item is removed


Topic: Locking Cached Items

Locking Cached Items

Locking prevents multiple clients from updating the same data simultaneously and also provides data consistency. A proper locking mechanism is necessary to ensure data consistency when there is a possibility of multiple clients accessing and possibly modifying the same data at the same time.
NCache provides an exclusive lock mechanism where once a client request acquires a lock for a particular data item, it blocks every other client until lock is released. Locks can also be forcefully released. A lockId and lockdate is associated with every locked item and are verified every time a locked item is accessed.
Include the following import statement in your project for using locking:
import com.alachisoft.ncache.web.caching.*;
Following are the methods that can be used to implement locking in an application.
Method Name
Parameters
Description
Get
string key, Timespan lockTimeout, ref lockHandle lockHandle, bool acquireLock
Gets cached item and can also acquire a lock on it if value of acquireLock parameter is true. key is a key of item to get.
lockTimeout is time span after which the lock will be released automatically.
lockHandle is an object of the lockHandle class which contains all the information about lock.
acquireLock determines whether to acquire lock or not.
Cache _cache = NCache.initializeCache("myCache");
TimeSpan timeSpan = new TimeSpan();
timeSpan.setSeconds( 10 );
// Acquires lock for specified time
Object lockedItem = _cache.get("Customer:David:1001", timeSpan, new LockHandle(), true);
Insert
string key, CacheItem item, lockHandle lockHandle, bool releaseLock
Inserts an item in cache and can also release a lock if item was locked. key is a key of item to insert.
item is a an item to insert into cache.
lockHandle is an object of the lockHandle class which contains all information about the lock.
releaseLock determines whether to release a lock or not on successful insert.
Cache _cache = NCache.initializeCache("myCache");
CacheItemVersion cItem = _cache.insert("Customer:David:1001", new CacheItem("Can Contain any type"), new LockHandle(), true);
Remove
string key, lockHandle lockHandle
Removes an item from cache. key is a key of item to release lock.
lockHandle is an object of the lockHandle class which contains all information about the lock.
Cache _cache = NCache.initializeCache("myCache");
// Populates Cache
_cache.remove("Customer:David:1001", new LockHandle());
Lock
string key, Timespan lockTimeout, out lockHandle lockHandle
Locks cached item. key is a key of item to acquire a lock.
lockTimeout is time span after which the lock will be released automatically.
lockHandle is an object of the lockHandle class which contains all information about the lock.
Cache _cache = NCache.initializeCache("myCache");
TimeSpan lockForTime = new TimeSpan();
lockForTime.setSeconds( 10 );
bool isLocked = _cache.lock("Customer:David:1001", lockForTime, new LockHandle());
if (!isLocked) // if Lock is not acquired
{
// If lock was unsuccessful, lock.getLockId() returns the ID of the already existing lock
String lockId = lock.getLockId();
}
UnLock
string key
Forcefully unlocks the cached item. key is a key of item to release lock.
Cache _cache = NCache.initializeCache("myCache");
_cache.unlock("Customer:David:1001");
UnLock
string key, lockHandle lockHandle
Unlocks cached item. key is a key of item to release lock.
lockHandle is an object of the lockHandle class which contains all information about the lock.
Cache _cache = NCache.initializeCache("myCache");
_cache.unlock("Customer:David:1001", "specific Lock ID");
NCache will ignore the locks if other overloads of Get, Insert and Remove methods are called.
See Also
Specify Expiration | Specify Priority | Group/Subgroup


Topic: Cache Item Version

Cache Item Version

CacheItem Version is a property associated with every cache item. It is basically a numeric value that is used to represent the version of cached item which changes with every update to an item. This property allows user to track any changes occurred (by some clients) to an item while it is been fetched and updated by other client.
NCache first reads item version before updating it. It will update only if the item version is same i.e. only latest version is stored in the cache. As clusters are of distributed nature, so there could be a possibility that some cache clients might not have updated copy of item. So for concurrency reasons CacheItemVersion class is very important to be implemented. Following are the steps to use cache item version:
  1. Include the following import statements in your project for using item versioning:
    import com.alachisoft.ncache.web.caching.*;
    import java.util.*;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    import java.io.Serializable;
    public class Customer implements Serializable
    {
    ....
    }
  4. Now insert the following code in the 'Main' of the project.
Cache _cache = NCache.initializeCache("mycache");
_cache.clear();
Customer customer = new Customer();
customer.Name = "David";
customer.Id = 1001;
customer.OrderPlaced = "C-11";
customer.City = "New York";
CacheItem cItem = new CacheItem(customer);
//Add Item to Cache
CacheItemVersion version1 = _cache.add("Customer:David:1001", cItem);
// Update the Cache Item, to change the CacheItemVersion
customer.Name = "David";
customer.Id = 1001;
customer.OrderPlaced = "C-11";
customer.City = "London";
GetIfNewer:
Here is how you can retrieve items from the cache
//Update Cache Item Version
CacheItemVersion version2 = _cache.insert("Customer:David:1001", cItem);
Object obj = _cache.getIfNewer("Customer:David:1001", version1);
if (obj == null)
{
System.out.println("Value not updated");
}
else
{
System.out.println("Current Version of Customer:David:1001 is: " + version1.getVersion());
}
Remove:
Here is how you can remove items from the cache.
//Update Cache Item Version
CacheItemVersion version3 = _cache.insert("Customer:David:1001", cItem);
//Remove only if the local Client has the latest Version
Object objGet = _cache.remove("Customer:David:1001", version3);
if (objGet == null)
{
System.out.println("Item not removed from the cache. Newer Version of Item exists");
}
else
{
System.out.println("Item Removed from the cache");
}
Update:
Here is how you can get the latest items from the cache.
//Update Cache Item Version
CacheItemVersion version4 = _cache.insert("Customer:David:1001", cItem);
//Get only if the local Client has the latest Version
Object objGet = _cache.get("Customer:David:1001", version1);
if (objGet == null)
{
System.out.println("Item version updated");
}
else
{
System.out.println("Value not updated");
}
5. Start the Local Cache 'myCache'.
6. Run the project.
See Also
Specify Expiration | Specify Priority | Group/Subgroup


Topic: Streaming API

Streaming API

NCache API now allows you to read and write binary data stream in the cache. NCache has implemented a CacheStream which is a replacement of Java input/output streaming, CacheStream provides major functionality of streaming in NCache. However, it does not support 'seeking' which is the querying and modifying of the current position within a stream. Include the following import statements in your project for using stream:
import com.alachisoft.ncache.web.caching.*;
Open Stream:
To open a stream with respect to a specific Key in Cache, the GetStreamMethod is used where three different StreamModes can be defined.
Cache _cache = NCache.initializeCache("myCache");
CacheStream stream;
stream = _cache.GetCacheStream("Customer:David:1001", StreamMode.Read);
Once the stream is obtained, normal streaming operations can be applied, some of them explained below.
Close Stream:
After using the stream in any mode, users are expected to close the stream in order to release the lock.
Cache _cache = NCache.initializeCache("myCache");
CacheStream stream;
stream = _cache.GetCacheStream("Customer:David:1001", StreamMode.Read);
//Do some operation
stream.Close();
Read Stream:
Read mode can either be acquired with lock or without lock. In read with lock mode, multiple read operations can be performed simultaneously on a stream but no write operation is allowed in this mode. While in read without lock, write operations can be done parallel to read operations.
Read with Lock: Multiple read operations can be performed on a stream, no write operation is allowed in this mode. CacheStream Reader class will throw an exception if stream is already in use by other application.
Cache _cache = NCache.initializeCache("myCache");
CacheStream stream;
byte [] readBuffer = new byte [1024];
int readCount;
stream = _cache.GetCacheStream("Customer:David:1001", StreamMode.Read);
readCount = stream.Read(readBuffer, 0, readBuffer.length);
// Do operations ...
stream.Close();
Read Without Lock: Multiple read and write operations can be performed on the stream acquired.
Cache _cache = NCache.initializeCache("myCache");
CacheStream stream;
byte [] readBuffer = new byte [1024];
int readCount;
stream = _cache.GetCacheStream("Customer:David:1001", StreamMode.ReadWithoutLock);
readCount = stream.Read(readBuffer, 0, readBuffer.length);
// Do some operations ...
stream.Close();
Write Stream:
In write mode only single write operation can be performed on a stream. No read operation is allowed in this mode. CacheStream Writer class will throw an exception if stream is already in use by other application.
Cache _cache = NCache.initializeCache("myCache");
CacheStream stream;
byte [] writeBuffer = new byte [1024];
stream = _cache.GetCacheStream("Customer:David:1001", StreamMode.Write);
stream.Write(writeBuffer, 0, writeBuffer.length);
stream.Close();
Get Stream Length
After Reading a stream, its current length can be obtained. Its return typed is 'long' and it simply returns how many bytes does it contain. Exception 'IllegalAccessException' is thrown if it is called after closing the stream.
Cache _cache = NCache.initializeCache("myCache");
CacheStream stream;
stream = _cache.GetCacheStream("Customer:David:1001", StreamMode.Read);
stream.Ready();
long length = stream.Length();
See Also
Adding Items to the Cache | Deleting Items from the Cache | Getting notified when an item is removed


Topic: Bulk Operations

Bulk Operations

Where the normal add, insert and remove methods let you work with single key-value pairs, bulk operations let you add, update or remove a collection of key-value pairs in a single method call. The idea behind bulk operations is to minimize the cluster traffic by bundling multiple operations into a single call. This is handy if you want to work with collection of items.
Note: Here users are supposed to provide unique keys for all bulk operations.
  1. Include the following import statements in your project:
    import com.alachisoft.ncache.web.caching.*;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    import java.io.Serializable;
    public class Customer implements Serializable
    {
    ....
    }
  4. Now insert the following code in the 'Main' of the project.
    Adding Collection of Items:
    Performing a bulk fetch gives back a dictionary object. Items which are not present in cache, are not returned in the dictionary
    Cache _cache = NCache.initializeCache("myCache");
    _cache.clear();
Customer customer = new Customer();
customer.name = "David";
customer.customerID = 1001;
customer.setCity("London");
customer.setContactNumber("+44-xxx-xxxx-xxxx");
customer.setOrderInProcess(true);
Customer customer1 = new Customer();
customer1.name = "Alex";
customer1.customerID = 1002;
customer1.setCity("Chicago");
customer1.setContactNumber("+44-xxx-xxxx-xxxx");
customer1.setOrderInProcess(false);
String[] keys = new String[] {"Customer:David:1001", "Customer:Alex:1002"};
CacheItem[] items = new CacheItem[2];
items[0] = new CacheItem(customer);
items[1] = new CacheItem(customer1);
//Add items to cache in Bulk
_cache.addBulk(keys, items, DSWriteOption.None, null);
Retrieving Collection of Items:
The following code retrieves a collection of items from cache.
//Get items from cache in Bulk
public HashMap getBulk(String[] keys, String provideName, DSReadOption dsReadOption)
for(Iterator iter = object_recieved.values().iterator(); iter.hasNext();)
{
Customer customerInformation = (Customer)iter.next();
System.out.println("Customer ID: " + customerInformation.customerID);
System.out.println("Name: " + customerInformation.name);
System.out.println("City: " + customerInformation.getCity());
System.out.println("Contact Number: " + customerInformation.getContactNumber());
System.out.println("Order placed: " + customerInformation.isOrderInProcess());
System.out.println();
}
Updating Collection of Items:
The following code updates a collection of items in cache.
//Update items to cache in Bulk
_cache.insertBulk(keys, items, DSWriteOption.None, null);
HashMap object_recieved = _cache.getBulk(keys, DSWriteOption.None, null);
for(Iterator iter = object_recieved.values().iterator(); iter.hasNext();)
{
Customer customerInformation = (Customer)iter.next();
System.out.println("Customer ID: " + customerInformation.customerID);
System.out.println("Name: " + customerInformation.name);
System.out.println("City: " + customerInformation.getCity());
System.out.println("Contact Number: " + customerInformation.getContactNumber());
System.out.println("Order placed: " + customerInformation.isOrderInProcess());
System.out.println();
}
Removing Collection of Items:
Performing a bulk remove is very much similar to a bulk fetch operation. Items not in the cache are not returned in the dictionary.
//Remove items from cache in Bulk
HashMap object_recieved = _cache.removeBulk(keys, DSWriteOption.None, null);
for(Iterator iter = object_recieved.values().iterator(); iter.hasNext();)
{
Customer customerInformation = (Customer)iter.next();
System.out.println("Customer ID: " + customerInformation.customerID);
System.out.println("Name: " + customerInformation.name);
System.out.println("City: " + customerInformation.getCity());
System.out.println("Contact Number: " + customerInformation.getContactNumber());
System.out.println("Order placed: " + customerInformation.isOrderInProcess());
System.out.println();
}
Deleting Collection of Items:
The following code deletes a collection of items from the cache. This API performs the same functionality as "removeBulk" but it does not return any value.
//Delete items from the cache in Bulk
_cache.deleteBulk(keys, DSWriteOption.None, null);
  1. Start the Local Cache 'myCache'.
  2. Run the project.
See Also
Adding Items to the Cache | Deleting Items from the Cache | Getting notified when an item is removed


Topic: Async Operations

Async Operations

NCache provides the facility of providing Cache operations asynchronously so that maximum performance can be achieved. Following are the simple coding example implementing Async operations.
  1. Include the following import statements in your project:
    import com.alachisoft.ncache.web.caching.*;
  2. Create a new Class named 'Customer' in your already created Test Application.
  3. Insert the following code in the 'Customer' class.
    import java.io.Serializable;
    public class Customer implements Serializable
    {
    …
    }
  4. Now insert the following code in the 'Main' of the project:
    Cache _cache = NCache.initializeCache("myCache");
    _cache.clear();
    Customer customer = new Customer();
    customer.name = "David";
    customer.customerID = 1001;
    customer.setCity("London");
    customer.setContactNumber("+44-xxx-xxxx-xxxx");
    customer.setOrderInProcess(true);
    For Adding item in a cache asynchronously
    // Add Item to Cache asynchronously
    _cache.addAsync(String key, CacheItem item, DSWriteOption dsWriteOption, DataSourceItemsAddedCallback onSourceItemAdded);
    Thread.sleep(1000);
    Object object_Customer = _cache.get("Customer:David:100");
    Customer customerInformation = (Customer)object_Customer;
    System.out.println("Customer ID: " + customerInformation.customerID);
    System.out.println("Name: " + customerInformation.name);
    System.out.println("City: " + customerInformation.getCity());
    System.out.println("Contact Number: " + customerInformation.getContactNumber());
    System.out.println("Order placed: " + customerInformation.isOrderInProcess());
    For Updating item in a cache asynchronously
    // Update Item to Cache asynchronously
    _cache.insertAsync((String key, Object value, AsyncItemUpdatedCallback asyncItemUpdatedCallback,
    String group, String subGroup);
    Thread.sleep(1000);
    Object object_Customer = _cache.get("Customer:David:100");
    Customer customerInformation = (Customer)object_Customer;
    System.out.println("Customer ID: " + customerInformation.customerID);
    System.out.println("Name: " + customerInformation.name);
    System.out.println("City: " + customerInformation.getCity());
    System.out.println("Contact Number: " + customerInformation.getContactNumber());
    System.out.println("Order placed: " + customerInformation.isOrderInProcess());
    For Removing item from a cache asynchronously
    // Remove Item from Cache asynchronously
    _cache.removeAsync(String key, AsyncItemRemovedCallback asyncItemRemovedCallback, DSWriteOption dsWriteOption, DataSourceItemsRemovedCallback onDataSourceItemRemoved);
    For Clearing cache asynchronously
    // Clear Cache asynchronously
    _cache.clearAsync(DSWriteOption dsWriteOption, AsyncCacheClearedCallback onAsyncCacheCleared, DataSourceClearedCallback onDataSourceCleared);
  5. Start the Local Cache 'myCache'.
  6. Run the project.
See Also
Adding items with priority settings | Using Bulk Operations | Using Data Grouping


Topic: Cache Dependency

Cache Dependency

Caching can depend on several items which include file, database table rows, query strings, and also other cached items. If you add an item to the Cache with a dependency, when the dependency changes, the item automatically removes from the Cache. You can add items with dependencies to your application's cache with the Add and Insert methods.
In This Section
Using Key Dependency
Explains way to associate one cached item with another item in a cache.
Using File Dependency
Describes how to set the validity of a cache item based on an external file/files.
Using Aggregate Dependency
Describes how to set the aggregate dependency for a cache item.
Using SqlCacheDependency
Represents keeping the cached items synchronized with the SQL database.
Using Oracle Dependency
Represents keeping the cached items synchronized with the Oracle database.
Using OLEDB Cache Dependency
Explains how you can maintain the cached items synchronized with any of the database
See Also
Expiring cached items
Describes how certain cached items can be automatically removed from the cache when required.
Adding items with priority settings
Explains adding items in the cache with priority settings.
Using Bulk Operations
Describes performing bulk operations to add, insert or remove collection of items in a single method call. It helps speeding up the process and minimizes cluster traffic.
Using Data Grouping
Presents distributing related objects in 'logical' groups.


Topic: Key Dependency

Key Dependency

Key based dependency associates one cached item with another item in the cache. It invalidates the dependent item when that particular item changes. Whenever that item is removed or updated from the cache, associated object will be expired. Key based dependency is cascaded. For example, if key1 depends on key2, key2 depends on key3 and key3 depends on key4, then removal of k4 will result in expiration of key1, key2 and key3.
Add the following import statement in your project:
import com.alachisoft.ncache.web.caching.*;
import com.alachisoft.ncache.runtime.dependencies.*;
The following code explains the implementation.
Cache _cache = NCache.initializeCache("myCache");
_cache.add("Key-1", "Base Value");
String[] cacheKeys = new String[1];
cacheKeys[0] = "Key-1";
// Adding cache item "Key-2" dependant on another cache item "Key-1"
_cache.add("Key-2", "dependant item", new KeyDependency(cacheKeys), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal);
// Removing/Deleting/Updating key: "Key-1" will automatically make all of its dependant keys removed, here it's "Key-2"
System.out.println("Removing key \"Key-1\"");
Object removedObject = _cache.remove("Key-1");
System.out.println("value \"" + removedObject.toString() + "\" removed");
if (_cache.contains("Key-2"))
{
System.out.println("ERROR: cache Key: Key-2 not removed,/n Please read Help from NCache for further details or contact support@alachisoft.com");
}
else
{
System.out.println("Cache Key: \"Key-2\" does not exist, item removed once the base key was removed from Cache");
}
See Also
Using File Dependency | Using SqlCacheDependency | Using OLEDB CacheDependency


Topic: File Dependency

File Dependency

We can set the validity of the cache item based on an external file or files. When this resource changes, the cached object becomes obsolete and is removed from the cache. In File Dependency object, a File/Directory path is provided. Cache object also expires if the path is used to create a new File/Directory. Following steps demonstrate how to use file based dependency.
The following steps demonstrate how to use file based dependency:
  1. Create a text file with name NCache.txt at path C:\ i.e C:\NCache.txt .
  2. Add the following import statement in your project:
    import com.alachisoft.ncache.web.caching.*;
    import com.alachisoft.ncache.runtime.dependencies;
  3. Copy and run the following code in Java environment.
  4. When prompted "Enter when done", either Remove, Modify or Rename the file, C:\NCache.txt, then press Enter, the dependant key will be removed from the Cache automatically.
Cache _cache = NCache.initializeCache("myCache");
_cache.clear();
// Adding cache item "dependantItemOnFile" dependant on file C:\NCache.txt
_cache.add("dependantItemOnFile", "dependant", new FileDependency("C:\NCache.txt"), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal);
if (_cache.contains("dependantItemOnFile"))
{
System.out.println("cache Key: \"dependantItemOnFile\" exists");
}
// Wait for file removal, deletion or modification to show File based dependency
System.out.println("Remove/Rename/Modify file C:\NCache.txt/nPress Enter when done");
System.in.read();
if (_cache.contains("dependantItemOnFile"))
{
System.out.println("ERROR: cache Key: \"dependantItemOnFile\" not removed,/n Please read Help from NCache for further details or contact support@alachisoft.com");
}
else
{
System.out.println("cache Key: \"dependantItemOnFile\" does not exist, item removed since the file C:\NCache.txt was either Removed, Renamed or Modified");
}
See Also
Using Key Dependency | Using SqlCacheDependency | Using OLEDB CacheDependency


Topic: Aggregate Dependency

Aggregate Dependency

Aggregate Cache Dependency associates one cached item with collection of dependency objects which can be CacheDependency objects, DBCacheDependency objects or any combination of these. The AggregateCacheDependency monitors collection of dependency objects so that when any of them changes, the cached object becomes obsolete and is removed from the cache.
Aggregate Cache Dependency allows you to associate multiple dependencies of different types with a single cached item. For example, you can associate key dependency and file dependency with an item using aggregate dependency by creating an instance of the AggregateCacheDependency class with each dependency added to it. You can then use a single Insert call to make the item dependent on the AggregateCacheDependency instance.
Add the following import statement in your project:
import com.alachisoft.ncache.web.caching.*;
import com.alachisoft.ncache.runtime.dependencies.*;
The following code explains the implementation.
Cache _cache = NCache.initializeCache("mycache");
_cache.clear();
Customer customer = new Customer();
customer.Name = "David";
customer.Id = 1001;
CacheItem cItem = new CacheItem(customer);
//Adding a key to create Dependency on
_cache.add("Customer:David:1001", cItem);
//Customer Steve is dependant on David
customer = new Customer();
customer.Name = "Steve";
customer.Id = 1002;
cItem = new CacheItem(customer);
//Initializing Aggregate Dependency; CacheItem dependent on File and Key
AggregateCacheDependency aggregateDependency = new AggregateCacheDependency();
aggregateDependency.getDependencies().add(new FileDependency("C:\\customer.config"));
aggregateDependency.getDependencies().add(new KeyDependency("Customer:David:1001"));
cItem.setCacheDependency(aggregateDependency);
_cache.add("Customer:Steve:1002", cItem);
//Updating Key Customer:David:1001
customer = new Customer();
customer.Name = "David";
customer.Id = 1001;
cItem = new CacheItem(customer);
_cache.insert("Customer:David:1001", cItem);
Thread.sleep(1000);
//Key will be removed since it's dependant Key has been updated
if (!_cache.contains("Customer:Steve:1002"))
{
System.out.println("Cache Key: Customer:Steve:1002 does not exist, item removed once the base key or file is removed/deleted/updated from Cache");
}
else
{
System.out.println("ERROR: cache Key: Customer:Steve:1002 not removed,/n Please read Help from NCache for further details or contact support@alachisoft.com");
}
See Also
Using File Dependency | Using SqlCacheDependency | Using OLEDB CacheDependency


Topic: Cache Sync Dependency

Cache Sync Dependency

Cache sync dependency provides a way to synchronize two caches, so an item updated or removed from one cache has same affect in synchronized cache. For example, you can have a Local Cache that keeps items frequently used by application and a Clustered Cache that keeps larger number of items being shared with other applications. And, your local items are kept synchronized with the clustered cache so you never have any data integrity problems while improving your app performance even further.
Add the following import statement in your project:
import com.alachisoft.ncache.web.caching.*;
import com.alachisoft.ncache.runtime.dependencies.*;
Following code snippet shows how CacheSyncDependency can be utilized:
Cache cache1 = NCache.initializeCache("myReplicatedCache");
Cache cache2 = NCache.initializeCache("myCache");
cache1.clear();
cache2.clear();
cache1.add("Customer:David:1001", "Value1");
// Creating CacheItem, with CacheSyncDependency assigned
CacheItem cItem = new CacheItem("Value1");
CacheSyncDependency cdb = new CacheSyncDependency("myReplicatedCache", "Customer:David:1001");
cItem.setCacheSyncDependency(cdb);
cache2.add("Customer:Alex:1002", cItem);
// Now whenever 'Customer:David:1001' in myReplicatedCache is changed it will be updated in myCache against Key: "Customer:Alex:1002"
System.out.println("Updating Value of Customer:David:1001 in myReplicatedCache to 'UpdatedValue-Check' ");
cache1.insert("Customer:David:1001", "UpdatedValue-Check");
// The value of key Customer:Alex:1002 will be updated automatically
System.out.println("Key Customer:Alex:1002 Updated with Value: " + cache.get("Customer:Alex:1002").toString());
See Also
Using Key Dependency | Using File Dependency | Using SqlCacheDependency | Using OLEDB CacheDependency


Topic: SQL Cache Dependency

SQL Yukon Dependency

While working with databases in a multiuser environment, updates are very frequent in database. When cache is involved, you need to keep cached items synchronized with the database. One possible solution is that, on every update, database itself notifies the cache and cache expires the out of synch items. Sql Yukon Dependency is provided by NCache for this purpose. Item expires if result of the command (based on command text) changes. SQLYukonDependency is only available in NCache CLR 2.0 and requires SQL Server 2005.
Following is the step-by-step guide for using SQLCacheDependency.
Enabling Database Notification:
Enable the service broker in SQL Server 2005 or above before NCache can use SqlCacheDependency. This allows SQL Server 2005 to send event notifications to NCache to let it know that data has changed in the database.
[SQL]
ALTER DATABASE Northwind SET ENABLE_BROKER;
GO
To verify that the broker is running you can check properties in the databaseserver using SQL Management studio or run the following query:
select is_broker_enabled from sys.databases where name = '<dbname>'
Make sure that you get "1" for the database you intend to use.
Database Permissions :
If you are not a database owner (dbo) then please enable following permissions in order to use NCache SQL cache dependency. Database permissions are defined for two different modes: Default mode and Custom mode. In Default mode SQLDependency will create the SQL Service and Queue at run time. Custom mode is used by those clients who want to use SQLDependency without Service and Queue creation rights. In this case SQLDependency will not create the SQL Service and Queue at run time and clients are supposed to create it for each NCache process.
For Default Mode:
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO <database_principal>
GRANT CREATE QUEUE TO <database_principal>
GRANT CREATE SERVICE TO <database_principal>
GRANT CREATE PROCEDURE TO <database_principal>
For Custom Mode:
CREATE QUEUE "NCacheSQLQueue-[IP-Address]";
CREATE SERVICE "NCacheSQLService-[IP-Address]"
ON QUEUE "NCacheSQLQueue-[IP-Address]"
([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]);
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO [User Name];
GRANT RECEIVE ON "NCacheSQLQueue-[IP-Address]" TO [User Name];
GRANT RECEIVE ON QueryNotificationErrorsQueue TO [User Name] ;
GRANT SEND ON SERVICE :: "NCacheSQLService-[IP-Address]" to [User Name] ;
Note:
  • Replace [IP-Address] with node ip address and [User Name] with database user name.
  • In a clustered environment, users are supposed to create SQL Service and Queue per NCache process.
  • You can also create required SQL Service and Queue using script "NCacheServiceQueue.sql" located at "%Install Directory%/NCache/bin/resources".
Using Dependency:
  1. Create a Java project in any Java environment.
  2. Add reference of NCClient from installationFolder../NCache/java/lib/
  3. Add the following import statement in your project:
    import com.alachisoft.ncache.web.caching.*;
    import com.alachisoft.ncache.runtime.dependencies.*;
  4. Declare a variable "_cache" in the code and initialize it with "sqlDependencyCache", and clear it if this cache was used previously.
    Cache _cache = NCache.initializeCache("sqlDependencyCache");
    _cache.clear();
  5. Create a String "connectionString" containing information to connect with SQL database e.g.
    String connectionString ="Data Source=Computer_Name//SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;";
  6. Create a dependency and add it to the cache.
    CacheDependency sqlSync = new SqlCacheDependency(connectionString, "SELECT ProductID FROM dbo.Products WHERE ProductID = 006");
    _cache.insert("ProductID:006" , "my Item" , sqlSync, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal);
  7. Now update the key "6" of the Database table using the following SQL command.
    [SQL]
    UPDATE Products SET ProductName = 'Modified Product' WHERE ProductID =6
  8. This invalidates cacheKey Dependant-ProductID6 " and is removed by NCache.
    Note : If SQL Server goes down/restarts, all dependencies become invalid and are removed from the cache .
See Also
Using DbCacheDependency


Topic: Oracle Cache Dependency

Oracle Cache Dependency

While working with databases in a multiuser environment, updates are very frequent in the databse. When cache is involved, you need to keep cached items synchronized with the database. One possible solution is that, on every update database itself notifies the cache and cache expires the out of synch items. Oracle Dependency is provided by NCache for this purpose. Item expires if result of the command (based on command text) changes. Oracle Dependency is only available for Oracle database 10g release 2 or later.
Following is the step-by-step guide for using OracleCacheDependency.
Enabling Database Notification:
Grant CHANGE NOTIFICATION privilege to the user to create a notification registration. Following statement grants the CHANGE NOTIFICATION privilege to the user.
[SQL]
"grant change notification to scott"
Using Dependency:
  1. Create a Java project in any Java environment.
  2. Add reference of NCClient from installationFolder../NCache/java/lib/
  3. Add the following import statement in your project:
    import com.alachisoft.ncache.web.caching.*;
    import com.alachisoft.ncache.runtime.dependencies.*;
  4. Declare a variable "_cache" in the code and initialize it with "oracleDependencyCache", and clear it if this cache was used previously
    Cache _cache = NCache.initializeCache("oracleDependencyCache");
    _cache.clear();
  5. Create a String "connectionString" containing information to connect with Oracle database e.g.
    String connectionString = "User Id=scott;Password=tiger;Data Source=oracle" ;
  6. Create a dependency and add it to the cache.
    CacheDependency orclSync = new OracleCacheDependency(connectionString, "SELECT CustomerID FROM Customers WHERE CustomerID = 006");
    _cache.insert("Customer:David:006", "my Item" , orclSync, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal);
  7. Now update the key "6" of the Database table using the following Oracle command.--[SQL]
    UPDATE Customers SET Customer Name = 'Modified Customer' WHERE CustomerID =6
  8. This invalidates cacheKey " Dependant-CustomerID6 " and is removed by NCache.
Note: In Oracle 10g, database change notifications are only object based. This means that change notifications will be fired if any row is modified in object. Therefore we have to check rowID to confirm if the row changed is the one for which the event is registered. RowID's cannot be retrieved unless explicitly included in query. Therefore, customer has to include rowID in query that he/she is registering with OracleDependecy, otherwise change notification will be fired if any row is modified in table.
When rowID is included in query like: select rowID, productID, productname, unitprice from Products where ProductID = 220; NCache will save rowID of rows for which change notification is registered. When it receives any change notification, NCache will compare the rowIDs to determine whether the row changed is the one for which the rowID is registered. Otherwise NCache will have no way to check this and items for which change notification is registered will be removed if any row in table changes.
In Oracle 11g both object based and query based (default) notifications are provided. In query based notifications; change of the modified row will be notified only if the change notification is registered for it.
See Also
Using DbCacheDependency


Topic: OLEDB Dependency

DBCache Dependency

DBCacheDependency is used to keep cache items synchronized with any of the database. Prior to its use, you need to enable notifications for the underlying database. For details, see Using DB Cache Dependency For SQL Server , Using DB Cache Dependency For DB2 and Using DB Cache Dependency For Oracle . This is a row based dependency. The cache key is associated with the primary key value of the table. Thus an item expires only if the row with that primary key gets changed.
While using DBCacheDependency for SQL Server, you need to use 'Sql versions' of commands, connections, readers etc. available under 'System.Data.SqlClient' import statement in your client application. For Oracle and DB2, you need to use 'OleDb versions' of commands, connections, readers etc., available under 'System.Data.OleDb' import statement.
Following is the step-by-step guide for using DBCacheDependency. The example given is for SQL Server, however, Oracle and DB2 databases can also be used with little modifications.
See Also
Enabling Notifications For SQL Server | Enabling Notifications For DB2 | Enabling Notifications For Oracle | Using Sql Yukon Dependency


Topic: Enabling Notifications For SQL Server

Enabling Notifications For SQL Server

For enabling notifications for SQL Server you need to follow these steps:
  1. Create a table 'ncache_db_sync' having four fields (cache_key VARCHAR, cache_id VARCHAR, modified BIT and work_in_progress BIT). Script to create the table is as follows:[SQL]
    --Create table'ncache_db_sync'
    CREATE TABLE ncache_db_sync (
    cache_key VARCHAR ( 256 ),
    cache_id VARCHAR ( 256 ),
    modified BIT DEFAULT ( 0 ),
    work_in_progress BIT DEFAULT ( 0 ),
    PRIMARY KEY ( cache_key , cache_id ) );
  2. Create UPDATE and DELETE triggers, for every table on which notification is required. They set the 'modified' field of corresponding row in the ncache_db_sync table to 1.To carry out the task, see the following sample script that creates trigger on 'Products' table:
    --create trigger
    CREATE TRIGGER myTrigger
    ON dbo . Products
    FOR DELETE , UPDATE
    AS
    UPDATE ncdbs
    SET modified = 1
    from ncache_db_sync ncdbs
    inner join Deleted old on cache_key = (Cast((old.ProductID) as VarChar)
+ ':dbo.Products' );
Note: cache_key must be the same key that is used to add the corresponding record in the cache.
Now, As soon as an item is added to cache with dependency, a row will be created in table 'ncache_db_sync' for this cache key. We'll have to make sure that the format of cache key while adding into cache is exactly same as defined in the corresponding trigger. For our example, cache key for product id 10 should be like, "10:dbo.Products". Following code demonstrates how to add items with dependency.
  1. Create a new Clustered Cache or a Local Cache in NCache Manager with the name "sqlDependencyCache".
  2. Start the cache "sqlDependencyCache".
  3. Create a Java project in any Java environment.
  4. Add reference of NCClient from installationFolder../NCache/java/lib/
  5. Add the following import statement in your project:
    import com.alachisoft.ncache.web.caching.*;
    import com.alachisoft.ncache.runtime.dependencies.*;
  6. Declare a variable "_cache" in the code and initialize it with "sqlDependencyCache", and clear it if this cache was used previously
    Cache _cache = NCache.initializeCache("sqlDependencyCache");
    _cache.clear();
  7. Create a String "connectionString" containing information to connect with SQL database e.g.
    String connectionString ="Data Source=Computer_Name//SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;";
  8. Create a dependency and add 10 items to the cache
    for ( int i = 0 ; i < 10 ; i++)
    {
    CacheDependency dependency = DBDependencyFactory.CreateSqlCacheDependency(connectionString, Integer.toString(i) + ":dbo.Products");
    _cache.insert(i + ":dbo.Products", i,dependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,CacheItemPriority.Default);
    }
  9. Now update the key "6" of the Database table using the following SQL command:
    [SQL]
    UPDATE Products SET ProductName = 'Modified Product' WHERE ProductID =6
  10. This invalidates cacheKey cache_key 6:dbo.Products and is removed by NCache in ncache_db_sync table.
See Also
Enabling notifications for Oracle tables | Enabling notifications for DB2 tables


Topic: Enabling Notifications For Oracle

Enabling Notifications For Oracle

For enabling notifications for Oracle follow steps given below:
  1. Create a table 'ncache_db_sync' having four fields (cache_key VARCHAR, cache_id VARCHAR, modified BIT and work_in_progress BIT). Script to create the table is as follows:
    --Create table'ncache_db_sync'
    CREATE TABLE NCACHE_DB_SYNC (
    CACHE_KEY VARCHAR2 ( 256 ) NOT NULL ENABLE ,
    CACHE_ID VARCHAR2 ( 256 ) NOT NULL ENABLE ,
    MODIFIED NUMBER ( 2 , 1 ) DEFAULT 0 NOT NULL ENABLE ,
    WORK_IN_PROGRESS NUMBER ( 2 , 1 ) DEFAULT 0 NOT NULL ENABLE ,
    PRIMARY KEY ( CACHE_KEY , CACHE_ID ) ENABLE
    );
  2. Create UPDATE and DELETE triggers, for every table on which notification is required. They set the 'modified' field of corresponding row in the ncache_db_sync table to 1. To carry out the task, see the following sample script that creates trigger on 'Products' table:
    --create trigger
    Create or replace trigger MYTRIGGER
    AFTER
    update or delete on PRODUCTS
    REFERENCING OLD AS oldRow
    for each row
    BEGIN
    UPDATE NCACHE_DB_SYNC
    SET modified = 1
    WHERE cache_key = (: oldRow . ProductID || ':dbo.Products' );
    END TRIGGER ;
    Note: cache_key must be the same key that is used to add the corresponding record in the cache.
    Now, As soon as an item is added to cache with dependency, a row will be created in table 'ncache_db_sync' for this cache key. We'll have to make sure that the format of cache key while adding into cache is exactly same as defined in the corresponding trigger. For our example, cache key for product id 10 should be like, "10:oldRow.Products". Following code demonstrates how to add items with dependence:
  3. Create a new Clustered Cache or a Local Cache in NCache Manager with the name "oracleDependencyCache".
  4. Start the cache "oracleDependencyCache ".
  5. Create a Java project in any Java environment.
  6. Add reference of NCClient from installationFolder../NCache/java/lib/
  7. Add the following import statement in your project:
    import com.alachisoft.ncache.web.caching.*;
    import com.alachisoft.ncache.runtime.dependencies.*;
  8. Declare a variable "_cache" in the code and initialize it with "oracleDependencyCache", and clear it if this cache was used previously
    Cache _cache = NCache.initializeCache("oracle DependencyCache");
    _cache.clear();
  9. Create a String "connectionString" containing information to connect with SQL database e.g.
    String connectionString = "Provider=ORAOLEDB; User Id=SCOTT;Password=TIGER;Data Source=ORACLE";
  10. Create a dependency and add 10 items to the cache:
    for ( int i = 0 ; i < 10 ; i++)
    {
    //Cache key for product id 10 will be "10:dbo.Products"
    CacheDependency dependency = DBDependencyFactory.CreateOleDbCacheDependency(connectionString, Integer.toString(i) + ":oldRow.Products");
    _cache.insert(i + ":oldRow.Products", i, dependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default);
    }
  11. Now update the key "6" of the Database table using the following Oracle command:
    [ORACLE]
    UPDATE Products SET ProductName = 'Modified Product' WHERE ProductID =6
  12. This invalidates cacheKey cache_key 6:oldRow.Products and is removed by NCache in ncache_db_sync table.
See Also
Enabling notifications for SQLServer tables | Enabling notifications for DB2 tables


Topic: Enabling Notifications For DB2

Enabling Notifications For DB2

For enabling notifications for DB2 follow these steps:
  1. Create a table 'ncache_db_sync' having four fields (cache_key VARCHAR, cache_id VARCHAR, modified BIT and work_in_progress BIT). Script to create the table is as follows:
    --Create table'ncache_db_sync'
    CREATE TABLE ncache_db_sync (
    cache_key VARCHAR ( 256 ),
    cache_id VARCHAR ( 256 ),
    modified BIT DEFAULT ( 0 ),
    work_in_progress BIT DEFAULT ( 0 ),
    PRIMARY KEY ( cache_key , cache_id ) );
  2. Create UPDATE and DELETE triggers, for every table on which notification is required. They set the 'modified' field of corresponding row in the ncache_db_sync table to 1. To carry out the task, see the following sample script that creates trigger on 'Products' table:
    --create trigger
    CREATE TRIGGER myTrigger
    ON dbo . Products
    FOR DELETE , UPDATE
    AS
    UPDATE ncache_db_sync
    SET modified = 1
    WHERE cache_key IN
    ( Cast (( Select old . ProductID from DELETED old ) as VarChar ) + ':dbo.Products' );
    Note: cache_key must be the same key that is used to add the corresponding record in the cache.
    Now, As soon as an item is added to cache with dependency, a row will be created in table 'ncache_db_sync' for this cache key. We'll have to make sure that the format of cache key while adding into cache is exactly same as defined in the corresponding trigger. For our example, cache key for product id 10 should be like, "10:dbo.Products". Following code demonstrates how to add items with dependency.
  3. Create a new Clustered Cache or a Local Cache in NCache Manager with the name "sqlDependencyCache".
  4. Start the cache "sqlDependencyCache".
  5. Create a Java project in any Java environment.
  6. Add reference of NCClient from installationFolder../NCache/java/lib/
  7. Add the following import statement in your project:
    import com.alachisoft.ncache.web.caching.*;
    import com.alachisoft.ncache.runtime.dependencies.*;
  8. Declare a variable "_cache" in the code and initialize it with "sqlDependencyCache", and clear it if this cache was used previously.
    Cache _cache = NCache.initializeCache("sqlDependencyCache");
    _cache.clear();
  9. Create a String "connectionString" containing information to connect with SQL database e.g.
    String connectionString = "Provider=SQLOLEDB; Data Source=Computer_Name//SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;";
  10. Create a dependency and add 10 items to the cache
    for (int i = 0; i < 10; i++)
    {
    //Cache key for product id 10 will be "10:dbo.Products"
    CacheDependency dependency = DBDependencyFactory.CreateOleDbCacheDependency(connectionString, Integer.toString(i) + ":dbo.Products");
    _cache.insert(i + ":dbo.Products", i, dependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default);
    }
  11. Now update the key "6" of the Database table using the following SQL command:--
    [SQL]
    UPDATE Products SET ProductName = 'Modified Product' WHERE ProductID =6
  12. This invalidates cacheKey cache_key 6:dbo.Products and is removed by NCache in ncache_db_sync table.
See Also
Enabling notifications for SQLServer tables | Enabling notifications for Oracle tables


Topic: Use DB Dependency with Hibernate

Use DB Dependency with Hibernate

To enable Database Cache Dependency in Hibernate items, you need to define <ncache> configuration section in the application's configuration file (it could be app.config file if it is a desktop application or web.config file if it is a web application) and enable database notifications on the database.
To enable DBCacheDependency in Hibernate, do the following:
  • Include the following import statements in your application:
import com.alachisoft.ncache.runtime.dependencies.*;
import com.alachisoft.ncache.web.caching.*;
  • Provide dbSync type in <ncache> section as follows:
    <ncache>
    <dbSync type = "sqlDependency"/>
    <class name = "hibernator.BLL.Customer">
    <CacheKey format = "Customer:CustomerID:[pk]"/>
    <sqlDependency sql = "select ContactName from dbo.Customers where CustomerID =?"/>
    </class>
    <class name = "hibernator.BLL.Order">
    <CacheKey format = " [pk]:Order"/>
    <sqlDependency sql = "select ContactName from dbo.Orders where OrderID=?"/>
    </class>
    </ncache>
    <ncache> section contains following configurable options to enable Database Cache Dependency:
  • dbsync: The value for dbSync type is either "sqlDependency" or "dbDependency". sqlDependency is a mechanism for synchronizing your cache with SQL Server 2005 database through java events. dbDependency allows you to synchronize your cache with any OLEDB compliant database through a configurable polling interval.
  • CacheKey: You can specify the cache-key format here. The example above shows "Customer:CustomerID:[pk]" which would translate into "Customer:CustomerID:1000" if the CustomerID value of the object is 1000.
  • sqlDependency: If you specify "sqlDependency" value, then you must also specify the <sqlDependency=""/> tag for individual classes in <class> section. You specify a "select" SQL statement to identify a row in SQL Server 2005 database that corresponds to this cached item. Then, whenever that row is updated or removed, this cached item is also removed. The "?" in the command will be replaced with the primary key of the mapped table at runtime.
  • Enable database notifications on the database except when you are using SQL Server 2005. For further details see Enabling Database Notifications for SQL Server , Enabling Database Notifications for Oracle and Enabling Database Notifications for DB2 .
See Also
Expiring cached items | Using NCache with NHibernate


Topic: Event Notifications

Event Notifications

NCache allows client applications to register to be notified whenever add, insert or remove operation is performed against any or selected cache keys, or when some custom event occurs. Similarly, NCache provides events that are fired based upon cluster status. This section is about availing such notifications.
In This Section
Using General Purpose Events
Explains the use of General Purpose Notifications in clusters for add, insert, remove, and clear operations.
Using Item Specific Events
Describes notifying all the subscribers of selective notification event when a single or multiple cache items are updated or removed from the cache.
Using Custom Events
Describes how a producer application can call a single method that invokes handlers on all the subscribers of the custom notification event.
Using Cache Generated Events
Explains writing event handlers to respond to notifications about the cluster status.


Topic: General Purpose Events

General Purpose Events

NCache notifies client applications whenever an add, insert, remove or clear operation is done against the cache. These are cluster-wide notifications, and Java applications can receive them.
Cache Item Added Notification
  1. Create a class with a name (can be any name) 'CacheEventListner' which implements 'CacheListener' from com.alachisoft.ncache.event.
    import com.alachisoft.ncache.web.caching.*;
    import com.alachisoft.ncache.event.*;
    public class CacheEventListner implements CacheListener
    {
    public void cacheCleared()
    {
    System.out.println("Cache Cleared");
    }
    public void cacheItemAdded(CacheEvent ce)
    {
    System.out.println("Cache Item Added");
    }
    public void cacheItemRemoved(CacheEvent ce)
    {
    System.out.println("Cache Item Removed");
    }
    public void cacheItemUpdated(CacheEvent ce)
    {
    System.out.println("Cache Item Updated");
    }
    }
  2. Subscriber of the event needs to register itself to get the notifications. Now simply add an item to get the Notification.
    CacheEventListner cacheListner = new CacheEventListner();
    Cache _cache = NCache.initializeCache("myCache");
    _cache.addCacheEventListener(cacheListner);
    _cache.registerAddNotification();
    _cache.add("Customer:David:1001", "my Item");
See Also
Using Selective Notifications | Using Custom Notifications | Using Event Notifications


Topic: Getting notified when an item is removed

Getting notified when an item is removed

Create a class with a name (could be any name) 'CacheEventListner' which implements ' CacheItemUpdatedCallback' from com.alachisoft.ncache.caching.
import com.alachisoft.ncache.web.caching.*;
public class CacheEventListner implements CacheItemRemovedCallback
{
public void itemRemoved(String string)
{
System.out.println("Cache Key" + string + " is Removed");
}
}
Subscriber of the event needs to register itself to get notifications. Now simply add an item to get the Notification:
CacheEventListner onItemRemoved = new CacheEventListner();
Cache _cache = NCache.initializeCache("myCache");
CacheItem cItem = new CacheItem("my Item");
cItem.setItemRemoveCallback(onItemRemoved);
_cache.insert("x-y-z", "my Item");
See Also
Using Event Notifications | Using Custom Notifications | Using General Notifications


Topic: Getting notified when an item is updated

Getting notified when an item is updated

Create a class with a name (could be any name) 'CacheEventListner' which implements ' CacheItemUpdatedCallback' from com.alachisoft.ncache.caching:
import com.alachisoft.ncache.web.caching.*;
public class CacheEventListner implements CacheItemUpdatedCallback
{
public void itemUpdated(String string)
{
System.out.println("Cache Key" + string + " is Updated");
}
}
Subscriber of the event needs to register itself to get notifications. Now simply add an item to get the Notification:
CacheEventListner onItemUpdated = new CacheEventListner();
Cache _cache = NCache.initializeCache("myCache");
CacheItem cItem = new CacheItem("my Item");
cItem.setItemUpdateCallback(onItemUpdated);
_cache.insert("x-y-z", "my Item");
See Also
Using Event Notifications | Using Custom Notifications | Using General Notifications


Topic: Custom Notifications

Custom Notifications

NCache provides the ability to generate custom notifications. A producer application can call a single method that invokes handlers on all the subscribers of the custom notification event. In a clustered environment, custom notifications are convenient means of communication among the participants of the cluster. Even in local environment, a producer consumer style communication between applications is easily achieved using this facility.
Using custom notifications is a two step process. One is a producer end of the notification and other is a consumer end.
  1. To register we simply implement an interface CustomListener on a class:
    import com.alachisoft.ncache.event.*;
    public class CacheEventListner implements CustomListener
    {
    public void customEventOccured(CustomEvent event)
    {
    System.out.println("Custom EVENT :- Custom event is raised for Key[ " + event.getKey() + " ] with value: " + event.getSource().toString());
    }
    }
  2. The custom notification is simply raised by calling:
    CacheEventListner();
    Cache _cache = NCache.initializeCache("myCache");
    _cache.addCustomEventListener(onItemUpdated);
    _cache.raiseCustomEvent("custom-Object", "Custom.Event");
    _cache.unRegisterCustomNotification();
    _cache.removeCustomEventListener(onItemUpdated);;
See Also
Using Selective Notifications | Using General Notifications | Using Event Notifications


Topic: Cache Generated Events

Cache Generated Events

NCache provides events that are fired when a node joins or leaves the cluster or when cache stops. Applications can register interest for these events and are therefore notified when such events occur. Both .NET and Java clients can receive such notifications.
Below example explains how to write event handlers which respond to notifications about the cluster status.
import com.alachisoft.ncache.web.caching.*;
import com.alachisoft.ncache.event.*;
public class CacheEventListner implements ClusterListener
{
public void cacheStopped(ClusterEvent ce)
{
System.out.println("Cache Stopped");
}
public void memberJoined(ClusterEvent ce)
{
System.out.println(ce.getIp() + " Joined Cluster " + ce.getCacheId());
}
public void memberLeft(ClusterEvent ce)
{
System.out.println(ce.getIp() + " left Cluster " + ce.getCacheId());
}
}
CacheEventListner eventListner = new CacheEventListner();
Cache _cache = NCache.initializeCache("ClusteredCache");
_cache.addClusterEventListener(eventListner);
_cache.registerMemberJoinedNotification();
_cache.registerMemberJoinedNotification();
_cache.registerMemberLeftNotification();
See Also
Using Selective Notifications | Using Custom Notifications | Using General Notifications


Topic: Read-through, Write-through, Write-behind

Read-through and Write-through Cache Providers

While working with datasources, it is important to transparently fetch the required data from the master datasource if it is not available in the cache and vice versa. Read-Through and Write-through are provided by NCache for this purpose. User can add multiple Read-Through and Write-through providers with their applications.
Following section describes the required steps to enable read-through and write-through Cache Providers.
In this section
Enabling Read-Through Cache Providers
Describes how you can enable Read-Through Caching using NCache Manager in few simple steps.
Enabling Write-Through Cache Providers
Describes how you can enable Write-Through Caching using NCache Manager in few simple steps.
See Also
Implementing ReadThruProvider
Explains implementation of ReadThuProvider and list of methods required to be defined by the classes implementing this provider on server end.
Implementing WriteThruProvider
Explains implementation of WriteThruProvider and list of methods required to be defined by the classes implementing this provider on server end.
ReadThruProvider and WriteThruProvider Deployment
Explains the deployment of ReadThuProvider and WriteThuProvider.


Topic: Enabling Read-through Cache Provider

Enabling Read-through Cache Provider

To enable Read-through caching, you need to implement ReadThruProvider and specify them in the cache properties. NCache Manager provides an interface for specifying them in the cache properties. For enabling read-through caching, follow the steps given below:
  1. From the start programs, launch NCache Manager.
  2. Open the project containing cache or cluster for which you want to configure the read-through caching.
  3. From the explorer, select the cache or cluster. In the right pane, cluster/cache view will be opened.
  4. From the view, select the Backing Source tab .
  5. Check the Enable Read-Through on this cache check box.
  6. Click Add button and browse the Assembly that contains the class implementing ReadThruProvider and then select class name from the list. The Assembly implementing ReadThruProvider must contain the reference of NCRuntime.jar.
  7. Deploy the appropriate assemblies to the cache servers using the Deploy Provider button on a same tab view.
  8. You can provide some additional parameters (like datasource file name) if required from the same screen.
  9. Add the following import statement in your project:
    import com.alachisoft.ncache.runtime.datasourceprovider.ReadThruProvider;
  10. Now you can make direct calls to NCache to get the required items. If NCache does not have already loaded the items, it will use "LoadFromSource" method in specified data access class to load the items from a datasource. The code to access the cache should look like:
Cache mycache = NCache.initializeCache("myreplicatedcache");
Object customer = mycache.get("Customer:David:1001", "XmlReadThruProvider", DSReadOption.ReadThru);
If you do not want to give provider name in API, you can provide it in client.ncconf. If provider name is not provided in both API and client.ncconf, default provider will automatically be used.
<cache id = "myreplicatedcache" client-cache-id = "" default-readthru-provider = "XmlReadThruProvider"
default-writethru-provider = "XmlWriteThruProvider">
<server name = "20.200.20.5">
</cache>
NCache logs the warnings in Application event log in case of an exception during loading the assemblies.
See Also
Configure Cluster Cache | Implementing ReadThruProvider


Topic: Enabling Write-through Cache Provider

Enabling Write-through Cache Provider

To enable Write-through caching, you need to implement WriteThruProvider and specify them in the cache properties. NCache Manager provides an interface for specifying them in the cache properties. For enabling write-through caching, follow the steps given below:
  1. From the start programs, launch NCache Manager.
  2. Open the project containing cache or cluster for which you want to configure the write-through caching.
  3. From the explorer, select the cache or cluster. In the right pane, cluster/cache view will be opened.
  4. From the view, select the Backing Source tab .
  5. For enabling Write-through caching, check the Enable Write-Through on this cache check box on the same tab.
  6. Click Add button and browse the Assembly that contains the class implementing WriteThruProvider and then select class name from the list. The Assembly implementing WriteThruProvider must contain the reference of NCRuntime.jar.
  7. For enabling the Write-Behind caching, mark the checkbox under Write-Behind column.
  8. Deploy appropriate assemblies to the cache servers using the Deploy Provider button on a same tab view.
  9. You can provide some additional parameters (like datasource file name) if required from the same screen.
  10. Add the following import statement in your project:
    import com.alachisoft.ncache.runtime.datasourceprovider.WriteThruProvider;
  11. The code to add data in a cache should look like:
Cache cache = NCache.initializeCache("myreplicatedcache");
Product product = new Product();
CacheItem citem = new CacheItem (product);
cache.add(textBox.Text, citem, DSWriteOption.WriteThru, null);
If you do not want to give provider name in API, you can provide it in client.ncconf. If provider name is not provided in both API and client.ncconf, default provider will automatically be used.
<cache id = "myreplicatedcache" client-cache-id = "" default-readthru-provider = "XmlReadThruProvider"
default-writethru-provider = "XmlWriteThruProvider">
<server name = "20.200.20.5">
</cache>
NCache logs the warnings in Application event log in case of an exception during loading the assemblies.
See Also
Configure Cluster | Implementing WriteThruProvider


Topic: Queries

Queries

NCache allows you to fetch collection of objects from cache, in Java based applications. You have to make API calls and specify a search criteria based on Object Query Language to search the cache. NCache requires all searchable attributes to be indexed. For details on indexing, see Indexing Searchable attributes in Java.
Cache Search Returning Keys
The following code searches the cache and returns a collection of keys. Then, it iterates over all the returned keys and individually fetches the corresponding cached items from the cache.
import com.alachisoft.ncache.runtime.exceptions.*;
import com.alachisoft.ncache.web.caching.*;
import java.util.Collection;
import java.util.Iterator;
public class QueryProgram
{
public static void main(String args[])
{
Cache c = null;
try
{
c = NCache.initializeCache("mycache");
}
catch (CacheException ex)
{
ex.printStackTrace();
return;
}
String query = "select javaapplication5.Product where this.ProductID > ?";
HashMap values = new HashMap();
values.put("ProductID", 100);
try
{
// Fetch the keys matching this search criteria
Collection coll = c.search(query, values);
Iterator ps = coll.iterator();
for (; ps.hasNext();)
{
System.out.println(ps.next());
}
c.dispose();
}
catch (CacheException ex)
{
ex.printStackTrace();
}
}
}
Cache Search Returning Items
In some situations, it is better to fetch all the keys and items in one call. Below is an example of this. It searches the cache and returns a dictionary containing both keys and values.
import com.alachisoft.ncache.runtime.exceptions.*;
import com.alachisoft.ncache.web.caching.*;
import java.util.Collection;
import java.util.Iterator;
public class QueryProgram
{
public static void main(String args[])
{
Cache c = null;
try
{
c = NCache.initializeCache("mycache");
}
catch (CacheException ex)
{
ex.printStackTrace();
return;
}
String query = "select javaapplication5.Product where this.ProductID > ?";
HashMap values = new HashMap();
values.put("ProductID", 100);
try
{
// Fetch the keys matching this search criteria
HashMap entries = c.searchEntries(query, values);
for (Object key : entries.keySet())
{
Product prod = (Product) entries.get(key);
System.out.println("key: " + (String) key + " -- " + "ProductId: " + prod.ProductID);
}
c.dispose();
}
catch (CacheException ex)
{
ex.printStackTrace();
}
}
}
search and searchEntries methods throw GeneralFailureException, OperationFailedException, AggregateException and SecurityException.
See Also
Object Query Language Syntax | Indexing Searchable attributes in Java


Topic: Indexing Searchable Attributes in Java

Indexing Searchable Attributes in Java

To use queries in Java, you have to define query indexes on the attributes participating in the query. Then use methods from NCache Client API for Java to query the objects.
Defining Indexes
Follow the steps given below to define indexes for the attributes of Product:
  • Stop the Cache if it is running.
  • From the tabbed view, select 'Query Indexes' tab as shown in the figure below.
  • Click 'Add' button from the Query Indexes tab, you'll see the 'Select Query Indices' dialog. Click 'Browse' button to add assembly which contains the definition of the Product.
  • From the list of 'Selected Assemblies', select Product class and add it to the List of selected Classes using 'Add Class' button.
  • From the 'Select Query Indexes' dialog, mark the attribute(s) of the Product class that you want to be indexed.
  • Press 'OK' button to complete the process.
  • The following screen appears, showing the attributes selected for the indexing.
  • Apply Configuration changes to the cache .
See Also
Using Queries


Topic: Object Query Language Syntax

Object Query Language Syntax

NCache supports SQL-like language called Object Query Language (OQL). Syntax of the language is explained with the help of examples below:
Using Equal Operator:
Cache _cache = NCache.initializeCache("Cache");
String queryString = "select NCacheQuerySample.Business.Product where this.Category = ?" ;
Hashtable searchCriteria = new Hashtable();
searchCriteria.put("ProductID", 10);
Collection keys = _cache.search(queryString, searchCriteria);// Return Keys
Dictionary dict = _cache.SearchEntries(query, searchCriteria);// Return Keys and values
Using Multiple Operators:
Cache _cache = NCache.initializeCache("Cache");
String queryString = "select NCacheQuerySample.Business.Product where this.ProductID < ? AND this.Category = ?" ;
Hashtable searchCriteria = new Hashtable();
searchCriteria.put("ProductID", 10);
searchCriteria.put("Category", 4);
Collection keys = _cache.search(queryString, searchCriteria);// Return Keys
Dictionary dict = _cache.SearchEntries(query, searchCriteria);// Return Keys and values
Using IN Operator:
Cache _cache = NCache.initializeCache("Cache");
String queryString = "select NCacheQuerySample.Business.Product where this.ProductID IN (?,?,?)" ;
ArrayList aList = new ArrayList();
aList.add(10);
aList.add(4);
aList.add(7);
Hashtable searchCriteria = new Hashtable();
searchCriteria.put("ProductID", aList);
Collection keys = _cache.search(queryString, searchCriteria);// Return Keys
Dictionary dict = _cache.SearchEntries(query, searchCriteria);// Return Keys and values
Using LIKE Operator:
Cache _cache = NCache.initializeCache("Cache");
String queryString = "select NCacheQuerySample.Business.Product where this.ProductName LIKE ?" ;
ArrayList aList = new ArrayList();
aList.add("Ch*"); //returns all entries that start with "Ch".
Hashtable searchCriteria = new Hashtable();
searchCriteria.put("ProductName", aList);
Collection keys = _cache.search(queryString, searchCriteria);// Return Keys
Dictionary dict = _cache.SearchEntries(query, searchCriteria);// Return Keys and values
Showing using tags in OQL:
NCache gives Tagging facility. Keyword(s) can be associated with cache objects. Items can be added to the cache having multiple tags. Tag acts as an identifier to the cache items.
So one can get items on the basis of Tags. Tags are Indexed in NCache thus giving user the ability to search for Tagged cache objects using Queries. Please be aware that Query strings should be specific as shown in the following example
Cache _cache = NCache.initializeCache("myCache");
Object valueToStore = "Can contain any type" ;
Tag[] tagList = new Tag[2];
tagList[0] = new Tag("myTag1");
tagList[1] = new Tag("myTag2");
// Add items to cache containing tags
_cache.add("x-y-z" , valueToStore, tagList);
Hashtable searchCriteria = new Hashtable();
ArrayList queryTagList = new ArrayList();
queryTagList.add("myTag1");
queryTagList.add("myTag2");
searchCriteria.put("$Tag$", queryTagList);
// Query string, for searching Cache items with respect to Tags, should be specific to the following
_cache.search("SELECT System.String WHERE this.$Tag$=? AND this.$Tag$=?" , searchCriteria);
See Also
Using Queries


Topic: Continuous Query

Continuous Query

NCache provides Continuous Query support for both .NET and Java clients. Continuous Query is a technique of registering queries on a cache server and associating list of related events with them in order to get the latest result. It notifies about the changes occured in query result set and therefore, client applications don't have to re-query the data for updates. This process is ideal for the scenarios where application repeats a specific query and would benefit from always having an up-to-date query result set.
Continuous Query is also capable of notifying an ongoing stream of events related to the specific query result set. Here cache monitors the result set of a query for any Add/Update/Remove event and notifies the application accordingly, which eventually helps in maintaining an up-to-date copy of data all the time.
Continuous Query endow with a list of events that are fired when any add, update or delete operation is performed on the data set which in return affects query result set. Applications can register interest for these events and are therefore notified whenever a query result set changes.
NCache also provides Object Query Language (OQL) to let you search the cache. You have to make API calls and specify a search based on this OQL in order to register/unregister and fetch a collection of objects from the cache. NCache requires all searchable attributes to be indexed. See Indexing Searchable Attributes in Java for details on indexing.
Include the following import statement in your application:
import com.alachisoft.ncache.web.caching.*;
import java.util.HashMap;
import java.util.*;
See Also
Indexing Searchable Attributes in Java | Using Continuous Query


Topic: Indexing Searchable Attributes in Java

Indexing Searchable Attributes in Java

NCache requires all searchable attributes to be indexed. This is because, without indexing, it would have to traverse entire cache in order to find items. That could be a very costly operation with potential of slowing down the entire cache.
NCache provides its own indexing mechanism. You can identify objects in Java assemblies that you want to index. NCache uses Java Reflection to extract data from the indexed attributes and builds its internal index. Then, when you query the cache with cache.searchCQ() and cache.searchEntriesCQ(), NCache uses these indexes to quickly find out the desired objects and returns them to you.
Defining Indexes
NCache Manager provides a user friendly interface for defining indexes. Following example demonstrates procedure of defining indexes on attributes.
Suppose that cache contains Person object where the definition of Person is as below:
public class Person implements Serializable
{
public String CustomerID;
public int Age;
public Person(String id, int age) {
this.CustomerID = id;
this.Age = age;
}
}
Follow these steps to define indexes for the attributes of Person:
  • Stop the Cache if it is running.
  • From the tabbed view, select 'Query Indexes' tab as shown in the figure below.
  • Click 'Add' button from the Query Indexes tab, you'll see the 'Select Query Indices' dialog. Click 'Browse' button to add assembly which contains the definition of the Person.
  • From the list of 'Selected Assemblies', select Person class and add it to the List of selected Classes using 'Add Class' button.
  • From the 'Select Query Indexes' dialog, mark the attribute(s) of the Person class that you want to be indexed.
  • Press 'OK' button to complete the process.
  • Following screen appears, showing the attributes selected for the indexing.
  • Apply Configuration changes to the cache .
See Also
Using Continuous Query | Continuous Query


Topic: Using Continuous Query

Using Continuous Query

Following is a list of methods needs to be defined by the class for implementing Continuous Query and a brief description of their purpose.
  • Instance of ContinuousQuery class and notification registration:
An instance of a ContinuousQuery class is required for all methods. It holds information regarding a unique String query i.e. "command text" and HashMap values i.e. "command parameters". ContinuousQuery class also contains event notifications for Add, Update and Remove operations. To activate a Continuous Query, you need to register event notifications for that particular Continuous Query instance.
Note: For every continuous query instances, at least one Notification must be registered.
Following event handler procedures should be created which will be called by Add, Update and Remove callbacks whenever a result set changes. If user is not interested in some callback, "null" can be passed for that particular callback:
ContinuousQuery query = new ContinuousQuery(queryString, values);
query.RegisterAddNotification(new ContinuousQueryItemAddedCallback()
{
public void continuousQueryItemAdded(String key)
{
System.out.println("Item Added");
}
});
query.RegisterUpdateNotification(new ContinuousQueryItemUpdatedCallback()
{
public void continuousQueryItemUpdated(String key)
{
System.out.println("Item Updated");
}
});
query.RegisterRemoveNotification(new ContinuousQueryItemRemovedCallback()
{
public void continuousQueryItemRemoved(String key)
{
System.out.print("Item Removed");
}
});
  • void registerCQ(ContinuousQuery query);
Register continuous query method is used to activate "Continuous Query" on server. This method can be called many times for the same query for registering/un-registering various callbacks. cache.registerCQ method is used only for registering continuous query and it does not return any result set to the client application.
cache.registerCQ(query);
  • void unRegisterCQ(ContinuousQuery query);
Unregister Continuous Query method is used to unregister the callbacks from cache when a user is no more interested in notifications for changes in a query result set.
cache.unRegisterCQ(query);
  • Collection searchCQ(ContinuousQuery query);
Search Continuous Query method performs two functionalities, ‘registerCQ’ which activates continuous query on server (if it is not already activated) and ‘searchCQ’ which searches the cache and returns a collection of keys to the client application. The benefit of this approach is that it returns keys only. Then, the client application can determine the keys to be fetched. The drawback of this approach is that if user is going to fetch most of the items from the cache anyway, he will end up making lots of trips to the cache. And, if the cache is distributed, this might eventually become costly.
Collection keys = cache.searchCQ(query);
if (keys.size() > 0)
{
Iterator ie = keys.iterator();
while (ie.hasNext())
{
String key = (String)ie.next();
Person prs = (Person)cache.get(key);
HandlePerson(prs);
System.out.print("Age: {0}", prs.Age);
}
}
  • HashMap searchEntriesCQ(ContinuousQuery query);
Search Entries Continuous Query method is almost similar to the cache.searchCQ method but it searches the cache and returns a hashmap containing both, keys and values. It will keep pre-fetched data locally and will immediately return data on demand. It runs query on the dataset and returns a HashMap containing both, keys and values. This way, all the data based on the query is fetched in one call. This is much more efficient way of fetching the data from the cache.
HashMap dict = cache.searchEntriesCQ(query);
if (dict.size() > 0) {
Iterator ide = dict.keySet().iterator();
while (ide.hasNext()) {
String key = (String) ide.next();
Person prs = (Person) cache.get(key);
HandlePerson(prs);
System.out.print("Key = {0}, Age: {1}", key, prs.Age);
}
}
Example Continuous Query:
Here is how your class should look like:
Cache cache = NCache.initializeCache("mycache");
String queryString = "SELECT ClassLibrary1.Person WHERE this.Age >= ?";
HashMap values = new HashMap();
values.put("Age", 10);
ContinuousQuery query = new ContinuousQuery(queryString, values);
query.RegisterAddNotification(new ContinuousQueryItemAddedCallback(continuousQueryItemAdded);
query.RegisterUpdateNotification(new ContinuousQueryItemUpdatedCallback(continuousQueryItemUpdated);
query.RegisterRemoveNotification(new ContinuousQueryItemRemovedCallback(continuousQueryItemRemoved);
The following operators are supported in NCache Continuous queries:
Category | Operator
<Query> | = , == , != , <> , < , > , <=, >=, IN, LIKE , NOT LIKE
Logical Operators | AND , OR , NOT
Aggregate Functions | Sum, Count, AVG, Min, Max
Miscellaneous | DateTime.Now , DateTime ("any date time compatible string")
See Also
Indexing Searchable Attributes in Java | Continuous Query


Topic: Server Side API Programming

Server Side API Programming

This tutorial is a practical guide for programmers who want to utilize powerful features of Server side NCache to create high performance and scalable .NET applications. This includes working examples and code snippets to utilize various features of NCache efficiently.
In This Section
Cache Startup Loader
Explains how to use Cache Startup Loader.
Read-through, Write-through, Write-behind
Shows how to transparently fetch the required data from the master datasource if it is not available in the cache and vice versa.
Dynamic Compact Serialization
Explains making application data types Compact Serializable and use them in your application with NCache.
Data Sharing between .Net and Java
Explains how to share data between .Net and Java clients at runtime.
Bridge Conflict Resolver
Explains how to use Conflict Resolver.


Topic: Cache Startup Loader

Cache Startup Loader

While its not always the case when a user should enter data in cache manually. Under some special scenarios it is important that a cache is pre loaded with base data before a user start using it. NCache allows this pre load of cache by providing the feature of Cache Startup Loader.
Following section describes the required steps to enable Cache Startup Loader.
In this section
Using Cache Startup Loader
Explains the API references and import statements required for implementing Cache Startup Loader.
Enabling Cache Startup Loader
Describes how you can enable Cache Startup Loader through NCache Manager in few simple steps.
Implementing CacheLoader
Explains implementation of CacheLoader and list of methods required to be defined by the classes implementing this loader.
See Also
Configure Cluster Cache
Helps you configure Clustered Cache.


Topic: Using Cache StartUp Loader

Using Cache Startup Loader

Namespace:
For enabling Cache Startup Loader, your program needs a reference of the assembly NCRuntime.jar that contains interface com.alachisoft.ncache.runtime.cacheloader.CacheLoader provided by NCache. The class implementing this interface allows framework to load data from the master datasource in the cache. Thus, the class needs to include the logic for loading the data from the datasource.
Following import statements are required in your project for using Cache Loader:
import com.alachisoft.ncache.runtime.cacheloader.CacheLoader;
import com.alachisoft.ncache.runtime.cacheloader.LoaderState;
CacheLoader Interfaces:
In order to use CacheLoader in your application, implement the following methods:
public void init(HashMap hm) throws Exception;
public boolean loadNext(LinkedHashMap lhm, LoaderState ls) throws Exception;
public void dispose() throws Exception;
See Also
Configure Cluster Cache | Implementing CacheLoader


Topic: Enabling Cache Startup Loader

Enabling Cache Startup Loader

Configuring Startup Loader in NCache Manager:
To enable Cache Startup Loader, you need to implement CacheLoader and specify it in the cache properties. NCache Manager provides an interface for specifying it under the cache properties. For Cache Startup Loader, follow these steps:
  1. From the start programs, launch NCache Manager.
  2. Open the project containing cache or cluster for which you want to configure the Cache Startup Loader.
  3. From the explorer, select the cache or cluster. In the right pane, cluster/cache view will be opened.
  4. From the view, select the Cache Loader tab .
  5. Check the Enable Cache-Startup Loader check box.
  6. Click Browse button and browse the Assembly that contains the class implementing ICacheLoader and then select class name from the list. The Assembly implementing ICacheLoader must contain the reference of NCRuntime.jar.
  7. You can provide some additional parameters (like chunkSize etc.) if required.
  8. You can specify number of retries if any cache operation fails.
  9. You can also specify retry interval between each retry. This value is in sec's.
  10. Deploy the appropriate assemblies to the cache servers using the Deploy Cache Loader button on a same tab view.
Deployment:
For deployment details, kindly visit Deploying Cache Loader page.
Note: Restart your NCache Service after deploying the CacheLaoder provider.
See Also
Configure Cluster Cache | Implementing CacheLoader


Topic: Implementing Cache Startup Loader

Implementing Cache Startup Loader Interface

Implementing CacheLoader
Following is a list of methods needs to be defined by the class implementing interface and a brief description of their purpose.
  • void init(HashMap parameters);
This method performs tasks like allocating resources, acquiring connections etc. When the cache is initialized and Cache Startup Loader is enabled, it calls init method to notify the client that cache has initialized and you may initialize your data source too. The parameters passed as an argument contains all the parameters (if any) that were specified using NCache Manager cache/cluster views. These parameters can be utilized in many ways. For example, connection string of a datasource can be specified as a parameter through NCache Manager. Whenever cache will be initialized, the connection to the datasource could be made using this connection string passed as an argument. Thus, it provides a flexible way to change the datasource dynamically without requiring code changes.
  • void dispose();
This method performs tasks like releasing resources etc. When Cache is stopped or loadNext returns false, it calls the dispose() method to notify the client that the task is completed or cache is stopped now and you can free resources related to your datasource.
  • public bool loadNext(LinkedHashMap data, LoaderState state);
This method should contain logic to load object(s) from the master datasource. After init call, framework calls loadNext method in a loop till loadNext returns false. This method receives a LinkedHashMap that contains respective data that needs to be populated. Another variable is LoaderState which takes reference of an already stored object. This function allows user to add data in chunks, or add it as a single operation. If user wants to add data in chunks, he must return "true" back to caller framework, indicating that this method should be called again. User should return "false", to end Startup loading of data by the framework.
Using CacheLoader:
Here is how your class should look like for CacheLoader:
public class CacheLoaderImpl implements CacheLoader
{
private Connection connection;
private String connectionString = "jdbc:sqlserver://localhost:1433;databaseName=Northwind;user=xxxx;password=xxxx";
public void init(HashMap parameters) throws Exception {
connection = DriverManager.getConnection(connectionString);
}
public boolean loadNext(LinkedHashMap data, LoaderState state) throws Exception {
int nextIndex = 0;
if(state.index != null)
{
nextIndex = (Integer)state.index;
}
Statement command = connection.createStatement();
String query = "SELECT ProductID, ProductName, UnitPrice FROM Products WHERE ProductID > '" + nextIndex + "' AND ProductID < '" + (nextIndex + 10) + "'";
ResultSet reader = command.executeQuery(query);
boolean gotSomeRows = false;
while (reader.next())
{
Product product = new Product();
product.ProductID = reader.getInt("ProductID");
product.ProductName = reader.getString("ProductName");
product.UnitsAvailable = reader.getInt("UnitPrice");
ProviderCacheItem provideritem = new ProviderCacheItem(product);
provideritem.setDependency(new KeyDependency("Product:1"));
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, 30);
provideritem.setAbsoluteExpiration(calendar.getTime());
data.put("Product:" + product.ProductID, provideritem);
gotSomeRows = true;
}
if(gotSomeRows == false)
return true;
state.index = nextIndex + 10;
reader.close();
return false;
}
public void dispose() throws Exception {
connection.close();
}
}
NCache logs the warnings in Application event log in case of an exception during loading the libraries.
See Also
Enabling Cache Startup Loader


Topic: Read-Thru, Write-Thru/Write-Behind

Read-through and Write-through Cache Providers

While working with datasources, it is important to transparently fetch required data from the master datasource if it is not available in the cache and vice versa. Read-Through and Write-through are provided by NCache for this purpose. User can add multiple Read-Through and Write-through providers with their applications.
Following section describes the required steps to enable read-through and write-through Cache Providers.
In this section
Using Read-Thru Provider
Explains implementation of ReadThuProvider and list of methods required to be defined by the classes implementing this provider.
Using Write-Thru Provider
Explains implementation of WriteThruProvider and list of methods required to be defined by the classes implementing this provider.
Enabling Read-Through Cache Providers
Describes how you can enable Read-Through Caching using NCache Manager in few simple steps.
Enabling Write-Through Cache Providers
Describes how you can enable Write-Through Caching using NCache Manager in few simple steps.
ReadThruProvider and WriteThruProvider Deployment
Explains the deployment of ReadThuProvider and WriteThuProvider.


Topic: Read-Thru Provider

Read-through Cache Provider

Namespace:
For enabling Read-through caching, you need a reference of the following assembly in your application:
NCRuntime.jar
This assembly contains class implementing com.alachisoft.ncache.runtime.DatasourceProviders.ReadThruProvider interface provided by NCache. The class implementing this interface gets notification requests to load the data from the master datasource if not available in the cache. Thus, the class needs to include the logic for loading the data from the datasource to the cache.
Following import statements are required in your project for using Read-Thru provider:
import com.alachisoft.ncache.runtime.datasourceprovider.ReadThruProvider;
Read-Through Interfaces:
In order to use Read-Thru cache provider in your application, implement the following methods:
public void start(HashMap parameters) throws Exception;
public void loadFromSource(String string, ProviderCacheItem pci) throws
Exception;
public HashMap<String, ProviderCacheItem> loadFromSource(String[] strings)
throws Exception;
public void stop() throws Exception;
See Also
Implementing ReadThruProvider


Topic: Configuring Read-Thru Cache Provider

Enabling Read-through Cache Provider

Configuring Read-Through Provider:
To enable Read-through caching, you need to implement ReadThruProvider and specify them in the cache properties. NCache Manager provides an interface for specifying them in the cache properties. For enabling read-through caching, follow the steps given below:
  1. From the start programs, launch NCache Manager.
  2. Open the project containing cache or cluster for which you want to configure the read-through caching.
  3. From the explorer, select the cache or cluster. In the right pane, cluster/cache view will be opened.
  4. From the view, select the Backing Source tab .
  5. Check the Enable Read-Through on this cache check box.
  6. Click Add button and browse the Assembly that contains the class implementing ReadThruProvider and then select class name from the list. The Assembly implementing ReadThruProvider must contain the reference of NCRuntime.jar.
  7. Deploy the appropriate assemblies to the cache servers using the Deploy Provider button on a same tab view.
  8. You can provide some additional parameters (like datasource file name) if required from the same screen.
Deployment:
For deployment details, kindly visit Deploying Read-Thru/Write-Thru provider page.
Note: Restart your NCache Service after deploying the ReadThru provider.
See Also
Implementing ReadThruProvider


Topic: Implementing Read-Thru Provider Interface

Implementing ReadThruProvider

Implementing Interface:
Following is a list of methods needs to be defined by the class implementing interface and a brief description of their purpose.
  • void start(HashMap parameters);
This method performs tasks like allocating resources, acquiring connections etc. When cache is initialized and finds that read-through caching is enabled, it calls start method to notify the client that cache has initialized and you may initialize your data source too. The parameters passed as an argument contains all the parameters (if any) that were specified using NCache Manager cache/cluster views. These parameters can be utilized in many ways. For example, connection string of a datasource can be specified as a parameter through NCache Manager. Whenever cache will be initialized, the connection to the datasource could be made using this connection string passed as an argument. Thus, it provides a flexible way to change the datasource dynamically without requiring code changes.
public void start(HashMap parameters) throws Exception
{
String connectionString = "jdbc:sqlserver://localhost:1433;databaseName=Northwind;user=xxxx;password=xxxx";
connection = DriverManager.getConnection(connectionString);
}
  • void stop();
This method is responsible for releasing the resources etc. When cache is stopped it calls the stop() method to notify the client that the cache is stopped now and you can free the resources related to your datasource.
public void stop() throws Exception
{
connection.close();
}
  • void loadFromSource(String key, ProviderCacheItem cacheItem);
This method contains logic to load an object from the master datasource. Whenever a request for an item comes and item is not present in the cache, then cache calls loadFromSource method and passes the 'key' as an argument. It is the responsibility of a cache to return object against the passed key from the master datasource. The other argument of this method is ProviderCacheItem.
ProviderCacheItem contains the following parameters:
  • AbsoluteExpiration/SlidingExpiration value for an item,
  • Dependency for cached item,
  • Group/SubGroup identifier for a cached item,
  • ItemPriority for an item to be evicted,
  • ResyncItemOnExpiration is a Boolean parameter, used for automatic reload of the cache item if required. If ResyncItemOnExpiration is enabled and cache item expires, it passes the key of the expired item to reload fresh item from the master datasource. In this way the required item remains in cache with updated values,
  • ResyncProviderName is a provider name which reloads the item,
  • Tags for a cached item and
  • Value for a cached item.
public void loadFromSource(String key, ProviderCacheItem provideritem) throws Exception
{
Statement command = connection.createStatement();
String query = "SELECT ProductID, ProductName, UnitPrice FROM Products WHERE ProductID = '" + key + "'";
ResultSet reader = command.executeQuery(query);
if (reader.next())
{
Product product = new Product();
product.ProductID = reader.getInt("ProductID");
product.ProductName = reader.getString("ProductName");
product.UnitsAvailable = reader.getInt("UnitPrice");
provideritem.setDependency(new KeyDependency("Product:1"));
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, 30);
provideritem.setAbsoluteExpiration(calendar.getTime());
provideritem.setValue(product);
}
reader.close();
}
  • public HashMap <String, ProviderCacheItem> loadFromSource(String [] keys);
This method contains the logic to load array of objects from the master datasource. Whenever a request for items comes and items are not found in the cache, cache calls the loadFromSource method and passes array of keys as argument.
public HashMap<String, ProviderCacheItem> loadFromSource(String[] keys) throws Exception
{
HashMap <String, ProviderCacheItem> source = new HashMap <String, ProviderCacheItem>();
Statement command = connection.createStatement();
String query;
ResultSet reader;
for ( int i = 0; i < keys.length; i++)
{
query = "SELECT ProductID, ProductName, UnitPrice FROM Products WHERE ProductID = '" + keys[i] + "'";
reader = command.executeQuery(query);
if (reader.next())
{
Product product = new Product();
product.ProductID = reader.getInt("ProductID");
product.ProductName = reader.getString("ProductName");
product.UnitsAvailable = reader.getInt("UnitPrice");
ProviderCacheItem provideritem = new ProviderCacheItem(product);
provideritem.setDependency(new KeyDependency("Product:1"));
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, 30);
provideritem.setAbsoluteExpiration(calendar.getTime());
source.put(keys[i], provideritem);
}
reader.close();
}
return source;
}
Using Read-Thru Cache Provider:
After implementing the above interface, you can make direct calls to NCache to get required items. If NCache does not have already loaded the items, it will use "loadFromSource" method in specified data access class to load items from a datasource. The code to access the cache should look like;
Cache mycache = NCache.initializeCache("myreplicatedcache");
object product = mycache.get("ALFKI", "XmlReadThruProvider", DSReadOption.ReadThru);
If you do not want to give provider name in API, you can provide it in client.ncconf. If provider name is not provided in both API and client.ncconf, default provider will automatically be used.
<cache id = "myreplicatedcache" client-cache-id = "" default-readthru-provider = "XmlReadThruProvider" default-writethru-provider = "XmlWriteThruProvider">
<server name = "20.200.20.5">
</cache>
NCache logs the warnings in Application event log in case of an exception during loading the assemblies.
See Also
SqlCacheDependency | Enabling Read-through Caching


Topic: Write-Thru Provider

Write-through Cache Provider

Namespace:
For enabling Write-through caching, you need a reference of the following assembly in your application:
NCRuntime.jar
This assembly contains the class implementing com.alachisoft.ncache.runtime.DatasourceProviders.WriteThruProvider interface provided by NCache. The class implementing this interface gets notification requests to save the data back to the master datasource when new data is added to the cache. Thus, the class needs to include the logic for writing data from cache to the master datasource.
Following import statements are required in your project for using Write-Thru provider:
import com.alachisoft.ncache.runtime.datasourceprovider.WriteThruProvider;
Write-Through Interfaces:
In order to use Write-Thru/Write-Behind provider in your application, implement the following methods:
public void start(HashMap parameters) throws Exception;
public void stop() throws Exception;
public bool addToSource(String key, Object value) throws Exception;
public HashMap addToSource(String [] keys, Object [] vals) throws Exception;
public bool updateSource(String key, Object value) throws Exception;
public HashMap updateSource(String [] keys, Object [] vals) throws Exception;
public bool removeFromSource(String key) throws Exception;
public HashMap removeFromSource(String [] keys) throws Exception;
public bool clear() throws Exception;
See Also
Implementing ReadThruProvider


Topic: Configuring Write-Thru Cache Provider

Enabling Write-through Cache Provider

Configuring Write-Through Provider:
To enable Write-through caching, you need to implement WriteThruProvider and specify them in the cache properties. NCache Manager provides an interface for specifying them in the cache properties. For enabling write-through caching, follow these steps:
  1. From the start programs, launch NCache Manager.
  2. Open the project containing cache or cluster for which you want to configure write-through caching.
  3. From the explorer, select the cache or cluster. In the right pane, cluster/cache view will be opened.
  4. From the view, select the Backing Source tab .
  5. You can provide some additional parameters (like datasource file name) if required from the same screen.
  6. For enabling Write-through caching, check the Enable Write-Through on this cache check box.
  7. Click Add button and browse the Assembly that contains the class implementing WriteThruProvider and then select class name from the list.
  8. The Assembly implementing WriteThruProvider must contain the reference of NCRuntime.jar.
  9. Deploy the appropriate assemblies to the cache servers using the Deploy Provider button on a same tab view.
  10. For enabling the Write-Behind caching, check the checkbox under Write-Behind column.
Deployment:
For deployment details, kindly visit Deploying Read-Thru/Write-Thru provider page.
Note: Restart your NCache Service after deploying the WriteThru provider.
See Also
Configure Clustered Cache | Implementing WriteThruProvider


Topic: Implementing Write-Thru Provider Interface

Implementing WriteThruProvider

Implementing Interface:
Following is a list of methods needs to be defined by the class implementing interface and a brief description of their purpose.
  • void start(HashMap parameters);
This method performs tasks like allocating resources, acquiring connections etc. When the cache is initialized and read-through caching is enabled, it calls start method to notify the client that cache has initialized and you might initialize your data source too. The parameters passed as an argument contains all the parameters (if any) that were specified using NCache Manager cache/cluster views. These parameters can be utilized in many ways. For example, connection string of a datasource can be specified as a parameter through NCache Manager. Whenever cache will be initialized, the connection to the datasource could be made using this connection string passed as an argument. Thus, it provides a flexible way to change the datasource dynamically without requiring code changes.
public void start(HashMap parameters) throws Exception
{
String connectionString =
"jdbc:sqlserver://localhost:1433;databaseName=Northwind;user=xxxx;password=xxxx";
connection = DriverManager.getConnection(connectionString);
}
  • void stop();
This method is responsible for performing tasks like releasing the resources etc. When Cache is stopped it calls stop() method to notify the client that the cache has stopped now and you can free the resources related to your datasource.
public void stop() throws Exception
{
connection.close();
}
  • bool addToSource(String key, Object value);
This method is responsible for adding an object to the datasource. Both the key and value are passed as parameters. Object will not be added to cache if it fails to add in the data source.
public boolean addToSource(String key, Object value) throws Exception {
try
{
Statement command = connection.createStatement();
// Prepare a statement to update a record
Product product = (Product) value;
String sql = "INSERT INTO Products values " + "('" + key + "'," + product.Supplier +","
+ product.Categories + ",null,null,null,null, null, 1 ";
// Execute the insert statement
int count= command.executeUpdate(sql);
// count contains the number of updated rows
if(count > 0)
return true;
}
catch (SQLException sqlException)
{
throw sqlException;
}
return false;
}
  • HashMape addToSource(String[] keys, Object[] vals);
This method is responsible for adding array of objects to the datasource. Arrays of keys and values are passed as parameters. Objects that fail to add, will not be added to the data source.
public HashMap addToSource(String[] keys, Object[] vals) throws Exception {
HashMap mapException = new HashMap();
for(int index=0; index < keys.length; index++)
{
try
{
Statement command = connection.createStatement();
// Prepare a statement to update a record
Product product = (Product) vals[index];
String sql = "INSERT INTO Products values " + "('" + keys[index] + "'," +
product.Supplier + "," + product.Categories + ",null,null,null,null, null, 1 ";
command.executeUpdate(sql);
}
catch (SQLException sqlException)
{
mapException.put(keys[index], sqlException);
}
}
return mapException;
}
  • bool updateSource(String key, Object value);
This method is responsible for updating an object in the datasource. Both the key and value are passed as parameters. Object will not be updated in cache if it fails to update in the data source.
public boolean updateSource(String key, Object value) throws Exception {
try
{
Statement command = connection.createStatement();
// Prepare a statement to update a record
Product product = (Product) value;
String sql = "UPDATE Products SET ProductName = '" + product.ProductName + "' WHERE ProductName = '" + key + "'";
// Execute the insert statement
int count= command.executeUpdate(sql);
// count contains the number of updated rows
if(count > 0)
return true;
}
catch (SQLException sqlException)
{
throw sqlException;
}
return false;
}
  • HashMap updateSource(String[] keys, Object[] vals);
This method is responsible for updating array of objects in the datasource. Arrays of keys and values are passed as parameters. Object will not be updated in cache if it fails to update in the data source.
public HashMap updateSource(String[] keys, Object[] vals) throws Exception {
HashMap mapException = new HashMap();
for(int index=0; index < keys.length; index++)
{
try
{
Statement command = connection.createStatement();
// Prepare a statement to update a record
Product product = (Product) vals[index];
String sql = "UPDATE Products SET ProductName = '" + product.ProductName + "' WHERE ProductName = '" + keys[index] + "'";
command.executeUpdate(sql);
}
catch (SQLException sqlException)
{
mapException.put(keys[index], sqlException);
}
}
return mapException;
}
  • bool removeFromSource(String key);
This method is responsible for removing an object from datasource. Key is passed as parameter. Object will not be removed from cache if it fails to remove from the data source.
public boolean removeFromSource(String key) throws Exception {
try
{
Statement command = connection.createStatement();
String sql = "DELETE FROM Products WHERE ProductName = '" + key + "'";
// Execute the insert statement
int count= command.executeUpdate(sql);
// count contains the number of updated rows
if(count > 0)
return true;
}
catch (SQLException sqlException)
{
throw sqlException;
}
return false;
}
  • HashMap removeFromSource(String[] keys);
This method is responsible for removing array of objects from datasource. Array of keys is passed as parameter. Object will not be removed from cache if it fails to remove from the data source.
public HashMap removeFromSource(String[] keys) throws Exception {
HashMap mapException = new HashMap();
for(int index=0; index < keys.length; index++)
{
try
{
Statement command = connection.createStatement();
String sql = "DELETE FROM Products WHERE ProductName = '" + keys[index] +"'";
command.executeUpdate(sql);
}
catch (SQLException sqlException)
{
mapException.put(keys[index], sqlException);
}
}
return mapException;
}
  • bool clear();
This method is responsible for clearing datasource. Cache will not be cleared if it fails to clear the data source.
public boolean clear() throws Exception {
try
{
Statement command = connection.createStatement();
String sql = "DELETE * From Products";
// Execute the insert statement
int count= command.executeUpdate(sql);
// count contains the number of updated rows
if(count > 0)
return true;
}
catch (SQLException sqlException)
{
throw sqlException;
}
return false;
}
Using Write-Thru Cache Provider:
The code to access the cache should look like:
Cache mycache = NCache.initializeCache("myreplicatedcache");
Product product = new Product();
CacheItem citem = new CacheItem (product);
cache.add(textBox.Text, citem, DSWriteOption.WriteThru, null);
If you do not want to give provider name in API, then you can provide it in client.ncconf. If provider name is not provided in both API and client.ncconf, default provider will automatically be used.
<cache id = "myreplicatedcache" client-cache-id = "" default-readthru-provider = "XmlReadThruProvider" default-writethru-provider = "XmlWriteThruProvider">
<server name = "20.200.20.5">
</cache>
NCache logs the warnings in Application event log in case of an exception during loading the assemblies.
See Also
SqlCacheDependency | Enabling Write-through Caching


Topic: Dynamic Compact Serialization

Dynamic Compact Serialization

Its a process of producing a compact form of serialized object for performance improvement which results in faster network trips. As name illustrates, compact serialized file is compact in form of data and process. The idea behind compact serialization is that every 'known type' (a known type is a type that is registered with the framework) is assigned a unique 2-byte type handle by the framework, which lets the deserializer uniquely identify the 'known types'.
For example, suppose framework assigns a handle 0 to System.Int32. Then serializer writes a 2-byte handle followed by 4 bytes of object value to the stream. Deserializer reads the handle, figures out the object type and then creates and populates the object with its value. On the other hand the native serialization writes the complete type information with object data. NCache overcomes the issues of native serialization in the following ways:
  • Here serialized object does not contain the complete type information and assemblies. It only contains an object value and a unique 2-byte handle. This unique 2-byte handle is used as a reference to uniquely identify type details while deserializing an object. In this way the size of the object reduces.
  • Compact serialization also avoids the reflection which also reduces the overhead.
  • The above two features reduces the IO operations.
  • As the object size decreases, it will automatically make faster network trips and eventually the cost will also decrease.
  • Small object size and fast network traffic increases the application performance.
For using Compact Serialization, you are supposed to define a default public constructor (parameter less) in a compact serializable type and register that type with NCache Manager.
Note:
  • Custom generic types are not supported in java although they are supported in .Net.
  • An object registered in Data Sharing can’t be registered in Compact Serialization at the same time.
In This Section
Registering compact types with NCache
Explains how you can register compact types with NCache.
See Also
Configure Cluster Cache
Helps you configure Clustered Cache.


Topic: Using Compact Types

Using Compact Types

To use Compact Serializable types with NCache Configure Cache with NCache Manager and then register your compact serializable types with NCache.
Registering the Compact Serializable Types
Perform the following steps to register your types with the configured cache:
  • Stop the Cache if it is running.
  • Click on the 'Compact Serialization' tab which will open up the following screen.
  • Click 'Add Types' button. A 'Select Compact Classes' dialog will appear.
  • Browse for the assembly file that contains the compact types by clicking 'Browse' button as shown in the figure.
  • Select the classes you want to register with the cache from the loaded classes list.
  • Press 'Add Class' button to add the classes in selected classes list.
  • Click 'Ok'.
  • Newly added types will start appearing in the list box under the 'Compact Serialization' tab having Compact Type and Platform information.
  • 'Remove' will delete the selected type from the registered types list.
  • Apply changes to the cache .


Topic: Data Sharing

Data Sharing

NCache is providing both .net and java clients and there is a possibility of sharing same cache data among various clients either from same or different platforms. To make this sharing possible NCache introduces Data Sharing feature which not only allows the users to share cache content between various platforms but also provides the facility of class versioning within the same platform. Data sharing is a technique which dynamically serializes the objects at run time and makes it available for use in a very efficient way (in terms of time and cost).
Data sharing also support class versioning as discussed above. Class can have various versions associated with it having unique identifiers. Every new change in a class is recoded as a new version of a class. Using Data Sharing, different class versions can share cache contents among them at run time.
Data sharing is defined as the process of converting the state of an object (of any type) to some persistent state so that it can be understandable by clients from different platforms. It is the process which allows user to dynamically serialize an object to make it portable for different platforms/versions. In this way user can make the state of data persistent so that it can be saved on a remote location and it will be accessible for all clients.
The most common methods available in market for data sharing is XML based sharing which is comparatively a slower solution. NCache introduced an efficient technique for Data Sharing that is the binary serialization of objects at runtime.
Data Sharing is a very magnificent feature for all those clients who are using both NCache .net and NCache java editions but have some limitation as listed below:
  • Custom generic types are not supported in java although they are supported in .Net.
  • In case of multiple versions, user needs to define the default version for Read-Thru/Write-Thru and CacheLoader.
  • An object registered in Data Sharing can’t be registered in Compact Serialization at a same time.
The following mapping should be considered while serializing a Java/.Net class:
Note: Users should only map Java attributes to .Net attributes incase of unsigned types.
In This Section
Configuring Data Sharing
Explains how you can register shared types with NCache.
See Also
Configure Cluster Cache
Helps you configure Clustered Cache.


Topic: Using Data Sharing

Using Data Sharing

NCache introduces this feature to support data sharing between various versions of an object either from same platform or different platforms. To use Data Sharing with NCache Configure cache with NCache Manager and then share your data among different clients.
Perform the following steps to make classes portable:
  • Stop the Cache if it is running.
  • Click on the 'Data Sharing' tab which will open up the following screen:
  • Click on 'Add Shared Types' button. 'Select Data Sharing Classes' dialog will appear, as shown below.
  • You are required to specify Shared Type name in 'Name' field.
  • Browse for the assembly/jar which contains the class you want to share in cache. All the selected assemblies will be shown in the 'Loaded Classes' pane containing their respective classes.
  • Select the class you want to add in the selected classes list.
  • Use 'Add Class' button to add the selected classes.
  • All the selected classes will be listed in the 'List of selected Classes' pane with their Class Name, Version and Type.
  • Click 'OK' to continue.
  • All the classes in the selected 'Shared Type' will be shown here.
  • Bottom pane lists the 'Attributes Union List' and 'Selected Class Attributes' in their respective panes.
  • Class Attributes are already mapped with the Attribute Union List. This mapping is done at run time. You can see class mapping through a single click on the particular class.
  • Here you can remap the attributes of the selected class with Attribute Union List using dropdown list.
  • You can add a new 'Shared Type' and a version to an existing Shared Type by a right click on it.
  • Shared Type configurations can be imported and exported in XML file using "Import" and "Export" button. The configurations will be saved in XML file.
  • Once the mapping of attributes is done, apply changes to the cache .
Note:
By default NCache is using “Specification Version” for a given jar file. Users can change the version to “Implementation Version” from NCManager.exe.config file placed at: "%Install Directory%/NCache/ bin/IDE/NCache Manager”.


Topic: Bridge Conflict Resolver

Bridge Conflict Resolver

There are situations when a bridge tries to replicate an operation for a key that already exist in the cache. Conflict Resolver is introduced to resolve the conflict between existing operations and operation replicated from bridge to cache. It decides which key to apply on the cache depending upon defined rules. By default the decision will be made on “Time Based” rule, which keeps the latest key on a cache. Users can also define their own rules for conflict resolver.
Following section describes the required steps to enable Bridge Conflict Resolver.
In this section
Using Bridge Conflict Resolver
Explains the API references and namespaces required for implementing Bridge Conflict Resolver.
Enabling Bridge Conflict Resolver
Describes how you can enable Bridge Conflict Resolver through NCache Manager in few simple steps.
Implementing BridgeConflictResolver
Explains implementation of BridgeConflictResolver and list of methods required to be defined by the class implementing this loader.
See Also
Configure Cluster Cache
Helps you configure Clustered Cache.


Topic: Using Bridge Conflict Resolver

Using Bridge Conflict Resolver

Namespace:
For enabling Bridge Conflict Resolver, your program needs a reference to the assembly NCRuntime.jar that contains interface com.alachisoft.ncache.runtime.bridge.BridgeConflictResolver provided by NCache. The class implementing this interface allows framework to resolve conflict between existing operations and operation replicated from bridge to cache. Thus, the class needs to include the logic for Conflict Resolution between bridge and cache.
Following namespace is required in your project for using Bridge Conflict Resolver:
import com.alachisoft.ncache.runtime.bridge.BridgeConflictResolver;
import com.alachisoft.ncache.runtime.bridge.BridgeItemOpCodes;
import com.alachisoft.ncache.runtime.bridge.ConflictResolution;
import com.alachisoft.ncache.runtime.bridge.ProviderBridgeItem;
import com.alachisoft.ncache.runtime.bridge.ResolutionAction;
BridgeConflictResolver Interface:
In order to use BridgeConflictResolver in your application, implement the following interface:
public void init(HashMap parameters) throws Exception;
public ConflictResolution resolve(ProviderBridgeItem oldEntry, ProviderBridgeItem newEntry) throws Exception;
public void dispose() throws Exception;
See Also
Configure Cluster Cache | Implementing BridgeConflictResolver


Topic: Enabling Bridge Conflict Resolver

Enabling Bridge Conflict Resolver

Configuring Conflict Resolver in NCache Manager:
To enable Bridge Conflict Resolver, you need to implement BridgeConflictResolver and specify it in the cache properties. NCache Manager provides an interface for specifying it under the cache properties. For Bridge Conflict Resolver, follow these steps:
  1. From the start programs, launch NCache Manager.
  2. Open the project containing cache or cluster for which you want to configure the Bridge Conflict Resolver.
  3. From the explorer, select the cache or cluster. In the right pane, cluster/cache view will be opened.
  4. From the view, select the Conflict Resolver tab .
  5. Check the Enable Conflict Resolver check box.
  6. Click Browse button and browse the Assembly that contains the class implementing BridgeConflictResolver and then select class name from the list. The Assembly implementing BridgeConflictResolver must contain the reference of NCRuntime.jar.
  7. You can provide some additional parameters if required.
  8. Deploy the appropriate assemblies to the cache servers using the Deploy Conflict Resolver button on a same tab view.
Deployment:
For deployment details, kindly visit Deploying Conflict Resolver page.
See Also
Configure Cluster Cache | Implementing BridgeConflictResolver


Topic: Implementing BridgeConflictResolver Interface

Implementing BridgeConflictResolver Interface

Implementing BridgeConflictResolver
Following is a list of methods needs to be defined by the class implementing interface and a brief description of their purpose.
  • void init(HsahMap parameters);
This method performs tasks like allocating resources, acquiring connections etc. When cache is initialized and Conflict Resolvers is enabled, then it calls init method to notify the client that cache has initialized and you may initialize your conflict resolver too. Parameters passed as an argument contains all the parameters (if any) that were specified using NCache Manager cache/cluster views.
  • void dispose();
This method performs tasks like releasing the resources etc. When Cache is stopped or the task is completed, it calls the Dispose() method to notify the client that you can free the resources related to your task.
  • ConflictResolution resolve(ProviderBridgeItem oldEntry, ProviderBridgeItem newEntry);
This method should contain the logic to resolve the conflict occured while replicating an operation from bridge for a key that already exists in the cache. Whenever any conflict occurs, cache calls BridgeConflictResolution to decides which operation to apply on the cache depending upon rules implemented on it. It takes two parameters/entries, both are of ProviderBridgeItem type. ProviderBridgeItem contains the following parameters:
  • BridgeItemVersion contains version of an item.
  • Key contains key of an item.
  • Value of an item contains value of an item.
  • BridgeItemOpCodes contains conflicted operation.
Using BridgeConflictResolver:
Here is how your class should look like for BridgeConflictResolver:
public class BridgeConflictResolverImpl implements BridgeConflictResolver {
private boolean enableLogging;
private FileWriter textLogger;
public void init(HashMap parameters) throws Exception {
//If logging key is provided then based on it enable the bridge logging
if(parameters.containsKey("logging"))
{
enableLogging = Boolean.getBoolean(parameters.get("logging").toString());
}
if(enableLogging)
{
textLogger = new FileWriter("bridgeResolverLog.txt");
}
}
public ConflictResolution resolve(ProviderBridgeItem oldEntry, ProviderBridgeItem newEntry) throws Exception {
ConflictResolution conflictResolution = new ConflictResolution();
switch (oldEntry.getBridgeItemVersion())
{
//If Old cache entry bridge item version is less than the new entry then replace the cache item with new Entry received from bridge
case OLD:
{
conflictResolution.setResolutionAction(ResolutionAction.ReplaceWithNewEntry);
}
break;
//If old cache entry bridge item version is greater than the new entry then keep the old entry
case LATEST:
{
conflictResolution.setResolutionAction(ResolutionAction.KeepOldEntry);
}
break;
//If both items have the same bridge item version
case SAME:
{
//Replace the new entry only if old entry operation is of Remove; else keep the old entry
if (oldEntry.getOpCode() == BridgeItemOpCodes.Remove)
{
conflictResolution.setResolutionAction(ResolutionAction.ReplaceWithNewEntry);
}
else
{
conflictResolution.setResolutionAction(ResolutionAction.KeepOldEntry);
}
}
break;
}
if(enableLogging)
{
textLogger.write("Resolve Key " + oldEntry.getKey() + " and decision taken " + conflictResolution.getResolutionAction().value());
}
return conflictResolution;
}
public void dispose() throws Exception {
if(enableLogging)
{
textLogger.close();
}
}
}
NCache logs the warnings in Application event log in case of an exception during loading the jar files.
See Also
Enabling Bridge Conflict Resolver


Topic: Client Side JSP Features

Client Side JSP Features

This tutorial is a practical guide for programmers who want to utilize powerful features of JSP with NCache to create high performance and scalable Java applications. This includes working examples and code snippets to utilize various features of NCache efficiently.
In This Section
NCache Java Session Module
NCache provides no-code change option for Java based web applications to store sessions in NCache by implementing session module NCacheSessionProvider as a Java filter.
NCache with Session Beans
This section demonstrates the use of NCache with Session Beans.


Topic: NCache Java Session Module

NCache Java Session Module

NCache is an in-memory distributed caching solution developed in .NET and it has its own TCP/IP based socket protocol which allows Java applications to use NCache caching directly instead of going through any bridge.
Now, NCache also provides no-code change option for Java based web applications to store sessions in NCache by implementing session module NCacheSessionProvider as a Java filter. In order to use NCache java session module, you must be running a Servlet 2.3 compatible container (web server). You only need reference of few libraries and add a filter in web.xml of your application so that all the requests will comes to your application through NCache filter.
Following J2EE platforms are supported:
  • Tomcat
  • Web Logic
  • WebSphere
  • JBoss
Configuring application to use Java Session Module:
NCache provides no-code change option for Java applications for storing sessions in NCache distributed caching. Here are the steps that you need to follow to configure your Java application for using NCache as a distributed session store.
Adding Libraries:
You need to add required libraries. You can find these Java libraries at following path. %INSTALL_PATH% is the location where NCache is installed. If you are using IDE just add references to these files in the project, if you are not using IDE then you need to copy these files to 'WEB-INF/lib' folder under the application root folder.
On Linux: %INSTALL_PATH%/ncache/lib/
On Windows: %INSTALL_PATH%/NCache/java/lib/
  • NCActivate.jar (The NCache java client library to validate licensing information)
  • NCClient.jar (The NCache java client library that actually implements NCache communication protocol)
  • NCacheSessionProvider.jar (The HTTP module implementation for session caching using NCache)
  • NCRuntime.jar (The NCache java client library that implements Read-through/Write-through caching and Cache Startup operations)
  • NCSerialization.jar (The NCache java client library that actually implements dynamic compact serialization and object sharing operations)
  • javassist.jar (The NCache java 3rd party library responsible for runtime code generation)
Add the following to 'classes' folder in WEB-INF of your application:
  • javaReg.properties (The file containing licensing information. You can place this file under 'classes' directory of your web application)
Defining filter:
After adding required libraries in your application, you need to add the filter in the deployment descriptor of your web application. Deployment descriptor is XML file named 'web.xml' located in the WEB-INF directory under the application root directory. The class file containing the filter implementation is 'com.alachisoft.ncache.web.sessionstate.NSessionStoreProvider '.
To ensure the correct caching of sessions, you must apply this filter as the first filter in your deployment descriptor. Filters are executed in the order they are defined in deployment descriptor.
To create a filter, you must define it first under the <filter> tag and then provide a URL mapping for the filter using <filter-mapping> tag. The following filter configuration means that the filter will be applied to all the URLs in a web application.
<filter>
<filter-name> NCacheSessionProvider </filter-name>
<filter-class> com.alachisoft.ncache.web.sessionstate.NSessionStoreProvider </filter-class>
</filter>
<filter-mapping>
<filter-name> NCacheSessionProvider </filter-name>
<url-pattern> /* </url-pattern>
</filter-mapping>
NCache Session filter can be configured with a number of initialization parameters. The following are the required parameters.
<init-param>
<description> Name of running cache that will be used to persist session state.</description>
<param-name> cacheName </param-name>
<param-value> mycache </param-value>
</init-param>
<init-param>
<description> configPath is used to load the client.ncconf </description>
<param-name> configPath </param-name>
<param-value> %INSTALL_PATH%/config/ </param-value>
</init-param>
%INSTALL_PATH% is the location where NCache is installed.
Following is example of how the deployment descriptor should look like after defining the filter.
<session-config>
<session-timeout> 30 </session-timeout>
</session-config>
<filter>
<filter-name> NCacheSessionProvider </filter-name>
<filter-class> com.alachisoft.ncache.web.sessionstate.NSessionStoreProvider</filter-class>
<init-param>
<description> Name of running cache that will be used to persist session state.</description>
<param-name> cacheName </param-name>
<param-value> mycache </param-value>
</init-param>
<init-param>
<description> configPath is used to load the client.ncconf </description>
<param-name> configPath </param-name>
<param-value> C:\Program Files/NCache/config/ </param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name> NCacheSessionProvider </filter-name>
<url-pattern> /* </url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file> index.jsp </welcome-file>
</welcome-file-list>
</web-app>
Deploying application:
By default this sample application uses 'mycache' to store the session data. So make sure that cache 'mycache' exist in the 'client.ncconf' file located at '%INSTALL_PATH%/config/' with correct server IP Address and this cache should be started. %INSTALL_PATH% is location where NCache is installed. Following is an example of how the 'client.ncconf' should look like.
<?xml version = "1.0" encoding = "UTF-8"?>
<configuration>
<ncache-server connection-retries = "5" retry-interval = "1" client-request-timeout = "90" connection-timeout = "5" port = "9800"/>
<cache id = "mycache" client-cache-id = "" client-cache-syncmode = "optimistic" load-balance = "true" >
<server name = "20.200.20.41"/>
<! -- This is the server IP Address where mycache is running -- >
</cache>
</configuration>
Windows:
Follow the below mentioned steps to deploy application on the respected server.
Apache Tomcat:
Following instructions use tomcat version 6.0.29. Steps remain the same but the location of the files might change depending upon the version of the tomcat. For the following steps %TOMCAT_HOME% refers to the location where Tomcat is installed and %NCACHE_HOME% refers to the location where NCache is installed.
  1. Open the command prompt, change directory to '%TOMCAT_HOME%/bin' and execute 'shutdown.bat'. This will stop the server.
  2. NCache uses 'log4j' for logging. Place the 'log4j' at the following location.'%TOMCAT_HOME%/lib'
  3. Create a new text document with following contents and save it with the name of 'log4j.properties' in the '%TOMCAT_HOME%/lib' folder.log4j.rootLogger=DEBUG, R
    log4j.appender.R=org.apache.log4j.RollingFileAppender
    log4j.appender.R.File=${catalina.home}/logs/tomcat.log
    log4j.appender.R.MaxFileSize=10MB
    log4j.appender.R.MaxBackupIndex=10
    log4j.appender.R.layout=org.apache.log4j.PatternLayout
    log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
  4. Download the 'commons-logging-x.x.x-bin.zip' from http://commons.apache.org/logging/download_logging.cgi extract it and copy the 'commons-logging-x.x.x.jar' file into the following location.
    '%TOMCAT_HOME%/lib'
  5. Open the command prompt, change directory to '%TOMCAT_HOME%/bin' and execute 'startup.bat'. This will start the server.
  6. Move the 'GuessGame.war' file located at '%NCACHE_HOME%/samples/java/bin' to the directory '%TOMCAT_HOME%/webapps'.
  7. Open the web browser and try to access the following URL:http://host:port/GuessGame/index.jsp
    Where 'host' will be the address/IP of the machine where Tomcat is installed in case of local machine it should be 'localhost', and 'port' where Tomcat is listening the request. The default port for Tomcat is 8080.
WebLogic:
For the following steps %WEBLOGIC_HOME% refers to the location where WebLogic is installed. %DOMAIN_NAME% is the domain already created on the server. %NCACHE_HOME% refers to the location where NCache is installed.
  1. NCache uses 'log4j' for logging. Place the 'log4j' at the following location and restart server:
    '%WEBLOGIC_HOME%/user_projects/domains/%DOMAIN_NAME%/lib'
  2. Move the 'GuessGame.war' file located at '%NCACHE_HOME%/samples/java/bin' to the directory '%WEBLOGIC_HOME%/user_projects/domains/%DOMAIN_NAME%/autodeploy'.
  3. Open the web browser and try to access the following URL:http://host:port/GuessGame/index.jsp
    Where 'host' will be the address/IP of the machine where WebLogic is installed in case of local machine it should be 'localhost', and 'port' where WebLogic is listening the request. The default port for WebLogic is 7001.
WebSphere:
For the following steps %WEBSPHERE_HOME% refers to the location where WebSphere is installed and %NCACHE_HOME% refers to the location where NCache is installed.
  1. NCache uses 'log4j' for logging. Place the 'log4j' at the following location and restart server:
    '%WEBSPHERE_HOME%/AppServer/lib/ext'
  2. If WebSphere is installed properly, you will be able to access the admin console through browser with the help of the following url:http://ip-address:port/ibm/console/
    By default, 9060 is the port used by WAS. Make sure that your are using the correct port if you changed it during installation.
  3. You can go to Applications --> New Application --> New Enterprise Application.
  4. Specify the path of the 'GuessGame.war' file and click Next. You can locate the 'GuessGame.war' at the following location'%NCACHE_HOME%/samples/java/bin'
  5. Select Fast Path installation mode and click Next.
  6. Specify the Application Name and Application Directory and click Next. Both Application Name and Application Directory should be 'GuessGame'.
  7. Map the application to the server, Select 'GuessGame.war' from the list with the default settings and click Next.
  8. Map the application to the virtual host, Select 'GuessGame.war' from the list with the default settings and click Next.
  9. Map the context root to the application, type 'GuessGame' into the textbox resulting in '/GuessGame' as the contents of the textbox and click Next.
  10. Click the Finish button to complete the deployment.
  11. Go to Applications --> Application Types --> WebSphere enterprise applications.
  12. You should see the GuessGame application in the list, select the GuessGame application by clicking on the checkbox and press the start button at the top left, you should see a green icon showing that application has started.
  13. Open the web browser and try to access the following URL:http://host:port/GuessGame/index.jsp
    Where 'host' will be the address/IP of the machine where WebSphere is installed in case of local machine it should be 'localhost' and 'port' where WebSphere is listening the request. Make sure that you are using the correct port. The default port for WebSphere is 9080.
JBoss:
For the following steps %JBOSS_HOME% refers to the location where JBoss is installed and %NCACHE_HOME% refers to the location where NCache is installed.
  1. NCache uses 'log4j' for logging. JBoss by default uses 'log4j' for logging so no need to place it.
  2. Move the 'GuessGame.war' file located at '%NCACHE_HOME%/samples/java/bin' to the directory '%JBOSS_HOME%/server/default/deploy'.
  3. Open the web browser and try to access the following URL:http://host:port/GuessGame/index.jsp
    Where 'host' will be the address/IP of the machine where JBoss is installed in case of local machine it should be 'localhost', and 'port' where JBoss is listening the request. The default port for JBoss is 8080.
Linux:
Follow the below mentioned steps to deploy application on the respected server.
Apache Tomcat:
Following instructions use tomcat version 6.0.29. Steps remain the same but the location of the files might change depending upon the version of the tomcat. For the following steps %TOMCAT_HOME% refers to the location where Tomcat is installed and %NCACHE_HOME% refers to the location where NCache is installed.
  1. Open the command prompt, change directory to '%TOMCAT_HOME%/bin' and execute 'shutdown.sh'. This will stop the server.
  2. NCache uses 'log4j' for logging. Place the 'log4j' at the following location.'%TOMCAT_HOME%/lib'
  3. Create a new text document with following contents and save it with the name of 'log4j.properties' in the '%TOMCAT_HOME%/lib' folder.log4j.rootLogger=DEBUG, R
    log4j.appender.R=org.apache.log4j.RollingFileAppender
    log4j.appender.R.File=${catalina.home}/logs/tomcat.log
    log4j.appender.R.MaxFileSize=10MB
    log4j.appender.R.MaxBackupIndex=10
    log4j.appender.R.layout=org.apache.log4j.PatternLayout
    log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
  4. Download the 'commons-logging-x.x.x-bin.zip' from http://commons.apache.org/logging/download_logging.cgi
    extract it and copy the 'commons-logging-x.x.x.jar' file into the following location.
    '%TOMCAT_HOME%/lib'.
  5. Open the command prompt, change directory to '%TOMCAT_HOME%/bin' and execute 'startup.sh'. This will start the server.
  6. Move the 'GuessGame.war' file located at '%NCACHE_HOME%/samples/bin' to the directory '%TOMCAT_HOME%/webapps'.
  7. Open the web browser and try to access the following URL:http://host:port/GuessGame/index.jsp
    Where 'host' will be the address/IP of the machine where Tomcat is installed in case of local machine it should be 'localhost', and 'port' where Tomcat is listening the request. The default port for Tomcat is 8080.
WebLogic:
For the following steps %WEBLOGIC_HOME% refers to the location where WebLogic is installed. %DOMAIN_NAME% is the domain already created on the server. %NCACHE_HOME% refers to the location where NCache is installed.
  1. NCache uses 'log4j' for logging. Place the 'log4j' at the following location and restart server:
    '%WEBLOGIC_HOME%/user_projects/domains/%DOMAIN_NAME%/lib'
  2. Move the 'GuessGame.war' file located at '%NCACHE_HOME%/samples/bin' to the directory '%WEBLOGIC_HOME%/user_projects/domains/%DOMAIN_NAME%/autodeploy'.
  3. Open the web browser and try to access the following URL:http://host:port/GuessGame/index.jsp
    Where 'host' will be the address/IP of the machine where WebLogic is installed in case of local machine it should be 'localhost', and 'port' where WebLogic is listening the request. The default port for WebLogic is 7001.
JBoss:
For the following steps %JBOSS_HOME% refers to the location where JBoss is installed and %NCACHE_HOME% refers to the location where NCache is installed.
  1. NCache uses 'log4j' for logging. JBoss by default uses 'log4j' for logging so no need to place it.
  2. Move the 'GuessGame.war' file located at '%NCACHE_HOME%/samples/bin' to the directory '%JBOSS_HOME%/server/default/deploy'.
  3. Open the web browser and try to access the following URL:http://host:port/GuessGame/index.jsp
    Where 'host' will be the address/IP of the machine where JBoss is installed in case of local machine it should be 'localhost', and 'port' where JBoss is listening the request. The default port for JBoss is 8080.
See Also
NCache with Session Beans


Topic: NCache with Session Beans

NCache with Session Beans

This sample demonstrates the use of NCache with Session Beans, it uses EJB 3.0, you must be running Java EE 5 compatible application server. Following J2EE platforms are supported:
  • WebSphere
  • Web Logic
  • JBoss
Configuring Session Beans to use NCache:
You need to add reference to the required libraries in EJB module of the enterprise application.
Adding Libraries:
You need to add required libraries. You can find these Java libraries at following path. %INSTALL_PATH% is the location where NCache is installed. If you are using IDE just add references to these files in the project, if you are not using IDE then you need to copy these files to 'WEB-INF/lib' folder under the application root folder.
On Linux: %INSTALL_PATH%/ncache/lib/
On Windows: %INSTALL_PATH%/NCache/java/lib/
  • NCActivate.jar (The NCache java client library to validate licensing information)
  • NCClient.jar (The NCache java client library that actually implements NCache communication protocol)
  • NCacheSessionProvider.jar (The HTTP module implementation for session caching using NCache)
  • NCRuntime.jar (The NCache java client library that implements Read-through/Write-through caching and Cache Startup operations)
  • NCSerialization.jar (The NCache java client library that actually implements dynamic compact serialization and object sharing operations)
  • javassist.jar (The NCache java 3rd party library responsible for runtime code generation)
Add the following to 'classes' folder of your EJB module
  • javaReg.properties (The file containing licensing information. You can place this file under 'classes' directory of your web application)
Build application using NetBeans:
Follow the below mentioned steps to successfully build the project in NetBeans.
Windows:
  1. Open the project at the following location '%NCACHE_HOME%/samples/java/NetBeans/JavaAPIEJBTest' in the NetBeans environment.
  2. Under the Java EE Modules right click the JavaAPIEJBTest-war.war and open the project, project will now be added into the NetBeans projects list.
  3. Under the Java EE Modules right click the JavaAPIEJBTest-ejb.jar and open the project, project will now be added into the NetBeans projects list.
  4. Configure the application server for all the three projects by right clicking the project and opening the Properties --> Run and selecting the appropriate server with Java EE 5. The project will not build without the server selection.
  5. Make sure that 'JavaAPIEJBTest-ejb' project references the required 'NCClient.jar' and 'NCActivate.jar' files located at '%NCACHE_HOME%/java/lib/'.
  6. Add the 'javareg.Properties' file located at '%NCACHE_HOME%/java/lib/' in the default source package of the 'JavaAPIEJBTest-ejb' project.
  7. Build the JavaAPIEJBTest project, it will generate the 'JavaAPIEJBTest.ear' file in the following location:%NCACHE_HOME%/samples/java/NetBeans/JavaAPIEJBTest/JavaAPIEJBTest/dist
Linux:
  1. Open the project at the following location '%NCACHE_HOME%/samples/NetBeans/JavaAPIEJBTest' in the NetBeans environment.
  2. Under the Java EE Modules right click the JavaAPIEJBTest-war.war and open the project, project will now be added into the NetBeans projects list.
  3. Under the Java EE Modules right click the JavaAPIEJBTest-ejb.jar and open the project, project will now be added into the NetBeans projects list.
  4. Configure the application server for all the three projects by right clicking the project and opening the Properties --> Run and selecting the appropriate server with Java EE 5. The project will not build without the server selection.
  5. Make sure that 'JavaAPIEJBTest-ejb' project references the required 'NCClient.jar' and 'NCActivate.jar' files located at '%NCACHE_HOME%/lib/'.
  6. Add the 'javareg.Properties' file located at '%NCACHE_HOME%/lib/' in the default source package of the 'JavaAPIEJBTest-ejb' project.
  7. Build the JavaAPIEJBTest project, it will generate the 'JavaAPIEJBTest.ear' file in the following location%NCACHE_HOME%/samples/NetBeans/JavaAPIEJBTest/JavaAPIEJBTest/dist
Build application using Eclipse:
Follow the below mentioned steps to successfully build the project in Eclipse.
Windows:
  1. Import the project at the following location '%NCACHE_HOME%/samples/java/Eclipse/JavaAPIEJBTest' in the Eclipse environment.
  2. Import the project at the following location '%NCACHE_HOME%/samples/java/Eclipse/JavaAPIEJBTest/JavaAPIEJBTest-ejb' in the Eclipse environment.
  3. Import the project at the following location '%NCACHE_HOME%/samples/java/Eclipse/JavaAPIEJBTest/JavaAPIEJBTest-war' in the Eclipse environment.
  4. Configure the application server for all the three projects by right clicking the project and opening the Server and selecting the appropriate server with Java EE 5. The project will not build without the server selection.
  5. Make sure that 'JavaAPIEJBTest-ejb' project references the required 'NCClient.jar' and 'NCActivate.jar' files located at '%NCACHE_HOME%/java/lib/'.
  6. Add the 'javareg.Properties' file located at '%NCACHE_HOME%/java/lib/' in the default source package of the 'JavaAPIEJBTest-ejb' project.
  7. Right click the JavaAPIEJBTest project and select Validate.
  8. Right click the JavaAPIEJBTest project and select Export --> EAR File.
  9. Provide the following destination path for the EAR file and click finish.%NCACHE_HOME%/samples/java/Eclipse/JavaAPIEJBTest/JavaAPIEJBTest/dist
Linux:
  1. Import the project at the following location '%NCACHE_HOME%/samples/Eclipse/JavaAPIEJBTest' in the Eclipse environment.
  2. Import the project at the following location '%NCACHE_HOME%/samples/Eclipse/JavaAPIEJBTest/JavaAPIEJBTest-ejb' in the Eclipse environment.
  3. Import the project at the following location '%NCACHE_HOME%/samples/Eclipse/JavaAPIEJBTest/JavaAPIEJBTest-war' in the Eclipse environment.
  4. Configure the application server for all the three projects by right clicking the project and opening the Server and selecting the appropriate server with Java EE 5. The project will not build without the server selection.
  5. Make sure that 'JavaAPIEJBTest-ejb' project references the required 'NCClient.jar' and 'NCActivate.jar' files located at '%NCACHE_HOME%/lib/'.
  6. Add the 'javareg.Properties' file located at '%NCACHE_HOME%/lib/' in the default source package of the 'JavaAPIEJBTest-ejb' project.
  7. Right click the JavaAPIEJBTest project and select Validate.
  8. Right click the JavaAPIEJBTest project and select Export --> EAR File.
  9. Provide the following destination path for the EAR file and click finish.%NCACHE_HOME%/samples/Eclipse/JavaAPIEJBTest/JavaAPIEJBTest/dist
Deploying Application:
By default this sample application uses 'mycache', So make sure that cache 'mycache' exist in the 'client.ncconf' file located at '%INSTALL_PATH%/config/' with correct server IP Address and this cache should be started. %INSTALL_PATH% is location where NCache is installed. Following is an example of how the 'client.ncconf' should look like.
<?xml version = "1.0" encoding = "UTF-8"?>
<configuration>
<ncache-server connection-retries = "5" retry-interval = "1" client-request-timeout = "90" connection-timeout = "5" port = "9800"/>
<cache id = "mycache" client-cache-id = "" client-cache-syncmode = "optimistic" load-balance = "true">
<server name = "20.200.20.41"/>
<!-- This is the server IP Address where mycache is running -->
</cache>
</configuration>
Windows:
Follow the below mentioned steps to deploy application on the respected server.
WebLogic:
For the following steps %WEBLOGIC_HOME% refers to the location where WebLogic is installed. %DOMAIN_NAME% is the domain already created on the server. %NCACHE_HOME% refers to the location where NCache is installed.
  1. Move the 'JavaAPIEJBTest.ear' file located at '%NCACHE_HOME%/ samples/java/bin' to the directory '%JBOSS_HOME%/server/default/deploy' .
  2. Open the web browser and try to access the following URL:
http://host:port/JavaAPIEJBTest-war/index.jsp
Where 'host' will be the address/IP of the machine where JBoss is installed in case of local machine it should be 'localhost', and 'port' where JBoss is listening the request. The default port for JBoss is 8080.
WebSphere:
For the following steps %WEBSPHERE_HOME% refers to the location where WebSphere is installed and %NCACHE_HOME% refers to the location where NCache is installed.
  1. If WebSphere is installed properly, you will be able to access the admin console through browser with the help of the following URL: http://ip-address:port/ibm/console/. By default, 9060 is the port used by WAS. Make sure that your are using the correct port if you changed it during installation.
  2. You can go to Applications --> New Application --> New Enterprise Application.
  3. Specify the path of the 'JavaAPIEJBTest.ear' file and click Next. You can locate the 'JavaAPIEJBTest.ear' file at the following location'%NCACHE_HOME%/samples/java/bin'
  4. Select Fast Path installation mode and click Next.
  5. Specify the Application Name and Application Directory and click Next. Both Application Name and Application Directory should be 'JavaAPIEJBTest'.
  6. Map the application to the server, Select 'JavaAPIEJBTest-ejb.jar' and 'JavaAPIEJBTest-war.war' from the list with the default settings and click Next.
  7. Map the application to the virtual host, Select 'JavaAPIEJBTest-war.war' from the list with the default settings and click Next.
  8. Click the Finish button to complete the deployment.
  9. Go to Applications --> Application Types --> WebSphere enterprise applications.
  10. You should see the 'JavaAPIEJBTest' application in the list, select the 'JavaAPIEJBTest' application by clicking on the checkbox and press the start button at the top left; you should see a green icon showing that application has started.
  11. Open the web browser and try to access the following URL:http://host:port/JavaAPIEJBTest-war/index.jsp
    Where 'host' will be the address/IP of the machine where WebSphere is installed in case of local machine it should be 'localhost', and 'port' where WebSphere is listening the request. Make sure that you are using the correct port. The default port for WebSphere is 9080.
JBoss:
For the following steps %JBOSS_HOME% refers to the location where JBoss is installed and %NCACHE_HOME% refers to the location where NCache is installed.
1. Move the 'JavaAPIEJBTest.ear' file located at '%NCACHE_HOME%/ samples/java/bin' to the directory '%JBOSS_HOME%/server/default/deploy'.
2. Open the web browser and try to access the following url:
http://host:port/JavaAPIEJBTest-war/index.jsp
where 'host' will be the address/IP of the machine where JBoss is installed in case of local machine it should be 'localhost'.
and 'port' where JBoss is listening the request. Make sure that you are using the correct port. The default port for JBoss is 8080.
Linux:
Follow the below mentioned steps to deploy application on the respected server.
WebLogic:
For the following steps %WEBLOGIC_HOME% refers to the location where WebLogic is installed. %DOMAIN_NAME% is the domain already created on the server. %NCACHE_HOME% refers to the location where NCache is installed.
  1. Move the 'JavaAPIEJBTest.ear' file located at '%NCACHE_HOME%/ samples/bin' to the directory '%JBOSS_HOME%/server/default/deploy'.
  2. Open the web browser and try to access the following URL:
    http://host:port/JavaAPIEJBTest-war/index.jsp
    Where 'host' will be the address/IP of the machine where JBoss is installed in case of local machine it should be 'localhost', and 'port' where JBoss is listening the request. The default port for JBoss is 8080.
JBoss:
For the following steps %JBOSS_HOME% refers to the location where JBoss is installed and %NCACHE_HOME% refers to the location where NCache is installed.
  1. Move the 'JavaAPIEJBTest.ear' file located at '%NCACHE_HOME%/ samples/bin' to the directory '%JBOSS_HOME%/server/default/deploy'.
  2. Open the web browser and try to access the following URL:
    http://host:port/JavaAPIEJBTest-war/index.jsp
    where 'host' will be the address/IP of the machine where JBoss is installed in case of local machine it should be 'localhost'.
    and 'port' where JBoss is listening the request. Make sure that you are using the correct port. The default port for JBoss is 8080.
See Also
NCache Java Session Module


Topic: Client Side Third Party Integrations

Client Side Third Party Integrations

This tutorial is a practical guide for programmers who want to utilize powerful Third Party Integrations with NCache to create high performance and scalable java applications. This includes working examples and code snippets to utilize various features of NCache efficiently.
In This Section
Enabling NCache in Hibernate Applications
Explains how you can plug-in NCache to your existing Hibernate application to use NCache with Hibernate.
Enabling NCache in Spring Framework Applications
Explains how you can plug-in NCache to your Spring framework application to use NCache with Spring.


Topic: Enabling NCache in Hibernate Applications

Enabling NCache in Hibernate Applications

NCache provides a second level or process level distributed cache for Hibernate by implementing CacheProvider and Cache interfaces. You can plug-in NCache to your existing Hibernate application without any code change. Just change your Hibernate configuration file to plug-in NCache as your cache provider and you're all set to start using distributed caching.
Follow these steps to use NCache with Hibernate.
  1. Register 'hibernate' and 'ncache' configuration sections in the <configSections> of the web.config or app.config as follows:
    <configSections>
    <section name = "hibernate-configuration" type = "Hibernate.Cfg.ConfigurationSectionHandler, Hibernate"/>
    <section name = "ncache" type = "Alachisoft.NCache.Integrations.Hibernate.Cache.NCacheSection, Alachisoft.NCache.Integrations.Hibernate.Cache"/>
    </configSections>
  2. Define section details for <hibernate> as follows:
    <hibernate-configuration xmlns = "urn:hibernate-configuration-2.2">
    <session-factory>
    <property name = "cache.provider_class"> Alachisoft.NCache.Integrations.Hibernate.Cache.NCacheProvider, Alachisoft.NCache.Integrations.Hibernate.Cache </property>
    </session-factory>
    </hibernate-configuration>
  3. Define section details for <ncache> as follows:
<ncache>
<region name = "default">
<add key = "cacheName" value = "mycache"/>
<add key = "enableCacheException" value = "false"/>
<class name = "hibernator.BLL.Customer">
<add key = "priority" value = "1"/>
<add key = "useAsync" value = "false"/>
<add key = "relativeExpiration" value = "180"/> or <add key = "staticExpiration" value = "100"/>
</class>
</region>
</ncache>
The above example of app.config or web.config contains the following options for you to configure. Each of them is explained below as well.
  • hibernate.cache.provider_class: This option lets you specify that NCache is your second level cache provider. You need to mention two classes that implement Hibernate.Cache.CacheProvider and Hibernate.Cache.Cache interfaces respectively. This is how Hibernate knows how to call this second level cache.
  • The "region" attribute of the NCache determines the Cache in which the particular entity will be cached.
  • cacheName: This option is included inside the <ncache> tag and lets you specify name of the cache that you have configured through NCache Manager. All caches in NCache are named and this name allows NCache provider to connect to the right cache.
  • enableCacheException: This flag allows you to turn on exception handling which by default is turned off. This will throw an exception which you'll have to catch in your java application.
  • class: This lets you specify options specific to a java class. All the options below are class-specific. Class name must be same as specified in the mapping file of the class ( .hbm.xml file).
  • priority: The priority you want to use for cached items. The possible values are from 1 to 6.
  • useAsync: This is a flag that tells the provider whether to use the standard synchronized "Add" and "Insert" or the asynchronous "AddAsync" and "InsertAsync" operations. The asynchronous operations immediately return control back to the client and queues up the operation in a background queue. Then, a background thread executes the command.
  • relativeExpiration: This value is specified as number of seconds. It indicates the idle-time expiration for your items, meaning how long your item can stay without being accessed.
Note:
  • Calling new Configuration() only reads the <hibernate> section.
  • Calling no-parameter version of cfg.Configure() configures Hibernate from app.config if it contains <hibernate-configuration>, otherwise hibernate.cfg.xml is used.
See Also
Enabling NCache in Spring Application


Topic: Enabling NCache in Spring Framework Applications

Enabling NCache in Spring Framework Applications

NCache is providing support for Spring framework applications. Now users can cache spring applications data using NCache to enhance performance of the application. Few changes are required in deployment descriptor file (which comes with your spring application) to plug-in NCache as your cache provider and you're all set to start using distributed caching.
Following are the prerequisites to enable NCache in Spring application:
1. You should have a Spring framework application. You can also use sample application for Spring from the following path:
"Installeddirectory:/NCache/samples/java/NetBeans/NCacheSpringTest"
  • In every Spring application, Spring Deployment Descriptor already exists with the xml extension.
2. NCache Java Client for:
  • NCacheSpringAnnotation.jar
  • NCClient.jar
  • NCActivate.jar
  • NCRuntime.jar
  • NCSerialization.jar
Following are the steps required to enable NCache in Spring application:
Step 1: Add Library:
Add "NCacheSpringAnnotation.jar" library to your Spring application. This .jar file is placed at the following path:
"Installeddirectory:/NCache/integration/java/spring".
After adding library, changes are required in 2 different files:
Step 2: Spring Deployment Descriptor Configurations:
Spring Deployment Descriptor already exist in a spring application, following changes are required to be made in this file:
1. Here you need to add the following elements as shown below:
[Existing Schema]
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
In order to inject NCache Spring Provider, you need to add the following two highlighted attributes in the existing schema.
  • Add xmlns:ncache attribute with its value in the schema.
  • Concatenate the NCache location in xsi:schemaLocation with the already existing location fields, as shown below:
[Changed Schema]
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:ncache="http://www.alachisoft.com/ncache/annotations/spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.alachisoft.com/ncache/annotations/spring http://www.alachisoft.com/ncache/annotations/spring/ncache-spring-1.0.xsd">
2. In Spring Deployment Descriptor, add the following element:
<ncache:annotation-driven>
<ncache:cache id="ID-1" name="mycache"/>
<ncache:cache id="ID-2" name="myreplicatedcache"/>
</ncache:annotation-driven>
"NCache:annotation-driven" tag provides the facility to add number of caches to be used with Spring framework application.
Step 3: Application Level Changes:
NCache provides number of annotation to perform various cache related tasks. You only need to add those annotations on the top of your methods to perform those tasks.

1. Key Generator:
Key Generator annotation is used to generate keys for caching spring application data in the cache. Here any of the two methods can be used to generate key for caching data. This annotation can be applicable to both @cacheable and @triggersremove.

a. Default method:
Default key generator includes a class name, method name and a list of arguments a method contains. By default method name is included in the key but you can omit the method name from the key by setting value="false" as shown below:
@Cacheable
(
cacheID="ID-1",
keyGenerator = @KeyGenerator (properties = @Property(name="includeMethod", value="false")))
public Collection<Message> findAllMessages()
{
.....
}
b. Custom Class:
NCache is providing you the facility to have your own custom class for key generation. In this way, you can generate keys in number of flexible ways which meet your business requirements. NCache provides an interface “CacheKeyGenerator” for defining your own key generation technique. All you need to do is to implement “CacheKeyGenerator” interface and override its “generateKey” method.
Below is how your class looks like:
public class MyKeyGenerator implements CacheKeyGenerator
{
public String generateKey(MethodInvocation methodInvocation)
{
return String;
}
}
You need to register your custom class for key generator as beans in spring deployment descriptor using the following xml:
<bean id="MyKeyGenerator" class="NCacheSpringTest.CustomKeyGenerators.MyKeyGenerator" />
Below is the code for calling your custom class for key generation in any annotation:
@Cacheable(cacheID="ID-1", keyGenerator = @KeyGenerator (name="MyKeyGenerator" ) )
public Collection<Message> findAllMessages()
{
.....
}

2. Sliding Expiration:
SlidingExpiration is use to expire the data (returns by the method) from the cache after a specific period of time. It will remove key from the cache if the specified period of time has elapsed since it was last accessed. This annotation is only applicable with @cacheable annotation.
For example:
@Cacheable
(
cacheID="ID-1",
slidingExpirator = @SlidingExpirator (expireAfter=15000)
)
public Collection<Message> findAllMessages()
{
.....
}

3. Partial Cache Key:
PartialCacheKey annotation is used with the default process of key generation. Here, it filters out arguments with which this annotation is appended and include them in the process of key generation while excluding the remaining arguments. PartialCacheKey can be applicable to both attributes of an object and parameters of a method. Here users are supposed to put this annotation before particular attribute/parameter as shown below:
For example:
@TriggersRemove
(
cacheID="ID-1",
when = When.BEFORE_METHOD_INVOCATION,
removeAll = false,
keyGenerator = @KeyGenerator(properties = @Property(name="includeMethod", value="false"))
)
public void updateMessage(@PartialCacheKey long id, String to, String body)
{
......
}

4. Cacheable:
The purpose of this annotation is to cache the data returned by the method with a specific key. Before caching the data, @cacheable generates a method specific key according to the given specifications and cache the data against that key. Here users are supposed to specify a cache id where they are interested to cache data of the method. This annotation is applicable to the methods of a class.
For example:
@Cacheable
(
cacheID="ID-1"
)
public Collection<Message> findAllMessages()
{
Collection<Message> values = messages.values();
Set<Message> messages = new HashSet<Message>();
synchronized (messages) {
Iterator<Message> iterator = values.iterator();
while (iterator.hasNext()) {
messages.add(iterator.next());
}
}
return Collections.unmodifiableCollection(messages);
}

5. Triggers Remove:
As mentioned above, a specific key is required to cache the data of the method. This annotation follows the same procedure for removing the data of a method by generating a similar key with which it is added. The purpose of @triggersremove annotation is to remove the data of a method from the cache by matching the key with the cached keys. To remove data from the cache you need to specify the following attributes:
  • CacheID: Specify the cache id from where the data is to be removed.
  • When: It will specify either the data is removed before or after the execution of a method. It take two different values i.e. When.AFTER_METHOD_INVOCATION and When.BEFORE_METHOD_INVOCATION.
  • RemoveAll: If value of this attribute is "False", it will only remove data of a specific key. If value is "True", it will clear the cache and remove all class related data from the cache.
This annotation is applicable to the methods of a class.
For example:
@TriggersRemove
(
cacheID="ID-1",
when = When.BEFORE_METHOD_INVOCATION,
removeAll = false
)
public void updateMessage(long id, String to, String body)
{
Message message = new Message();
message.setId(id);
message.setTo(to);
message.setBody(body);
messages.remove(id);
messages.put(id, message);
}
Note:
You can cache values of two different methods of a class in two different caches.
Two similar annotations can't be used on top of the same method.
You can not run @TriggersRemove for two caches on top of same method.
See Also
Enabling NCache in Hibernate Application


Topic: Troubleshooting

Troubleshooting

This section is intended as a quick reference for error codes, messages, and symptoms generated by NCache, and provides a summary of the likely problem. Refer to the following section to find details about symptoms and workarounds.
In This Section
Implementing Clusters
Provides help to troubleshoot the problems related to cluster implementation.
Using NCache Client API
Provides help to troubleshoot the problems related to NCache Client API.
Using Security
Provides help to troubleshoot the problems that may arise when using NCache security.
Viewing Statistics
Provides help to view remote server statistics.
Installing NCache
Gives workarounds of the problems that may arise during NCache installation process.
See Also
Getting Started
Presents a brief introduction to NCache, with an emphasis on new and old features, editions and requirements of NCache.
Configuring the Cache
Discusses configuration options that NCache provides for local and clustered caches. It also helps in configuring NCache through NCache Manager and configuration files.
Developing with NCache
Focuses on what is essential to become skilled at developing with NCache. It includes programmers guide, sample applications, hands on tutorials and extensive help on API reference.


Topic: Add Reference issue of Visual Studio 2010

Add Reference issue of Visual Studio 2010

If your development environment is Visual Studio 2010, you may not be able to see NCache .NET assemblies in the Add Reference dialog box under .NET tab. However, you can add reference to the NCache assemblies by using the Browse tab. You can find all these assembly files in NCache Installed folder/bin/assembly/.
See Also
Installing NCache


Topic: Upgrade NCache without disturbing deployed environment

Upgrade NCache without disturbing deployed environment

When a newer version of NCache is installed, your code doesn't need to recompile with the most recent version. Now, with each installation of NCache, a publisher policy file is installed. This file redirects all the previous versions of the specified assembly to the newer version. Policy assembly files for various NCache assemblies are as follows:
NCache Assembly | Publisher Policy Assembly
Alachisoft.NCache.Web.dll | policy.<version>.Alachisoft.NCache.Web.dll
Alachisoft.NCache.Runtime.dll | policy.<version>.Alachisoft.NCache.Runtime.dll
Alachisoft.NCache.Cache.dll | policy.<version>.Alachisoft.NCache.Cache.dll
Here <version> is the newer version of NCache. For example, for NCache 4.1.0.0, publisher policy file for Alachisoft.NCache.Web.dll will be Policy.4.1.0.0.Alachisoft.NCache.Web.dll. These policy assembly files are added to the GAC with all other assemblies and are removed at uninstall.
You can also bypass the publisher policy file by specifying 'publisherpolicy' tag in the "App.config" file.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Alachisoft.NCache.Web" publicKeyToken="cff5926ed6a53769" culture="neutral"/>
<publisherpolicy apply="no"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Alachisoft.NCache.Runtime" publicKeyToken="cff5926ed6a53769" culture="neutral"/>
<publisherpolicy apply="no"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Alachisoft.NCache.Cache" publicKeyToken="cff5926ed6a53769" culture="neutral"/>
<publisherpolicy apply="no"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>


Topic: Troubleshooting Scripts

Troubleshooting Scripts

The InstallNCache and UnInstallNCache scripts internally uses methods of Win32_Product class. If you got any error relating this class during script execution it means that Win32_Product class is not installed on that machine.
On Windows 2003 the Win32_Product class some times isn't installed by default. You can install it with Add/Remove Windows Component.
Steps for Installing Win32_Product class :
Step 1:
Go to Add/Remove Windows Components.
Step 2:
Look for the "Management and Monitoring Tools". If it is uncheck, make it checked. Click on Details Button.
Step 3:
Look for the "WMI Windows Installer Provider". Make it checked. Click OK.
See Also
Configuring PowerShell Environment | Remote Installation/Uninstallation | Activate NCache


Topic: Viewing statistics of a remote server

Viewing Statistics of a Remote Server Node

This section will help you in resolving problems that can occur while monitoring remote server nodes (Windows computers).
In this Section
Computer Name Not Found
Describes reason of this error and gives solutions to resolve it.
Diskperf Not Installed
Describes cause and provides steps to run Diskperf to avoid this error on monitored server node.
No READ Access to the Perflib Subkeys
Explains how to grant account READ permission to the Perflib sub key to avoid error while monitoring performance of a remote sever node.
Unable to Connect to Remote Server (Windows XP Machine)
Discusses causes of this error and offers solutions.
See Also
Implementing Clusters
Provides help to troubleshoot the problems related to cluster implementation.
Using NCacheAPI
Provides help to troubleshoot the problems related to NCache API.
Using Security
This section provides solutions for some common troubles in using NCache security.
Installing NCache
Provides quick reference for error codes, messages, and symptoms generated by NCache during installation


Topic: Troubleshooting Counters

Troubleshooting Counters

You can receive an error message 'Computer Name Not Found' when trying to monitor a remote server node from a non-administrator account.
Workaround
To enable remote monitoring on server node (Windows NT computer), do the following:
  • Grant at least READ access to the following files:%windir%/system32/PERFCxxx.DAT
  • %windir%/system32/PERFHxxx.DAT
    where xxx is the basic language ID for the system; for example, 009 for English.
  • Grant READ access to the following registry keys on the remote computer: Using REGEDT32, grant the user account at least READ access to HKEY_LOCAL_MACHINE/Software/Microsoft/Windows NT/CurrentVersion/Perflib and all sub keys of that key.
  • Using REGEDT32, give the user at least READ access to HKEY_LOCAL_MACHINE/System/CurrentControlSet/Control/SecurePipeServers/winreg.
    Note: Using Registry Editor incorrectly can cause serious system-wide problems that can make you to reinstall Windows operating system. Use this tool at your own risk.
See Also
Viewing Statistics of a Cluster


Topic: Diskperf Not Installed

Diskperf Not Installed

The Windows parameter sets cannot collect information about the monitored computer unless the Disk Performance Statistics Driver (Diskperf) has already been run on the monitored computer.
By default, Diskperf installs the Disk Performance Statistics Driver above the fault tolerant driver, Ftdisk.sys, in the I/O Manager disk driver stack. To determine if Ftdisk is started in your configuration, use the Devices Control Panel.
Workaround
Use the following steps to run Diskperf on the monitored Windows computer. You must be a member of the Administrator's local group on a computer to run Diskperf on that computer.
  • Open a Command Prompt window.
  • At the command prompt, type one of the following commands, and press 'Enter'.
  • diskperf -y: enables the counters on a standard disk configuration
  • diskperf: indicates whether disk counters are enabled or disabled
  • diskperf -yv: enables disk counters on mirror and stripe sets and other noncontiguous partition sets and installs the performance statistics driver below the fault tolerant driver in the I/O stack
  • diskperf -n: disables disk counters
Note:
  • To run diskperf on a remote computer, type the command name, followed by the computer name. For example: diskperf //computername
  • To monitor the physical disks in disk configurations that include Ftdisk, run the diskperf -yv command.
  • Restart the computer.
See Also
Viewing Statistics of a Cluster
Send comments on this topic


Topic: No READ Access to Perflib Subkeys

No READ Access to Perflib Subkeys

After the Performance Monitor (PerfMon) account connects to the Registry of the monitored computer, the account on the monitored computer needs READ access to the subkeys that PerfMon uses. The computer uses the ACL for the Perflib/LanguageID subkey to determine who has access to PerfMon data in the Registry, where LanguageID is the numeric code for the spoken language installed with Windows NT. The Perflib/LanguageID subkey is located in the following Registry path:
HKEY_LOCAL_MACHINE/Software/Microsoft/Windows NT /CurrentVersion/Perflib
By default, EVERYONE, LOCAL SERVICE group has READ access to the Perflib key. You need to give full control to these accounts on Perflib key.
Workaround
Here is how you can enable permissions on CurrentVersion/Perflib key:
  • On the computer to be monitored, start regedit.
  • Right-click Perflib and go to permissions.
  • Give full control to Local Service and Everyone users. You may have to add these users if they are not already in the list.
  • Go to Control Panel -> Services and restart 'Remote Registry' service.
Now you'll be able monitor this machine remotely.
See Also
Viewing Statistics of a Cluster


Topic: Unable to Connect to Server Node (Windows XP/ Windows 7 Machine)

Unable to Connect to Server Node (Windows XP/ Windows 7 Machine)

This error can occur when remote monitoring is not enabled on the server nodes that are running the Windows XP operating system.
Workaround
Use the following steps to enable remote monitoring:
  • Open Windows Explorer on the target Windows XP computer.
  • Choose 'Tools' -> 'Folder Options'.
  • Click the 'View' tab.
  • Clear the 'Use Simple File Sharing' check box, and click 'OK'.
  • Verify privileges on the target Windows XP computer as described in Microsoft Knowledge Base article# Q300702 .
  • If the systemroot is on an NTFS partition, you must have at least READ access to the following two files:
  • %SystemRoot%/System32/Perfc009.dat
  • %SystemRoot%/System32/Perfh009.dat
  • You must have at least READ access to the following registry keys on the remote computer:HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Control/SecurePipeServers/winreg
  • HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows NT/CurrentVersion/Perflib
  • Reboot Windows XP computer.
Note: A user that has administrator rights for the remote computer can also view remote counters.
In windows 7 if you are still unable to view counters of a remote server then enable "File, Folder and network sharing" options.
Follow steps given below
  • Go to Control panel, select "Network and Sharing center"
  • Click "Change Advanced Sharing Settings"
  • Under the Network discovery option select "Turn on network discovery"
  • Under the File and printer sharing option select "Turn on file and printer sharing"
  • Under the Public folder sharing option select "Turn on sharing so anyone with network access can read and write files in Public folders"
  • Then click Save changes, as shown in figure below.
See Also
Viewing Statistics of a Cluster


Topic: NCache API

NCache API

While using NCache API, you might experience some problems. This section provides solutions for some common troubles.
In This Section
No Server is available to process the request
Different situations are explained when this exception is thrown by NCache Client API (both Java and .NET).
java.lang.NoClassDefFoundError: com/alachisoft/ncache/licensing/LicenseManager
Describes when this error occurs and how to solve it. This solution is only for java version of NCache Client API.
com.alachisoft.ncache.exceptions.GeneralFailureException: License not verified
Explains reason of occurrence of this exception and also tells ways to solve this problem. This solution is only for java version of NCache Client API.
See Also
Implementing Clusters
Provides help to troubleshoot the problems related to cluster implementation.
Using NCache API
Provides help to troubleshoot the problems related to NCache API.
Using Security
Provides help to troubleshoot the problems that may arise when using NCache security.
Viewing Statistics
Provides help to view remote server statistics.
Installing NCache
Provides quick reference for error codes, messages, and symptoms generated by NCache during installation.


Topic: GeneralFailureException

GeneralFailureException

You may get this exception when any general type error occur in NCache. For example when the required jar files are not available at their appropriate location or if you can not connect to the target cache etc.
Workaround
  • Run 'install.bat' file at least once before start using NCache Client API. This file is located at %INSTALL_DIR%/NCache/java/lib/.
  • 'installer.jar', 'NCActivate', 'NCRuntime.jar', 'NCSerialization.jar', 'NCClient.jar' and 'javaReg.properties' should also be present at the above mentioned location.


Topic: java.lang.NoClassDefFoundError

java.lang.NoClassDefFoundError

The "java.lang.NoClassDefFoundError : com/alachisoft/ncache/licensing/LicenseManager" occurs when the required jar files are not available at their appropriate location. NCache Client API for java is shipped with the following jar files:
  • NCClient.jar: The Main NCache Client API file.
  • NCActivate.jar: The file is responsible for the Activation of NCache. The user may extend his/her evaluation period by running this file. this file can be run by executing the "activate.bat" file.
  • installer.jar: This file is only for Unix environment and is responsible for NCache client installation on Unix machines.
  • NCRuntime.jar: The file is responsible for Read-through/Write-through caching and Cache Startup operations.
  • NCSerialization.jar: This file is responsible for dynamic compact serialization and object sharing operations.
  • NCacheSessionProvider.jar: This file is responsible for providing JSP session caching support.
  • NCUtil.jar: This file contains the methods required by NCache Manager and Service.
  • swing-layout-1.0.4.jar: This file is providing java library for GUI.
  • javassist.jar: This file is the 3rd party library responsible for runtime code generation.
Workaround
Copy all the three jar files at the same location and mention location in class-path.


Topic: No server available to process request

No server available to process request

You may get this exception if the cache you are trying to connect is not running or the cache does not exist on the target machine.
Workaround
To workaround this problem, do the following:
  • See if the Servers specified in the client.ncconf are stopped. If so, then start them using NCache Manager. See Start a Server Node for further details .
  • Another situation can be that NCache Server is running but the cache that you are trying to use is not running. See Start a Cluster for more information.
  • Verify that you are using correct version of NCache Client API. Note that the Developer Edition does not allow you to connect to the remote NCache Server; however you can connect to NCache Server running on the same machine, using "localhost" as the server name in the client configuration file. Enterprise Edition does not have any such restriction. You can check NCache Edition from Help->About menu option in NCache Manager.
  • NCache Client API also throws this exception if it does not find the client.ncconf file or if there is any error reading NCache Server information from it.
  • And same error occurs if user tries to initialize a cache which does not exist or that cache is not listed in the "client.ncconf".
See Also
Start the Cluster | Start NCache Service | Configuring Clients


Topic: SessionStoreProvider not found

SessionStoreProvider not found

You may get following error message when using Session Store Provider.
Error: Could not load type 'Alachisoft.NCache.Web.SessionState.NSessionStoreProvider'.
Workaround
Please make sure the following also exists in your web.config:
<assemblies>
<add assembly="Alachisoft.NCache.SessionStoreProvider, Version=x.x.x.x, Culture=neutral, PublicKeyToken=CFF5926ED6A53769"/>
</assemblies>
Replace version “x.x.x.x” with the actual NCache version that you have.
See Also
Using Session State Store Provider


Topic: Implementing Clusters

Implementing Clusters

When Implementing Clusters, you may experience some problems. This section provides solutions for some of such troubles.
In This Section
Multiple Network Cards
Tells how to resolve the issue when NCache service may not be able to communicate with other nodes in the cluster if you have multiple network cards installed.
Compact serialization exception
Explains various causes of serialization exception.
Blocked node communication due to firewall
Explains ports used by default clusters and NCache service.
Out of memory problem
Describes why your system throws out of memory exception and gives workaround.
Unable to apply configurations or start cache due to disabled network card
Explains problems that arise due to disabled network card and provides solutions.
NCache Manager shows that both the nodes in Mirror Cache are active nodes
Provides the solution for the problem when both the nodes in a mirror cache appear as active nodes in NCache Manager.
Nodes in a clustered cache are not joining with each other.
Provides the solution for the problem nodes in a clustered cache are not joining with each other. Cluster is not formed and cache runs on every node as standalone cache.
See Also
Configuring with NCache Manager
Describes administration, implementation and monitoring of cluster through NCache Manager.
Using NCache API
Provides help to troubleshoot the problems related to NCache API.
Using Security
Provides help to troubleshoot the problems that may arise when using NCache security.
Viewing Statistics
Provides help to view remote server statistics.
Installing NCache
Provides quick reference for error codes, messages, and symptoms generated by NCache during installation.


Topic: Compact Serialization exception

Compact Serialization exception

Sometimes a Serialization exception may occur on node where Compact Serializable types are not registered.
Workaround
Register Compact Serializable types on all the nodes in the cluster. See Using Compact Types for further information.
See Also
Using Compact Serialization | Multiple Network Cards | Blocked node communication due to firewall | Out of memory problem | Unable to apply configurations or start cache due to disabled network card | Both nodes in a mirror cache appear as active nodes in NCache Manager | Nodes in a clustered cache are not joining with each other


Topic: Disabled Netwrok Card

Unable to apply configurations or start cache due to disabled network card

You may not be able to apply cache configurations or start the cache. Or, clients may be unable to connect with server even on local machine. These problems arise when network card is disabled or cable is not connected.
Workaround
To resolve this problem, restart NCache service once after the network card is disabled or network cable is disconnected. Restarting NCache service will rebind it to local host rather than IP address of that machine.
See Also
Multiple Network Cards | Compact serialization exception | Blocked node communication due to firewall | Out of memory problem | Both nodes in a mirror cache appear as active nodes in NCache Manager | Nodes in a clustered cache are not joining with each other


Topic: Maximum Size

Maximum Size

Through this configuration option, you can specify an upper limit on size of the cache in MB. The number of items in cache are limited by maximum size of the cache and amount of free system memory (virtual or physical). If some eviction policy is specified, whenever total data size in cache reaches maximum size or when lesser than 10% of memory is left in the system, items are removed from the cache as per eviction policy. Maximum size of a cache can be specified by one of following two ways.
NCache Manager:
You can specify cache max size for a Cache on Main Tab of its view window.
Config.ncconf:
You can specify the cache max size through Config.ncconf as follows.
<cache-config name="mypartitionedcache" inproc="False" config-id="1" last-modified="6/20/2010 3:50:34 PM">
<storage type="heap" cache-size="250mb"/>
</cache-config>
See Also
Configure Local Cache | Configure Cluster


Topic: Out of memory problem

Out of memory problem

Sometimes your system throws out of memory exception while using NCache. This usually happens when Maximum Size for the cache is not specified correctly. Often, processing overhead is not kept into consideration while specifying the Maximum Size.
Workaround
In order to resolve out of memory issue, NCache has provided a memory based cache, where you can specify an upper limit on the size of the cache in MB. Please specify correct Maximum Size for your cache.
You should specify a Maximum Size which, if completely consumed, still leaves enough space in the system so that it never goes under low resources. While specifying the cache size, consider the following factors:
  • Average size of Sessions or Objects.
  • Number of expected Sessions or Objects.
  • Available memory for the NCache process.
Then you can calculate the required memory by keeping the following in mind.
  • 15% Overhead per session.
  • 15-20% overhead for processing. If object size is greater than 80KB, this ratio may be little bit high.
See Also
Multiple Network Cards | Compact serialization exception | Blocked node communication due to firewall | Unable to apply configurations or start cache due to disabled network card | Both nodes in a mirror cache appear as active nodes in NCache Manager | Nodes in a clustered cache are not joining with each other
Send comments on this topic .


Topic: Multiple Network Cards

Multiple Network Cards

If you have dedicated network cards configured for public and private communication, then you might not be able to create new clusters or possibly existing NCache cluster could not communicate with others. Please note, the following problems will occur if nodes are unable to communicate with each other on specific interface(s).
  • NCache Service starts at one interface whereas other nodes try to communicate with it on the other interface. Therefore the two nodes are always unable to communicate with each other even when apparently both nodes are fully functional.
  • NCache Clients connect to NCache Server to get OutProc cache instances. So, it is possible that NCache Server starts at one interface whereas the client tries to connect to it on the other interface. This way, though NCache Server is ready to accept the client requests, client applications will always be unable to connect to the OutProc caches.
  • Situations can arise where cluster nodes are unable to join with each other and no cluster is forming. The reason could be that one node is listening join requests from other nodes on one network interface whereas other nodes send join requests on other network interface.
Workaround
To avoid such problems, you can bind NCache service to specific IP that is publicly available to other nodes in the cluster. Here is how you can bind IP to NCache service:
  • Go to Alachisoft.NCache.Service.exe.config located at
    %INSTALLATION_PATH%/NCache/bin/service/Alachisoft.NCache.Service.exe.config
  • Add following line in the configuration file:
    <add key = "NCacheServer.BindToClusterIP" value = "" />
    <add key = "NCacheServer.BindToClientServerIP" value = "" />
    BindToClusterIP: You can inform NCache which interface to use for cluster-wide communication. In order to do so, provide the IP Address you want the cluster server to bind with.
    BindToClientServerIP: You can inform NCache which interface to use for client communication. In order to do so, please provide the IP Address you want the client's (NCache client) server to bind with.
Note: If you want to initialize your clustered cache as InProc, you need to provide same information in your application's config file. Otherwise, this node may not join with other cluster nodes.
See Also
Configuring NCache Service | Detecting Multiple Network Cards | Compact serialization exception | Blocked node communication due to firewall | Out of memory problem | Unable to apply configurations or start cache due to disabled network card | Both nodes in a mirror cache appear as active nodes in NCache Manager | Nodes in a clustered cache are not joining with each other


Topic: Nodes not Joining

Nodes in a clustered cache are not joining

Some times it may be the case when you start a clustered cache, but nodes do not join with each other. It means that cluster is not formed and cache runs on each node as a standalone cache. You can use listcaches utility to confirm if the cluster is formed properly or not. When listcaches utility is used with '/a' switch, it lists all the nodes that have successfully joined the cluster. You can also use the NCache Manager "View Cluster Connectivity" GUI tool to check the node connectivity. "View Cluster Connectivity" option is available in a cluster properties and also located at NCache Manager tool bar.
Workaround
To resolve this problem:
  • See that every node can be accessed from every other node participating in the clustered cache. For this you can use the 'ping' utility. If nodes are not accessible then there is some network problem and must be resolved before starting the cache.
  • Please see that the cache configuration on each node contains the correct initial hosts list. Every node participating in the clustered cache must be listed there.
  • If the initial hosts list is not correct then update the initial hosts list and restart NCache service on all nodes.
  • Restart the clustered cache.
See Also
Multiple Network Cards | Compact serialization exception | Blocked node communication due to firewall | Out of memory problem | Both nodes in a mirror cache appear as active nodes in NCache Manager


Topic: Blocked node communication due to firewall

Blocked node communication due to firewall

Sometimes a cluster can not be formed, or cluster nodes are unable to communicate with each other. It may happen when Server and Cluster ports are blocked by firewall. Following error messages can occur in this case.
Error: "No server available to process request"
or
Error: "Unable to communicate with server node"
Workaround
  • If cluster is not formed, make it sure that Server port, at which NCache Service starts and accepts different client connections, is not blocked by firewall. Default value of this port is '9800'. You can change the default value from Alachisoft.NCache.Service.exe.config file.
  • If nodes in a cluster are unable to communicate, please see if your firewall is allowing the Cluster port. Cluster port is a port at which nodes in a cluster communicate. You can change the default value of these ports from NCache Manager . If you have specified a port range in NCache Manager, unblock all ports in range.
  • If NCache Manager is unable to connect with NCache Service, even when it is started, then your system firewall might be blocking Service port. Unblock Service port from system firewall.
See Also
Configuring Ports | Multiple Network Cards | Compact serialization exception | Out of memory problem | Unable to apply configurations or start cache due to disabled netwrok card | Both nodes in a mirror cache appear as active nodes in NCache Manager | Nodes in a clustered cache are not joining with each other
Send comments on this topic .


Topic: Two Active Nodes Situation

Both nodes in a mirror cache appear as active in NCache Manager

On starting a mirror cache, situation may arise where both nodes are shown as active in NCache Manager. This means that nodes could not join with each other. It is not a mirror cache cluster instead two different mirror caches are running on each node.
Workaround
To resolve this problem see how to resolve the nodes not joining issue .
See Also
Multiple Network Cards | Compact serialization exception | Blocked node communication due to firewall | Out of memory problem | Nodes in a clustered cache are not joining with each other


Topic: Installing NCache

Installing NCache

This section is intended as a quick reference for error codes, messages, and symptoms generated by NCache during installation, and provides a summary of the likely problem. Refer to the following section to find details about symptoms and workarounds.
In This Section
NCache Installation Error 1606: Could not access network location
Helps to troubleshoot the problem of NCache installation on Windows Vista.
Installation Error 1721: A required program could not be run
Provides help to troubleshoot the error 1721 occurred during install or uninstall process.
Upgrade NCache
Gives help on upgrading NCache without disturbing deployed environment.
Installation roll back problem on Windows Vista
Gives work around for installation roll back problem on Windows Vista.
NCache activation problem
Explains why NActivate tool fails to launch and gives workaround.


Topic: NCache Activation Error

NCache Activation Error

In some situations, while trying to launch NActivate tool, following error message is shown:
Error: "This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem."
This error message occurs usually when VC++ libraries are not installed. NActivate tool uses assemblies developed in VC++. Windows 2003 installation does not install Visual C++ Libraries required to run applications developed with Visual C++ on a computer that does not have Visual C++ 2005 SP1 installed.
Workaround
Install redistributable package from Microsoft. It will install all the required libraries. You can download redistributable package from the following link:
http://www.microsoft.com/en-us/download/details.aspx?id=26347
See Also
NCache Installation Error 1606 | Installation Error 1721: A required progaram could not be run | Upgrading NCache | Installation rolls back on Windows Vista


Topic: Error 1721: A required program could not be run

Installation Error 1721: A required program could not be run

On Windows Vista and Windows Server 2010, you may get the following error during install or uninstall process:
Error 1721: 'There is a problem with this Windows Installer package. A program required for this install to complete could not be run. Contact your support personnel or package vendor.'
This usually happens if UAC (User Account Control) is enabled on the target machine.
Workaround
To workaround this problem, please follow these steps:
  • Create a batch file containing the following command:
    msiexec /I "<NCache MSI path>"
  • Right click on the batch file and click Run as Administrator.
See Also
NCache Installation Error 1606 | Upgrading NCache | Installation rolls back on Windows Vista | NCache activation problem


Topic: Upgrade NCache without disturbing deployed environment

Upgrade NCache without disturbing deployed environment

When a newer version of NCache is installed, your code need no longer be recompiled with the most recent version. Now, with each installation of NCache, a publisher policy file is installed. This file redirects all the previous versions of the specified assembly to the newer version. Policy assembly files for various NCache assemblies are as follows:
NCache Assembly | Publisher Policy Assembly
Alachisoft.NCache.Web.dll | policy.<version>.Alachisoft.NCache.Web.dll
Alachisoft.NCache.Runtime.dll | policy.<version>.Alachisoft.NCache.Runtime.dll
Alachisoft.NCache.Cache.dll | policy.<version>.Alachisoft.NCache.Cache.dll
Here <version> is the newer version of NCache. For example, for NCache 4.1.0.0, publisher policy file for Alachisoft.NCache.Web.dll will be Policy.4.1.0.0.Alachisoft.NCache.Web.dll. These policy assembly files are added to the GAC with all other assemblies and are removed at uninstall.
You can also bypass the publisher policy file by specifying 'publisherpolicy' tag in the "App.config" file.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Alachisoft.NCache.Web" publicKeyToken="cff5926ed6a53769" culture="neutral"/>
<publisherpolicy apply="no"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Alachisoft.NCache.Runtime" publicKeyToken="cff5926ed6a53769" culture="neutral"/>
<publisherpolicy apply="no"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Alachisoft.NCache.Cache" publicKeyToken="cff5926ed6a53769" culture="neutral"/>
<publisherpolicy apply="no"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
See Also
NCache Installation Error 1606 | Installation Error 1721: A required progaram could not be run | Installation rolls back on Windows Vista | NCache activation problem


Topic: Installation Ended Prematurely

Installation Ended Prematurely

With 64-bit NCache installation, you may get the following error at the end of the installation.
Error: "installation ended prematurely"
This usually happens when NCache service is not removed properly.
Workaround
To workaround this problem on Windows computer, please follow these steps.
  • Run the following command on VS.NET command prompt to uninstall the service.
/> InstallUtil /u "C:\ProgramFiles\NCache\bin\serviceAlachisoft.NCache.Service.exe"
  • If you don't have the service file in the NCache/bin/service folder then copy it from the other machine and paste it there and run the command. It should uninstall the NCache service.
  • Install NCache.
See Also
Removing NCache assemblies from GAC


Topic: Removing NCache assemblies from GAC

Unable to remove assembly from the GAC machine

You may be unable to uninstall assemblies using select and delete mechanism from GAC. You will need to delete them using command prompt (manually). You will get following message:
Error: "Assembly Alachisoft.NCache.* could not be uninstalled because it is required by other application."
Workaround
Do the following to delete assemblies from GAC:
  • Go to command prompt.
  • Go to folder %windir%/assembly/GAC_MSIL/
  • Go to the respective assembly folder and remove the assembly.
See Also
Installation ends prematurely


Topic: NCache Installation Error 1606

NCache Installation Error 1606: Could not access network location

In some situations, you may unable to install NCache on Windows Vista with following error message.
Error: 'Error 1606. Could not access network location %SystemDrive%/inetpub/wwwroot/'
Workaround
In order to fix this, do the following:
  • Disable UAC in Windows Vista.
  • Find the following key: HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/InetStp/PathWWWRoot
  • Change the value of this registry key from '%SystemDrive%/inetpub/wwwroot' to 'C:\inetpub\wwwroot'. If your default website in IIS is stored at a different location, set the value of this registry key to that path.
  • Enable IIS 6.0 administration.
See Also
Installation Error 1721: A required progaram could not be run | Upgrading NCache | Installation rolls back on Windows Vista | NCache activation problem


Topic: Installation roll backs on Windows Vista

Installation roll backs on Windows Vista

When you install NCache on Windows Vista, sometimes it rolls back towards the end without giving any error.
Workaround
To workaround this problem on a Windows Vista computer, please follow these steps.
  • Click Start, go to Settings, and then click Control Panel.
  • In control panel, click the Programs and then click the "Turn Windows features on or off"
  • In the windows features dialog, find Internet Information Services and expand the tree to Web Management Tools and click the node IIS 6 Management Compatibility to enable it.
  • Click OK and let Windows install the selected feature on your system.
  • Now you can install NCache.
See Also
Upgrading NCache | NCache Installation Error 1606 | Installation Error 1721: A required program could not be run | NCache activation problem


Topic: Using Security

Using Security

This section provides solutions for some common troubles in using NCache security.
In This Section
Alachisoft.NCache.Runtime.Exceptions.SecurityException
Different situations are explained when this exception is thrown by NCache.
See Also
Implementing Clusters
Provides help to troubleshoot the problems related to cluster implementation.
Using NCache API
Provides help to troubleshoot the problems related to NCache API.
Viewing Statistics
Provides help to view remote server statistics.
Installing NCache
Provides quick reference for error codes, messages, and symptoms generated by NCache during installation.


Topic: Alachisoft.NCache.Runtime.Exceptions.SecurityException

Alachisoft.NCache.Runtime.Exceptions.SecurityException

This exception is raised if an unauthorized user tries to perform cache operations, or wrong credential information is given in the InitializeCache() overload given below or in client.ncconf file.
Workaround
To avoid security exception, do the following :
  • Check if you have given correct credential information through API or in client.ncconf. A typing mistake can be the result of this exception.
  • See if the user which you have specified exists under given domain in LDAP. Login credentials are required to belong to any WINDOWS Server hosting the user login and running Active Directory services.
  • Check if you have given a double slash '//' to separate domain name and User ID when passing them as a string through API. Sometimes a single slash is given, which is recognized as an escape sequence. In that case, no compile time error arises, rather it results in a security exception. Correct way to pass security information through API is shown below:
    // Initialize the cache
    NCache.InitializeCache("myQSReplicatedCache", primaryUserCredentials, secondaryUserCredentials);
See Also
Security | Configuring Security


Topic: Cache Event IDs

Cache Event IDs

Below is a table explaining Cache Event IDs.
Event Name | ID | Description
CacheStart | 1000 | Cache Started Successfully
CacheStop | 1001 | Cache Stopped Successfully
CacheStartError | 1002 | You don't have permission to perform this operation
CacheStopError | 1003 | Cache cannot be stopped due to an exception
ClientConnected | 1004 | Client has connected to cache
ClientDisconnected | 1005 | Client has disconnected from the cache
NodeJoined | 1006 | Node has joined
NodeLeft | 1007 | Node Has Left
StateTransferStart | 1008 | NCache has started state transfer
StateTransferStop | 1009 | NCache has completed state transfer
StateTransferError | 1010 | NCache has ended state transfer prematurely
UnhandledException | 1011 | An unhandled exception has occurred
ServiceStartFailure | 1013 | NCache Service fails to start (Normally in case of server reboot)
LoggingEnabled | 1014 | Logging enabled successfully
LoggingDisabled | 1015 | Logging disabled successfully
CacheSizeWarning | 1016 | Cache has exceeded from allocated cache size
GeneralError | 1017 | NCache failed to open log
GeneralInformation | 1018 | Any other information that cannot be defined using the current event IDs
ConfigurationError | 1019 | BridgeServer failed to load configuration information
LicensingError | 1020 | NCache evaluation has expired. It can't be extended anymore therefore, please purchase NCache license from sales@alachisoft.com and activate before expiration
SecurityError | 1021 | You don't have permission to perform this operation


Topic: How to's

How to's

This section contains the most commonly asked question.
In This Section
How to do NCache Version Upgrades?
Describes how to upgrade Microsoft SharePoint Server 2007 to Microsoft SharePoint Server 2010.
What is the Recommended Way to Apply Windows Patches on NCache Server?
Describes, how to convert External BLOB Storage to Remote BLOB Storage without copying BLOBs .
See Also
Troubleshooting
Presents a brief introduction to NCache, with an emphasis on new and old features, editions and requirements of NCache.
Configuring the Cache
Discusses configuration options that NCache provides for local and clustered caches. It also helps in configuring NCache through NCache Manager and configuration files.
Installing Ncache
Focuses on what is essential to become skilled at developing with NCache. It includes programmers guide, sample applications, hands on tutorials and extensive help on API reference.


Topic: How to do NCache Version Upgrades?

How to do NCache Version Upgrades?

NCache major version can be upgraded by few simple steps given below:
1. Create Backup of config.ncconf (Optional)
If you are upgrading major version of the NCache then in order to restore old configurations you need to create a backup of config.ncconf file but it is recommended to use new configuration settings in case of major version upgrade. Also refer back to the backup config.ncconf file to see what options you have already configured in order to have exactly same configuration settings again. Backup of log files can also be kept for history purpose.
2. Uninstall NCache
Uninstall current version of NCache. If any application is using NCache and you uninstall NCache then, an error message will be displayed as shown below.
Here you have to remove assemblies by yourself
  1. Remove .NET Framework 2.0 assemblies manually from [System Drive]:\Windows\assembly
  2. Remove .NET Framework 4.0 assemblies from [SystemDrive]:\Windows\Microsoft.NET\assembly
  1. For NCache 3.8 remove assemblies manually e.g.
1. [SystemDrive]:\Windows\Microsoft.NET\assembly\GAC_32\Alachisoft.NCache.Web\ v4.0_3.8.0.0__cff5926ed6a53769\Alachisoft.NCache.Web.dll
2. [SystemDrive]:\Windows\Microsoft.NET\Assembly\GAC_64\Alachisoft.NCache.Web\v4.0_3.8.0.0__cff5926ed6a53769\Alachisoft.NCache.Web.dll
b. For NCache 4.1 and above remove assemblies manually from [SystemDrive]:\Windows\Microsoft.NET\assembly\GAC_MSIL e.g.
1. [SystemDrive]:\Windows\Microsoft.NET\Assembly\GAC_MSIL\Alachisoft.NCache.Web\v4.0_4.1.0.0__cff5926ed6a53769\Alachisoft.NCache.Web.dll
3. Install New Version
Install new version of NCache. For complete step by step installation process see installation guide .
4. Verification
After installation you can verify whether NCache has been installed correctly or not by using some command line tools such as:
Startcache mycache It will start default shipped cache ‘mycache’.
Addtestdata mycache It will add 10 items in the cache ‘mycache’, if cache is already started.
Getcachecount mycache It will return the number of total item exist in cache i.e. ‘mycache’.
Listcaches It will show all the created caches on current machine.
5. Upgradeconfiguration Tool (Optional)
For restoring previous configuration settings use command line tool " upgradeconfiguration.exe ". Use of this tool is useful only when you want to use previous configuration settings otherwise it is not required.
You can also bind NCache service to specific IP that is publicly available to other nodes in the cluster. For details see Select Network Interface Card .
6. Recompile Application
If you are using object caching then you have to recompile your application. And if you are using view state caching or session state caching then you may have to change version manually from web.config file, generally their versions are not changed. But still it can be changed from web.config file For Example:
<assemblies>
<add assembly="Alachisoft.NCache.SessionStoreProvider, Version=x.x.x.x, Culture=neutral, PublicKeyToken=CFF5926ED6A53769"/>
</assemblies>
Replace Version “x.x.x.x” with the NCache version that you have just installed.
Similarly, if you are using NCache SessionStore provider module or content optimization feature then you need to follow the same process. Find “Alachisoft.NCache.*” and change “version=x.x.x.x” with the current version of the NCache module in use.
Note: NCache module version can be different from the NCache version e.g. NCache current release version is “4.1.0.0” but its ContentOptimization module version is “1.0.0.0”.
See Also
Installation Guide | Upgrading NCache | Command Line Tools | NCache Activation Problem


Topic: What is the Recommended Way to Apply Windows Patches on NCache Server?

< Previous page

What is the Recommended Way to Apply Windows Patches on NCache Server?

Recommended way for applying windows patches on NCache Server is windows standard procedure.
Required steps are:
1. Stop the cache
Stop the cache by right click on IP address of the node in NCache Manager under your cache cluster. If this node is part of multiple cache clusters then you need to stop this node/cache from all cache clusters. This will start state transfer process and data will be re-adjusted on other nodes available in the cluster.
2. Stop NCache Service
Stop NCache service on this server and also change the service startup type from “Automatic” to “Manual”, so that you can manually start NCache service after reboot.
3. Apply Patch
Apply required patches/updates. Complete all the maintenance tasks running on this machine and then reboot the servers.
4. Restart NCache service
After successful completion of step 3 now restart NCache service and also change service start up type back to “Automatic” for normal usage.
5. Start the cache
Now start the cache manually from NCache manager if auto-start is not enabled. Refresh cache cluster from NCache manger to view this node as active node in the cluster. Furthermore, you can see data being transferred to this lately added cache node.
Perform same steps for other nodes in your environment. The main reason of starting NCache service manually is that some of the patches complete their operations after some time of system startup and it is a good practice to start NCache service manually once all the patches are fully applied and maintenance work is complete on your server.
See Also
Installation Guide | Upgrading NCache | Unable to Connect to Remote Server (Windows XP Machine) | How to do NCache version upgrades
Send comments on this topic.
< Previous page