15 Building Integratable Objects for .NET Clients

Coherence caches are used to cache value objects. Enabling .NET clients to successfully communicate with a Coherence JVM requires a platform-independent serialization format that allows both .NET clients and Coherence JVMs (including Coherence*Extend Java clients) to properly serialize and deserialize value objects stored in Coherence caches. The Coherence for .NET client library and Coherence*Extend clustered service use a serialization format known as Portable Object Format (POF). POF allows value objects to be encoded into a binary stream in such a way that the platform and language origin of the object is irrelevant.

15.1 Configuring a POF Context

POF supports all common .NET and Java types out-of-the-box. Any custom .NET and Java class can also be serialized to a POF stream; however, there are additional steps required to do so:

  1. Create a .NET class that implements the IPortableObject interface. (See "Creating an IPortableObject Implementation (.NET)")

  2. Create a matching Java class that implements the PortableObject interface in the same way. (See "Creating a PortableObject Implementation (Java)")

  3. Register your custom .NET class on the client. (See "Registering Custom Types on the .NET Client")

  4. Register your custom Java class on each of the servers running the Coherence*Extend clustered service. (See "Registering Custom Types in the Cluster")

Once these steps are complete, you can cache your custom .NET classes in a Coherence cache in the same way as a built-in data type. Additionally, you will be able to retrieve, manipulate, and store these types from a Coherence or Coherence*Extend JVM using the matching Java classes.

15.1.1 Creating an IPortableObject Implementation (.NET)

Each class that implements IPortableObject can self-serialize and deserialize its state to and from a POF data stream. This is achieved in the ReadExternal (deserialize) and WriteExternal (serialize) methods. Conceptually, all user types are composed of zero or more indexed values (properties) which are read from and written to a POF data stream one by one. The only requirement for a portable class, other than the need to implement the IPortableObject interface, is that it must have a default constructor which will allow the POF deserializer to create an instance of the class during deserialization.

Example 15-1 illustrates a user-defined portable class:

Example 15-1 A User-Defined Portable Class

public class ContactInfo : IPortableObject
{
    private string name;
    private string street;
    private string city;
    private string state;
    private string zip;
    public ContactInfo()
    {}
    public ContactInfo(string name, string street, string city, string state, string zip)
    {
        Name   = name;
        Street = street;
        City   = city;
        State  = state;
        Zip    = zip;
    }
    public void ReadExternal(IPofReader reader)
    {
        Name   = reader.ReadString(0);
        Street = reader.ReadString(1);
        City   = reader.ReadString(2);
        State  = reader.ReadString(3);
        Zip    = reader.ReadString(4);
    }
    public void WriteExternal(IPofWriter writer)
    {
        writer.WriteString(0, Name);
        writer.WriteString(1, Street);
        writer.WriteString(2, City);
        writer.WriteString(3, State);
        writer.WriteString(4, Zip);
    }
    // property definitions ommitted for brevity
}

15.1.2 Creating a PortableObject Implementation (Java)

An implementation of the portable class in Java is very similar to the one in .NET from the example above:

Example 15-2 illustrates the Java version of the .NET class in Example 15-1.

Example 15-2 A User-Defined Class in Java

public class ContactInfo implements PortableObject
    {    private String m_sName;

    private String m_sStreet;
    private String m_sCity;
    private String m_sState;
    private String m_sZip;
    public ContactInfo()
        {
        }
    public ContactInfo(String sName, String sStreet, String sCity, String sState, String sZip)
        {
        setName(sName);
        setStreet(sStreet);
        setCity(sCity);
        setState(sState);
        setZip(sZip);
        }
    public void readExternal(PofReader reader)
            throws IOException
        {
        setName(reader.readString(0));
        setStreet(reader.readString(1));
        setCity(reader.readString(2));
        setState(reader.readString(3));
        setZip(reader.readString(4));
        }
    public void writeExternal(PofWriter writer)
            throws IOException
        {
        writer.writeString(0, getName());
        writer.writeString(1, getStreet());
        writer.writeString(2, getCity());
        writer.writeString(3, getState());
        writer.writeString(4, getZip());
        }
    // accessor methods omitted for brevity
}

15.1.3 Registering Custom Types on the .NET Client

Each POF user type is represented within the POF stream as an integer value. As such, POF requires an external mechanism that allows a user type to be mapped to its encoded type identifier (and visa versa). This mechanism uses an XML configuration file to store the mapping information. This is illustrated in Example 15-3. These elements are described in "POF User Type Configuration Elements .

Example 15-3 Storing Mapping Informaiton in the POF User Type Configuration File

<?xml version="1.0"?>
<pof-config xmlns="http://schemas.tangosol.com/pof">
  <user-type-list>
    <!-- include all "standard" Coherence POF user types -->
    <include>assembly://Coherence/Tangosol.Config/coherence-pof-config.xml</include>
    <!-- include all application POF user types -->

    <user-type>

      <type-id>1001</type-id>
      <class-name>My.Example.ContactInfo, MyAssembly</class-name>
    </user-type>
    ...
  </user-type-list>
</pof-config>

There are few things to note:

  • Type identifiers for your custom types should start from 1001 or higher, as the numbers below 1000 are reserved for internal use.

  • You need not specify a fully qualified type name within the class-name element. The type and assembly name is enough.

Once you have configured mappings between type identifiers and your custom types, you must configure Coherence for .NET to use them by adding a serializer element to your cache configuration descriptor. Assuming that user type mappings from Example 15-3 are saved into my-dotnet-pof-config.xml, you need to specify a serializer element as illustrated in Example 15-4:

Example 15-4 Using a Serializer in the Cache Configuration File

<remote-cache-scheme>
  <scheme-name>extend-direct</scheme-name>
  <service-name>ExtendTcpCacheService</service-name>
  <initiator-config>
    ...
    <serializer>
      <class-name>Tangosol.IO.Pof.ConfigurablePofContext, Coherence</class-name>
      <init-params>
        <init-param>
          <param-type>string</param-type>
          <param-value>my-dotnet-pof-config.xml</param-value>
        </init-param>
      </init-params>
    </serializer>
   </initiator-config>
</remote-cache-scheme>

The ConfigurablePofContext type will be used for the POF serializer if one is not explicitly specified. It uses a default configuration file ($AppRoot/coherence-pof-config.xml) if it exists, or a specific file determined by the contents of the pof-config element in the Coherence for .NET application configuration file. For example:

Example 15-5 Specifying a POF Configuration File

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="coherence" type="Tangosol.Config.CoherenceConfigHandler, Coherence"/>
  </configSections>
  <coherence>
    <pof-config>my-dotnet-pof-config.xml</pof-config>
  </coherence>
</configuration>

See "Configuring and Using the Coherence for .NET Client Library" for additional details.

15.1.4 Registering Custom Types in the Cluster

Each Coherence node running the TCP/IP Coherence*Extend clustered service requires a similar POF configuration for the custom types to be able to send and receive objects of these types.

The cluster-side POF configuration file looks similar to the one created on the client. The only difference is that instead of .NET class names, you must specify the fully qualified Java class names within the class-name element.

Example 15-6 illustrates a sample cluster-side POF configuration file called my-java-pof-config.xml:

Example 15-6 Cluster-side POF Configuration File

<?xml version="1.0"?>
<!DOCTYPE pof-config SYSTEM "pof-config.dtd">
<pof-config>
  <user-type-list>
    <!-- include all "standard" Coherence POF user types -->
    <include>example-pof-config.xml</include>
    <!-- include all application POF user types -->
    <user-type>
      <type-id>1001</type-id>
      <class-name>com.mycompany.example.ContactInfo</class-name>
    </user-type>
    ...
  </user-type-list>
</pof-config>

Once your custom types have been added, you must configure the server to use your POF configuration when serializing objects. This is illustrated in Example 15-7:

Example 15-7 Configuring the Server to Use the POF Configuration

<proxy-scheme>
  <service-name>ExtendTcpProxyService</service-name>
  <acceptor-config>
    ...
    <serializer>
      <class-name>com.tangosol.io.pof.ConfigurablePofContext</class-name>
      <init-params>
        <init-param>
          <param-type>string</param-type>
          <param-value>my-java-pof-config.xml</param-value>
        </init-param>
      </init-params>
    </serializer>
   </acceptor-config>
  ...
</proxy-scheme>

15.1.5 Evolvable Portable User Types

PIF-POF includes native support for both forward- and backward-compatibility of the serialized form of portable user types. In .NET, this is accomplished by making user types implement the IEvolvablePortableObject interface instead of the IPortableObject interface. The IEvolvablePortableObject interface is a marker interface that extends both the IPortableObject and IEvolvable interfaces. The IEvolvable interface adds three properties to support type versioning.An IEvolvable class has an integer version identifier n, where n >= 0. When the contents and/or semantics of the serialized form of the IEvolvable class changes, the version identifier is increased. Two versions identifiers, n1 and n2, indicate the same version if n1 == n2; the version indicated by n2 is newer than the version indicated by n1 if n2 > n1.

The IEvolvable interface is designed to support the evolution of types by the addition of data. Removal of data cannot be safely accomplished if a previous version of the type exists that relies on that data. Modifications to the structure or semantics of data from previous versions likewise cannot be safely accomplished if a previous version of the type exists that relies on the previous structure or semantics of the data.

When an IEvolvable object is deserialized, it retains any unknown data that has been added to newer versions of the type, and the version identifier for that data format. When the IEvolvable object is subsequently serialized, it includes both that version identifier and the unknown future data.

When an IEvolvable object is deserialized from a data stream whose version identifier indicates an older version, it must default and/or calculate the values for any data fields and properties that have been added since that older version. When the IEvolvable object is subsequently serialized, it includes its own version identifier and all of its data. Note that there will be no unknown future data in this case; future data can only exist when the version of the data stream is newer than the version of the IEvolvable type.

Example 15-8 demonstrates how the ContactInfo .NET type can be modified to support class evolution:

Example 15-8 Modifying a Class to Support Class Evolution

public class ContactInfo : IEvolvablePortableObject
{
    private string name;
    private string street;
    private string city;
    private string state;
    private string zip;
    // IEvolvable members
    private int    version;
    private byte[] data;
    public ContactInfo()
    {}
    public ContactInfo(string name, string street, string city, string state, string zip)
    {
        Name   = name;
        Street = street;
        City   = city;
        State  = state;
        Zip    = zip;
    }
    public void ReadExternal(IPofReader reader)
    {
        Name   = reader.ReadString(0);
        Street = reader.ReadString(1);
        City   = reader.ReadString(2);
        State  = reader.ReadString(3);
        Zip    = reader.ReadString(4);
    }
    public void WriteExternal(IPofWriter writer)
    {
        writer.WriteString(0, Name);
        writer.WriteString(1, Street);
        writer.WriteString(2, City);
        writer.WriteString(3, State);
        writer.WriteString(4, Zip);
    }
    public int DataVersion
    {
        get { return version; }
        set { version = value; }
    }
    public byte[] FutureData
    {
        get { return data; }
        set { data = value; }
    }
    public int ImplVersion
    {
        get { return 0; }
    }
    // property definitions ommitted for brevity
}

Likewise, the ContactInfo Java type can also be modified to support class evolution by implementing the EvolvablePortableObject interface:

Example 15-9 Modifying a Java Type Class to Support Class Evolution

public class ContactInfo
        implements EvolvablePortableObject
    {
    private String m_sName;
    private String m_sStreet;
    private String m_sCity;
    private String m_sState;
    private String m_sZip;

    // Evolvable members
    private int    m_nVersion;
    private byte[] m_abData;

    public ContactInfo()
        {}

    public ContactInfo(String sName, String sStreet, String sCity,
            String sState, String sZip)
        {
        setName(sName);
        setStreet(sStreet);
        setCity(sCity);
        setState(sState);
        setZip(sZip);
        }

    public void readExternal(PofReader reader)
            throws IOException
        {
        setName(reader.readString(0));
        setStreet(reader.readString(1));
        setCity(reader.readString(2));
        setState(reader.readString(3));
        setZip(reader.readString(4));
        }

    public void writeExternal(PofWriter writer)
            throws IOException
        {
        writer.writeString(0, getName());
        writer.writeString(1, getStreet());
        writer.writeString(2, getCity());
        writer.writeString(3, getState());
        writer.writeString(4, getZip());
        }

    public int getDataVersion()
        {
        return m_nVersion;
        }

    public void setDataVersion(int nVersion)        {
        m_nVersion = nVersion;
        }

    public Binary getFutureData()
        {
        return m_binData;
        }

    public void setFutureData(Binary binFuture)
        {
        m_binData = binFuture;
        }

    public int getImplVersion()
        {
        return 0;
        }

    // accessor methods omitted for brevity
    }

15.1.6 Making Types Portable Without Modification

In some cases, it may be undesirable or impossible to modify an existing user type to make it portable. In this case, you can externalize the portable serialization of a user type by creating an implementation of the IPofSerializer in .NET and/or an implementation of the PofSerializer interface in Java.

Example 15-10 illustrates, an implementation of the IPofSerializer interface for the ContactInfo type.

Example 15-10 An Implementation of IPofSerializer for the .NET Type

public class ContactInfoSerializer : IPofSerializer
{
    public object Deserialize(IPofReader reader)
    {
        string name   = reader.ReadString(0);
        string street = reader.ReadString(1);
        string city   = reader.ReadString(2);
        string state  = reader.ReadString(3);
        string zip    = reader.ReadString(4);

        ContactInfo info = new ContactInfo(name, street, city, state, zip);
        info.DataVersion = reader.VersionId;
        info.FutureData  = reader.ReadRemainder();

        return info;
    }

    public void Serialize(IPofWriter writer, object o)
    {
        ContactInfo info = (ContactInfo) o;

        writer.VersionId = Math.Max(info.DataVersion, info.ImplVersion);
        writer.WriteString(0, info.Name);
        writer.WriteString(1, info.Street);
        writer.WriteString(2, info.City);
        writer.WriteString(3, info.State);
        writer.WriteString(4, info.Zip);
        writer.WriteRemainder(info.FutureData);
    }
}

An implementation of the PofSerializer interface for the ContactInfo Java type would look similar:

Example 15-11 An Implementation of PofSerializer for the Java Type Class

public class ContactInfoSerializer
        implements PofSerializer
    {
    public Object deserialize(PofReader in)
            throws IOException
        {
        String sName   = in.readString(0);
        String sStreet = in.readString(1);
        String sCity   = in.readString(2);
        String sState  = in.readString(3);
        String sZip    = in.readString(4);

        ContactInfo info = new ContactInfo(sName, sStreet, sCity, sState, sZip);
        info.setDataVersion(in.getVersionId());
        info.setFutureData(in.readRemainder());

        return info;
        }

    public void serialize(PofWriter out, Object o)
            throws IOException
        {
        ContactInfo info = (ContactInfo) o;

        out.setVersionId(Math.max(info.getDataVersion(), info.getImplVersion()));
        out.writeString(0, info.getName());
        out.writeString(1, info.getStreet());
        out.writeString(2, info.getCity());
        out.writeString(3, info.getState());
        out.writeString(4, info.getZip());
        out.writeRemainder(info.getFutureData());
        }
    }

To register the IPofSerializer implementation for the ContactInfo .NET type, specify the class name of the IPofSerializer within a serializer element under the user-type element for the ContactInfo user type in the POF configuration file. This is illustrated in Example 15-12:

Example 15-12 Registering the IPofSerializer Implementation of the .NET Type

<?xml version="1.0"?>

<pof-config xmlns="http://schemas.tangosol.com/pof">
  <user-type-list>
    <!-- include all "standard" Coherence POF user types -->
    <include>assembly://Coherence/Tangosol.Config/coherence-pof-config.xml</include>

    <!-- include all application POF user types -->
    <user-type>
      <type-id>1001</type-id>
      <class-name>My.Example.ContactInfo, MyAssembly</class-name>
      <serializer>
        <class-name>My.Example.ContactInfoSerializer, MyAssembly</class-name>
      </serializer>
    </user-type>
      ...
  </user-type-list>
</pof-config>

Similarly, you can register the PofSerializer implementation for the ContactInfo Java type. This is illustrated in Example 15-13.

Example 15-13 Registering the PofSerializer Implementation of the Java Type

<?xml version="1.0"?>
<!DOCTYPE pof-config SYSTEM "pof-config.dtd">
<pof-config>
  <user-type-list>
    <!-- include all "standard" Coherence POF user types -->
    <include>example-pof-config.xml</include>

    <!-- include all application POF user types -->
    <user-type>
      <type-id>1001</type-id>
      <class-name>com.mycompany.example.ContactInfo</class-name>
      <serializer>
        <class-name>com.mycompany.example.ContactInfoSerializer</class-name>
      </serializer>
    </user-type>
    ...
  </user-type-list>
</pof-config>

15.2 Configuring and Using the Coherence for .NET Client Library

To use the Coherence for .NET library in your .NET applications, you must add a reference to the Coherence.dll library in your project and create the necessary configuration files.

Creating a reference to the Coherence.dll:

  1. In your project go to Project->Add Reference... or right click References in the Solution Explorer and choose Add Reference...

  2. In the Add Reference window that appears, choose the Browse tab and find the Coherence.dll library on your file system.

    Figure 15-1 Add Reference Window

    Description of Figure 15-1 follows
    Description of "Figure 15-1 Add Reference Window"

  3. Click OK.

Next, you must create the necessary configuration files and specify their paths in the application configuration settings. This is done by adding an application configuration file to your project (if one was not already created) and adding a Coherence for .NET configuration section (that is, <coherence/>) to it.

Example 15-14 Sample Application Configuration File

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="coherence" type="Tangosol.Config.CoherenceConfigHandler, Coherence"/>
  </configSections>
  <coherence>
    <cache-factory-config>my-coherence.xml</cache-factory-config>
    <cache-config>my-cache-config.xml</cache-config>
    <pof-config>my-pof-config.xml</pof-config>
  </coherence>
</configuration>

Elements within the Coherence for .NET configuration section are:

  • cache-factory-config—contains the path to a configuration descriptor used by the CacheFactory to configure the IConfigurableCacheFactory and Logger used by the CacheFactory.

  • cache-config—contains the path to a cache configuration descriptor which contains the cache configuration described earlier (see Configuring Coherence*Extend on the Client). This cache configuration descriptor is used by the DefaultConfigurableCacheFactory.

  • pof-config—contains the path to the configuration descriptor used by the ConfigurablePofContext to register custom types used by the application.

Figure 15-2 illustrates what the solution should look like after adding the configuration files:

Figure 15-2 File System Displaying the Configuration Files

Description of Figure 15-2 follows
Description of "Figure 15-2 File System Displaying the Configuration Files"

15.2.1 CacheFactory

The CacheFactory is the entry point for Coherence for .NET client applications. The CacheFactory is a factory for INamedCache instances and provides various methods for logging. If not configured explicitly, it uses the default configuration file coherence.xml which is an assembly embedded resource. It is possible to override the default configuration file by adding a cache-factory-config element to the Coherence for .NET configuration section in the application configuration file and setting its value to the path of the desired configuration file.

Example 15-15 Configuring a Factory for INamedCache Instances

<?xml version="1.0"?>

<configuration>
  <configSections>
    <section name="coherence" type="Tangosol.Config.CoherenceConfigHandler, Coherence"/>
  </configSections>
  <coherence>
    <cache-factory-config>my-coherence.xml</cache-factory-config>
    ...
  </coherence>
</configuration>

This file contains the configuration of two components exposed by the CacheFactory by using static properties:

  • CacheFactory.ConfigurableCacheFactory—the IConfigurableCacheFactory implementation used by the CacheFactory to retrieve, release, and destroy INamedCache instances.

  • CacheFactory.Logger—the Logger instance used to log messages and exceptions.

When you are finished using the CacheFactory (for example, during application shutdown), the CacheFactory should be shutdown by using the Shutdown() method. This method terminates all services and the Logger instance.

15.2.2 IConfigurableCacheFactory

The IConfigurableCacheFactory implementation is specified by the contents of the <configurable-cache-factory-config> element:

  • class-name—specifies the implementation type by it's assembly qualified name.

  • init-params—defines parameters used to instantiate the IConfigurableCacheFactory. Each parameter is specified by using a corresponding param-type and param-value child element.

Example 15-16 Configuring a ConfigurableCacheFactory Implementation

<coherence>
  <configurable-cache-factory-config>
    <class-name>Tangosol.Net.DefaultConfigurableCacheFactory, Coherence</class-name>
    <init-params>
      <init-param>
        <param-type>string</param-type>
        <param-value>simple-cache-config.xml</param-value>
      </init-param>
    </init-params>
  </configurable-cache-factory-config>
</coherence>

If an IConfigurableCacheFactory implementation is not defined in the configuration, the default implementation is used (DefaultConfigurableCacheFactory).

15.2.3 DefaultConfigurableCacheFactory

The DefaultConfigurableCacheFactory provides a facility to access caches declared in the cache configuration descriptor described earlier (see the Client-side Cache Configuration Descriptor section). The default configuration file used by the DefaultConfigurableCacheFactory is $AppRoot/coherence-cache-config.xml, where $AppRoot is the working directory (in the case of a Windows Forms application) or the root of the application (in the case of a Web application).

If you want to specify another cache configuration descriptor file, you can do so by adding a cache-config element to the Coherence for .NET configuration section in the application configuration file with its value set to the path of the configuration file.

Example 15-17 Specifying a Different Cache Configuration Desriptor File

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="coherence" type="Tangosol.Config.CoherenceConfigHandler, Coherence"/>
  </configSections>
  <coherence>
    <cache-config>my-cache-config.xml</cache-config>
    ...
  </coherence>
</configuration>

15.2.4 Logger

The Logger is configured using the logging-config element:

  • destination—determines the type of LogOutput used by the Logger. Valid values are:

    • common-logger for Common.Logging

    • stderr for Console.Error

    • stdout for Console.Out

    • file path if messages should be directed to a file

  • severity-level—determines the log level that a message must meet or exceed to be logged.

  • message-format—determines the log message format.

  • character-limit—determines the maximum number of characters that the logger daemon will process from the message queue before discarding all remaining messages in the queue.

Example 15-18 Configuring a Logger

<coherence>
  <logging-config>
    <destination>log4net</destination>
    <severity-level>5</severity-level>
    <message-format>(thread={thread}): {text}</message-format>
    <character-limit>8192</character-limit>
  </logging-config>
</coherence>

The CacheFactory provides several static methods for retrieving and releasing INamedCache instances:

  • GetCache(String cacheName)—retrieves an INamedCache implementation that corresponds to the NamedCache with the specified cacheName running within the remote Coherence cluster.

  • ReleaseCache(INamedCache cache)—releases all local resources associated with the specified instance of the cache. After a cache is release, it can no longer be used.

  • DestroyCache(INamedCache cache)—destroys the specified cache across the Coherence cluster.

Methods used to log messages and exceptions are:

  • IsLogEnabled(int level)—determines if the Logger would log a message with the given severity level.

  • Log(Exception e, int severity)—logs an exception with the specified severity level.

  • Log(String message, int severity)—logs a text message with the specified severity level.

  • Log(String message, Exception e, int severity)—logs a text message and an exception with the specified severity level.

Logging levels are defined by the values of the CacheFactory.LogLevel enum values (in ascending order):

  • Always

  • Error

  • Warn

  • Info

  • Debug—(default log level)

  • Quiet

  • Max

15.2.5 Using the Common.Logging Library

Common.Logging is an open source library that enables you to plug in various popular open source logging libraries behind a well-defined set of interfaces. The libraries currently supported are Log4Net (versions 1.2.9 and 1.2.10) and NLog. Common.Logging is currently used by the Spring.NET framework and will likely be used in the future releases of IBatis.NET and NHibernate, so you might want to consider it if you are using one or more of these frameworks in combination with Coherence for .NET, as it will allow you to configure logging consistently throughout the application layers.

Coherence for .NET does not include the Common.Logging library. If you would like to use the common-logger Logger configuration, you must download the Common.Logging assembly and include a reference to it in your project. You can download the Common.Logging assemblies for both .NET 1.1 and 2.0 from the following location:

http://netcommon.sourceforge.net/

The Coherence for .NET Common.Logging Logger implementation was compiled against the signed release version of these assemblies.

15.2.6 INamedCache

The INamedCache interface extends IDictionary, so it can be manipulated in ways similar to a dictionary. Once obtained, INamedCache instances expose several properties:

  • CacheName—the cache name.

  • Count—the cache size.

  • IsActive—determines if the cache is active (that is, it has not been released or destroyed).

  • Keys—collection of all keys in the cache mappings.

  • Values—collection of all values in the cache mappings.

The value for the specified key can be retrieved by using cache[key]. Similarly, a new value can be added, or an old value can be modified by setting this property to the new value: cache[key] = value.

The collection of cache entries can be accessed by using GetEnumerator() which can be used to iterate over the mappings in the cache.

The INamedCache interface provides several methods used to manipulate the contents of the cache:

  • Clear()—removes all the mappings from the cache.

  • Contains(Object key)—determines if the cache has a mapping for the specified key.

  • GetAll(ICollection keys)—returns all values mapped to the specified keys collection.

  • Insert(Object key, Object value)—places a new mapping into the cache. If a mapping for the specified key already exists, its value will be overwritten by the specified value and the old value will be returned.

  • Insert(Object key, Object value, long millis)—places a new mapping into the cache, but with an expiry period specified by several milliseconds.

  • InsertAll(IDictionary dictionary)—copies all the mappings from the specified dictionary to the cache.

  • Remove(Object key)—Removes the mapping for the specified key if it is present and returns the value it was mapped to.

INamedCache interface also extends the following three interfaces: IQueryCache, IObservableCache, and IInvocableCache.

15.2.7 IQueryCache

The IQueryCache interface exposes the ability to query a cache using various filters.

  • GetKeys(IFilter filter)—returns a collection of the keys contained in this cache for entries that satisfy the criteria expressed by the filter.

  • GetEntries(IFilter filter)—returns a collection of the entries contained in this cache that satisfy the criteria expressed by the filter.

  • GetEntries(IFilter filter, IComparer comparer)—returns a collection of the entries contained in this cache that satisfy the criteria expressed by the filter. It is guaranteed that the enumerator will traverse the collection in the order of ascending entry values, sorted by the specified comparer or according to the natural ordering if the "comparer" is null.

Additionally, the IQueryCache interface includes the ability to add and remove indexes. Indexes are used to correlate values stored in the cache to their corresponding keys and can dramatically increase the performance of the GetKeys and GetEntries methods.

  • AddIndex(IValueExtractor extractor, bool isOrdered, IComparer comparator)—adds an index to this cache that correlates the values extracted by the given IValueExtractor to the keys to the corresponding entries. Additionally, the index information can be optionally ordered.

  • RemoveIndex(IValueExtractor extractor)—removes an index from this cache.

Example 15-19 illustrates code that performs an efficient query of the keys of all entries that have an age property value greater or equal to 55.

Example 15-19 Querying Keys on a Particular Value

IValueExtractor extractor = new ReflectionExtractor("getAge");

cache.AddIndex(extractor, true, null);
ICollection keys = cache.GetKeys(new GreaterEqualsFilter(extractor, 55));

15.2.8 IObservableCache

IObservableCache interface enables an application to receive events when the contents of a cache changes. To register interest in change events, an application adds a Listener implementation to the cache that will receives events that include information about the event type (inserted, updated, deleted), the key of the modified entry, and the old and new values of the entry.

  • AddCacheListener(ICacheListener listener)—adds a standard cache listener that will receive all events (inserts, updates, deletes) emitted from the cache, including their keys, old, and new values.

  • RemoveCacheListener(ICacheListener listener)—removes a standard cache listener that was previously registered.

  • AddCacheListener(ICacheListener listener, object key, bool isLite)—adds a cache listener for a specific key. If isLite is true, the events may not contain the old and new values.

  • RemoveCacheListener(ICacheListener listener, object key)—removes a cache listener that was previously registered using the specified key.

  • AddCacheListener(ICacheListener listener, IFilter filter, bool isLite)—adds a cache listener that receive events based on a filter evaluation. If isLite is true, the events may not contain the old and new values.

  • RemoveCacheListener(ICacheListener listener, IFilter filter)—removes a cache listener that previously registered using the specified filter.

Listeners registered using the filter-based method will receive all event types (inserted, updated, and deleted). To further filter the events, wrap the filter in a CacheEventFilter using a CacheEventMask enumeration value to specify which type of events should be monitored.

In Example 15-20 a filter evaluates to true if an Employee object is inserted into a cache with an IsMarried property value set to true.

Example 15-20 Filtering on an Inserted Object

new CacheEventFilter(CacheEventMask.Inserted, new EqualsFilter("IsMarried", true));

In Example 15-21 a filter evaluates to true if any object is removed from a cache.

Example 15-21 Filtering on Removed Object

new CacheEventFilter(CacheEventMask.Deleted);

In Example 15-22 a filter that evaluates to true if when an Employee object LastName property is changed from Smith.

Example 15-22 Filtering on a Changed Object

new CacheEventFilter(CacheEventMask.UpdatedLeft, new EqualsFilter("LastName", "Smith"));

15.2.9 IInvocableCache

An IInvocableCache is a cache against which both entry-targeted processing and aggregating operations can be invoked. The operations against the cache contents are executed by (and thus within the localized context of) a cache. This is particularly useful in a distributed environment, because it enables the processing to be moved to the location at which the entries-to-be-processed are being managed, thus providing efficiency by localization of processing.

  • Invoke(object key, IEntryProcessor agent)—invokes the passed processor against the entry specified by the passed key, returning the result of the invocation.

  • InvokeAll(ICollection keys, IEntryProcessor agent)—invokes the passed processor against the entries specified by the passed keys, returning the result of the invocation for each.

  • InvokeAll(IFilter filter, IEntryProcessor agent)—invokes the passed processor against the entries that are selected by the given filter, returning the result of the invocation for each.

  • Aggregate(ICollection keys, IEntryAggregator agent)—performs an aggregating operation against the entries specified by the passed keys.

  • Aggregate(IFilter filter, IEntryAggregator agent)—performs an aggregating operation against the entries that are selected by the given filter.

15.2.10 Filters

The IQueryCache interface provides the ability to search for cache entries that meet a given set of criteria, expressed using a IFilter implementation.

All filters must implement the IFilter interface:

  • Evaluate(object o)—apply a test to the specified object and return true if the test passes, false otherwise.

Coherence for .NET includes several IFilter implementations in the Tangosol.Util.Filter namespace.

The code in Example 15-23 retrieves the keys of all entries that have a value equal to 5.

Example 15-23 Retrieving Keys Equal to a Numeric Value

EqualsFilter equalsFilter = new EqualsFilter(IdentityExtractor.Instance, 5);
ICollection  keys         = cache.GetKeys(equalsFilter);

The code in Example 15-24 retrieves all keys that have a value greater or equal to 55.

Example 15-24 Retrieving Keys Greater Than or Equal To a Numeric Value

GreaterEqualsFilter greaterEquals = new GreaterEqualsFilter(IdentityExtractor.Instance, 55);
ICollection         keys          = cache.GetKeys(greaterEquals);

The code in Example 15-25 retrieves all cache entries that have a value that begins with Belg.

Example 15-25 Retrieving Keys Based on a String Value

LikeFilter  likeFilter = new LikeFilter(IdentityExtractor.Instance, "Belg%", '\\', true);
ICollection entries    = cache.GetEntries(likeFilter);

The code in Example 15-26 retrieves all cache entries that have a value that ends with an (case sensitive) or begins with An (case insensitive).

Example 15-26 Retrieving Keys Based on a Case-Sensitive String Value

OrFilter    orFilter = new OrFilter(new LikeFilter(IdentityExtractor.Instance, "%an", '\\', false), new LikeFilter(IdentityExtractor.Instance, "An%", '\\', true));
ICollection entries  = cache.GetEntries(orFilter);

15.2.11 Extractors

Extractors are used to extract values from an object. All extractors must implement the IValueExtractor interface:

  • Extract(object target)—extract the value from the passed object.

Coherence for .NET includes the following extractors:

  • IdentityExtractor is a trivial implementation that does not actually extract anything from the passed value, but returns the value itself.

  • KeyExtractor is a special purpose implementation that serves as an indicator that a query should be run against the key objects rather than the values.

  • ReflectionExtractor extracts a value from a specified object property.

  • MultiExtractor is composite IValueExtractor implementation based on an array of extractors. All extractors in the array are applied to the same target object and the result of the extraction is a IList of extracted values.

  • ChainedExtractor is composite IValueExtractor implementation based on an array of extractors. The extractors in the array are applied sequentially left-to-right, so a result of a previous extractor serves as a target object for a next one.

The code in Example 15-27 retrieves all cache entries with keys greater than 5:

Example 15-27 Retrieving Cache Entries Greater Than a Numeric Value

IValueExtractor extractor = new KeyExtractor(IdentityExtractor.Instance);
IFilter         filter    = new GreaterFilter(extractor, 5);
ICollection     entries   = cache.GetEntries(filter);

The code inExample 15-28 retrieves all cache entries with values containing a City property equal to city1:

Example 15-28 Retrieving Cache Entries Based on a String Value

IValueExtractor extractor = new ReflectionExtractor("City");
IFilter         filter    = new EqualsFilter(extractor, "city1");
ICollection     entries   = cache.GetEntries(filter);

15.2.12 Processors

A processor is an invocable agent that operates against the entry objects within a cache.

All processors must implement the IEntryProcessor interface:

  • Process(IInvocableCacheEntry entry)—process the specified entry.

  • ProcessAll(ICollection entries)—process a collection of entries.

Coherence for .NET includes several IEntryProcessor implementations in the Tangosol.Util.Processor namespace.

The code in Example 15-29 demonstrates a conditional put. The value mapped to key1 is set to 680 only if the current mapped value is greater than 600.

Example 15-29 Conditional Put of a Key Value Based on a Numeric Value

IFilter         greaterThen600 = new GreaterFilter(IdentityExtractor.Instance, 600);
IEntryProcessor processor      = new ConditionalPut(greaterThen600, 680);
cache.Invoke("key1", processor);

The code in Example 15-30 uses the UpdaterProcessor to update the value of the Degree property on a Temperature object with key BGD to the new value 26.

Example 15-30 Setting a Key Value Based on a Numeric Value

cache.Insert("BGD", new Temperature(25, 'c', 12));
IValueUpdater   updater   = new ReflectionUpdater("setDegree");
IEntryProcessor processor = new UpdaterProcessor(updater, 26);
object          result    = cache.Invoke("BGD", processor);

15.2.13 Aggregators

An aggregator represents processing that can be directed to occur against some subset of the entries in an IInvocableCache, resulting in an aggregated result. Common examples of aggregation include functions such as minimum, maximum, sum and average. However, the concept of aggregation applies to any process that must evaluate a group of entries to come up with a single answer. Aggregation is explicitly capable of being run in parallel, for example in a distributed environment.

All aggregators must implement the IEntryAggregator interface:

  • Aggregate(ICollection entries)—process a collection of entries to produce an aggregate result.

Coherence for .NET includes several IEntryAggregator implementations in the Tangosol.Util.Aggregator namespace.

The code in Example 15-31 returns the size of the cache:

Example 15-31 Returning the Size of the Cache

IEntryAggregator aggregator = new Count();
object           result     = cache.Aggregate(cache.Keys, aggregator);

The code in Example 15-32 returns an IDictionary with keys equal to the unique values in the cache and values equal to the number of instances of the corresponding value in the cache:

Example 15-32 Returning an IDictionary

IEntryAggregator aggregator = GroupAggregator.CreateInstance(IdentityExtractor.Instance, new Count());
object           result     = cache.Aggregate(cache.Keys, aggregator);

Like cached value objects, all custom IFilter, IExtractor, IProcessor and IAggregator implementation classes must be correctly registered in the POF context of the .NET application and cluster-side node to which the client is connected. As such, corresponding Java implementations of the custom .NET types must be created, compiled, and deployed on the cluster-side node. Note that the actual execution of the these custom types is performed by the Java implementation and not the .NET implementation.

See "Configuring a POF Context" for additional details.

15.3 Launching a Coherence DefaultCacheServer Process

To start a DefaultCacheServer that uses the cluster-side Coherence cache configuration described earlier to allow Coherence for .NET clients to connect to the Coherence cluster by using TCP/IP, you need to do the following:

  1. Change the current directory to the Oracle Coherence library directory (%COHERENCE_HOME%\lib on Windows and $COHERENCE_HOME/lib on UNIX).

  2. Make sure that the paths are configured so that the Java command will run.

  3. Start the DefaultCacheServer command line application with the -Dtangosol.coherence.cacheconfig system property set to the location of the cluster-side Coherence cache configuration descriptor described earlier.

Example 15-33 illustrates a sample command line.

Example 15-33 Command to Launch a Coherence Default Cache Server

java -cp coherence.jar -Dtangosol.coherence.cacheconfig=file://<path to the server-side cache configuration descriptor> com.tangosol.net.DefaultCacheServer