appfabricappfabric-cacheazure-appfabric

How to read all the items present in an Appfabric Cache:


I am trying to develop a tool (in Visual Studio 2010, C#) which can read all the items present in an Appfabric cache and store them in a Table. I don't have to use powershell.

First I thought that If I can get all the regions present in the cache, I can make use of the DataCache.GetObjectsInRegion Method to complete my task. But I was not able to get all the region names from the cache as it does not shows the user defined region names but only the default ones, so now I am giving up on this approach.

Can anyone please guide me here, my main goal is to read all the items present in a cache.


Solution

  • There is no built-in method to list all items in the cache.

    You're correct, it's possible to list all items using GetObjectsInRegion for a named cache. You have to know first all regions names (if used) or call GetSystemRegions to get all (default) system regions. A simple foreach will allow you to list all items. When you put something into the cache without region name, it will be added to a system region.

    Here is a basic example

        // Declare array for cache host(s).
        DataCacheServerEndpoint[] servers = new DataCacheServerEndpoint[1];
        servers[0] = new DataCacheServerEndpoint("YOURSERVERHERE", 22233);
    
        // Setup the DataCacheFactory configuration.
        DataCacheFactoryConfiguration factoryConfig = new DataCacheFactoryConfiguration();
        factoryConfig.Servers = servers;
    
        factoryConfig.SecurityProperties = new DataCacheSecurity(DataCacheSecurityMode.None, DataCacheProtectionLevel.None);
    
        // Create a configured DataCacheFactory object.
        DataCacheFactory mycacheFactory = new DataCacheFactory(factoryConfig);
    
        // Get a cache client for the default cache 
        DataCache myCache = mycacheFactory.GetDefaultCache(); //or change to mycacheFactory.GetCache(myNamedCache);
    
        //inserty dummytest data
        myCache.Put("key1", "myobject1");
        myCache.Put("key2", "myobject2");
        myCache.Put("key3", "myobject3");
        Random random = new Random();
    
        //list all items in the cache : important part
        foreach (string region in myCache.GetSystemRegions())
        {
            foreach (var kvp in myCache.GetObjectsInRegion(region))
            {
                Console.WriteLine("data item ('{0}','{1}') in region {2} of cache {3}", kvp.Key, kvp.Value.ToString(), region, "default");
            }
        }