Search code examples
cachingappfabric

Adding Named Data Cache Programmatically in Appfabric


I want to add named data cache programmatically in appfabric. I kept following code for this :-

    try
    {
        //This can also be kept in a config file
        var config = new DataCacheFactoryConfiguration();
        config.SecurityProperties = new DataCacheSecurity();

        config.Servers = new List<DataCacheServerEndpoint> { new DataCacheServerEndpoint(Environment.MachineName, 22233) };

        DataCacheFactory dcf = new DataCacheFactory(config);

        if (dcf != null)
        {
            var state = InitialSessionState.CreateDefault();
            state.ImportPSModule(new string[] { "DistributedCacheAdministration", "DistributedCacheConfiguration" });
            state.ThrowOnRunspaceOpenError = true;
            var rs = RunspaceFactory.CreateRunspace(state);
            rs.Open();
            var pipe = rs.CreatePipeline();
            pipe.Commands.Add(new Command("Use-CacheCluster"));

            var cmd = new Command("New-Cache");
            cmd.Parameters.Add(new CommandParameter("Name", "Vaibhav"));

            cmd.Parameters.Add(new CommandParameter("Expirable", false));
            pipe.Commands.Add(cmd);

            var output = pipe.Invoke();
        }
    }
    catch (Exception e)
    {
        //throw new Exception 
    }

But this is not working as expected when i try to access the DataCache (using: dcf.GetCache("Vaibhav");) it is giving Cache not found error. When i created the Cache using powershell it worked fine and i was able to access the Cache, but i want to implement this programmactically and not by Command Prompt(powershell)

Please suggest a proper way to implement this....

Thanks in Advance Vaibhav


Solution

  • You actually have to Start the Visual Studio as admin to be able to create Cache programatically.