Total Pageviews

4 Jan 2014

Using AppFabric Programmatically on SharePoint 2013 Farm

First of all, if you are going to use standard App Fabric cluster that goes with the prerequisites for SharePoint 2013 you'll end up being unsupported by Microsoft:

If you are using custom applications in SharePoint Server 2013 which use the AppFabric client APIs, or are creating custom caches, you should create a separate AppFabric cache cluster to support your custom applications. Do not use the AppFabric cache cluster supporting your SharePoint Server 2013 farm. Run your separate AppFabric cache cluster for your custom applications on separate servers from the servers dedicated to your SharePoint Server 2013 farm.

If you still want to use the OOB AF cluster, here is a sample code for it:

 static void Main(string[] args)
        List<DataCacheServerEndpoint> servers = new List<DataCacheServerEndpoint>();
        servers.Add(new DataCacheServerEndpoint("server.domain", 22233));
        DataCacheFactoryConfiguration configuration = new DataCacheFactoryConfiguration();
        configuration.ChannelOpenTimeout = TimeSpan.FromSeconds(120);
        configuration.IsCompressionEnabled = false;
        configuration.MaxConnectionsToServer = 10;
        configuration.RequestTimeout = TimeSpan.FromSeconds(120);
        configuration.Servers = servers;
        configuration.TransportProperties.MaxBufferSize = 1000000;
        DataCacheFactory dataCacheFactory = new DataCacheFactory(configuration);
        DataCache cache = dataCacheFactory.GetCache("DistributedDefaultCache_" + SPFarm.Local.Id);

        if (cache.Get("MyKEY") == null)
            cache.Add("MyKEY", DateTime.Now);
        DateTime dt = (DateTime)cache.Get("MyKEY");

Note that you need to get the list of all servers in your cluster. In order to do it dynamically, you can use this piece of code:
string cacheClusterName = "SPDistributedCacheCluster_" + SPFarm.Local.Id;
var cacheClusterManager = SPDistributedCacheClusterInfoManager.Local;
var cacheClusterInfo =     cacheClusterManager.GetSPDistributedCacheClusterInfo(cacheClusterName);

foreach (var cacheHost in cacheClusterInfo.CacheHostsInfoCollection)
  servers.Add(new DataCacheServerEndpoint(cacheHost.HostName, cacheHost.CachePort));
I've also found a very decent helper class for working with OOB App Fabric cache (credits to Bernado Nguyen-Hoan).

No comments:

Post a Comment