Search code examples
.netcachingpowershellappfabric

How to create regions on App Fabric via Powershell


I think the title is clear, I'm surfing the web about an hour but every single page talks about creating regions dynamically using .net. I'm sure we have a command to execute on powershell. do you know it?

Thanks in advance,


Solution

  • There's no Powershell commandlet out of the box for creating/managing regions.

    The solution - write one!

    As Daniel Richnak says in the comments, Powershell is .NET under the covers, and this means you can write extra Powershell commandlets to fill in the gaps.

    A commandlet is a regular class that inherits from System.Management.Automation.Cmdlet, and it's decorated with the System.Management.Automation.Cmdlet attribute as well. Making it work is then a matter of overriding the ProcessRecord method. Command-line parameters are implemented as properties on the class, decorated with the System.Management.Automation.Parameter attribute. So a commandlet for creating regions would look something like:

    using System.Management.Automation;
    using Microsoft.ApplicationServer.Caching;
    
    [Cmdlet(VerbsCommon.New, "CacheRegion")]
    public class NewCacheRegion : Cmdlet
    {
        [Parameter(Mandatory = true, Position = 1)]
        public string Cache { get; set; }
        [Parameter(Mandatory = true, Position = 2)]
        public string Region { get; set; }
    
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
    
            DataCacheFactory factory = new DataCacheFactory();
            DataCache cache = factory.GetCache(Cache);
    
            try
            {
                cache.CreateRegion(Region);
            }
            catch (DataCacheException ex)
            {
                if (ex.ErrorCode == DataCacheErrorCode.RegionAlreadyExists)
                {
                    Console.WriteLine(string.Format("There is already a region named {0} in the cache {1}.", Region, Cache));
                }
            }
        }
    }