Example #1
0
        /// <summary>
        /// <see cref="M:Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.Caching.TryGet{TResult}"/>
        /// </summary>
        /// <typeparam name="TResult"><see cref="M:Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.Caching.TryGet{TResult}"/></typeparam>
        /// <param name="cacheItemConfig"><see cref="M:Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.Caching.TryGet{TResult}"/></param>
        /// <param name="result"<see cref="M:Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.Caching.TryGet{TResult}"/>></param>
        /// <returns><see cref="M:Microsoft.Samples.NLayerApp.Infrastructure.CrossCutting.Caching.TryGet{TResult}"/></returns>
        public bool TryGet <TResult>(CacheItemConfig cacheItemConfig, out TResult result)
        {
            if (cacheItemConfig != null)
            {
                //get default cache
                DataCache defaultCache = _cacheFactory.GetDefaultCache();

                string cacheKey = cacheItemConfig.CacheKey.GetCacheKey();

                //get object from cache and check if exists
                object cachedItem = defaultCache.Get(cacheKey);

                if (cachedItem != null)
                {
                    result = (TResult)cachedItem;

                    return(true);
                }
                else
                {
                    result = default(TResult);

                    return(false);
                }
            }
            else
            {
                throw new ArgumentNullException("cacheItem");
            }
        }
 internal static void AddToCache <T>(string tenant, string key, T @object) where T : class
 {
     GetRetryPolicy().ExecuteAction(() =>
     {
         DataCache cache = CacheFactory.GetDefaultCache();
         if (!cache.GetSystemRegions().Contains(tenant.ToLowerInvariant()))
         {
             cache.CreateRegion(tenant.ToLowerInvariant());
         }
         cache.Put(key.ToLowerInvariant(), @object, tenant.ToLowerInvariant());
     });
 }
Example #3
0
        public AzureCacheProvider()
        {
            //Creating a cache object by using DataCacheFactory
            DataCacheFactory cacheFactory = new DataCacheFactory();

            dataCache = cacheFactory.GetDefaultCache();
        }
Example #4
0
        public void Flush()
        {
            cache.Clear();
            DataCacheFactory cacheFactory = new DataCacheFactory();

            cache = cacheFactory.GetDefaultCache();
        }
Example #5
0
        public AzureCacheService(ILogService logger)
        {
            _logger = logger;
            var cacheFactory = new DataCacheFactory();

            _cache = cacheFactory.GetDefaultCache();
        }
        public void PuKeyValueRegionShouldUpdateCache()
        {
            var expectedOldValue = TestContext.TestName;
            var expectedNewValue = "Updated " + TestContext.TestName;
            var key = "Key" + TestContext.TestName;
            var region = "Region" + TestContext.TestName;

            var dcf = new DataCacheFactory();
            var dc = dcf.GetDefaultCache();

            // Clean up previous entries
            dc.CreateRegion(region);

            dc.Remove(key, region);
            dc.Add(key, expectedOldValue, region);

            var sut = new DataCachePut<string> {Key = key, Value = expectedNewValue, Region = region};

            // Put an item in the cache using the activity
            var itemVersion = WorkflowInvoker.Invoke(sut);

            // Get it from the cache
            var value = dc.Get(key, region) as string;

            // Assert
            Assert.IsNotNull(itemVersion);
            Assert.AreEqual(expectedNewValue, value);
        }
Example #7
0
        private void PrepareClient(bool sslEnabled)
        {
            string hostName = "[Cache endpoint without port]";      //Example : "MyCache.cache.appfabric.com";
            int    cachePort;

            cachePort = sslEnabled ? 22243 : 22233; // Default port
            List <DataCacheServerEndpoint> server = new List <DataCacheServerEndpoint>();

            server.Add(new DataCacheServerEndpoint(hostName, cachePort));
            DataCacheFactoryConfiguration config = new DataCacheFactoryConfiguration();

            // Uncomment the lines below to use the authentication token in plain text.
            //
            ////string authenticationToken = "[InsertAuthenticationTokenHere]";
            ////SecureString secureAuthenticationToken = GetSecureString(authenticationToken);

            // Load Auth token from settings
            SecureString secureAuthenticationToken = LoadAuthTokenFromSettings();

            config.SecurityProperties = new DataCacheSecurity(secureAuthenticationToken, sslEnabled);
            config.Servers            = server;

            config.LocalCacheProperties = new DataCacheLocalCacheProperties(10000, new TimeSpan(0, 5, 0), DataCacheLocalCacheInvalidationPolicy.TimeoutBased);
            DataCacheFactory myCacheFactory = new DataCacheFactory(config);

            myDefaultCache = myCacheFactory.GetDefaultCache();
        }
        public string GetCaching()
        {
            DataCacheFactory cacheFactory = new DataCacheFactory();

            DataCache cache  = cacheFactory.GetDefaultCache();
            object    result = cache.Get("Item");

            string str = " ";

            if (result == null)
            {
                // "Item" not in cache. Obtain it from specified data source
                // and add it.
                var times = TimeSpan.FromMinutes(2);
                str = "no cache..." + times.ToString();
                cache.Add("item", str, times);
            }
            else
            {
                str = (string)result;
                // "Item" is in cache, cast result to correct type.
            }

            return(str);
        }
        public void ShouldFailRemoveFromCacheItemVersionWithUpdate()
        {
            var expectedOldValue = TestContext.TestName;
            var expectedNewValue = "Updated " + TestContext.TestName;
            var key = "Key" + TestContext.TestName;
            var dcf = new DataCacheFactory();
            var dc = dcf.GetDefaultCache();

            dc.Remove(key);

            // Add the value
            var itemVersion = dc.Add(key, expectedOldValue);
            // Will update the item version
            var newItemVersion = dc.Put(key, expectedNewValue, itemVersion);

            var sut = new DataCacheRemove();

            // Using input arguments
            var input = new Dictionary<string, object>
                            {
                                {"Key", key},
                                {"ItemVersion", itemVersion},
                            };

            WorkflowInvoker.Invoke(sut, input);

            var item = dc.GetCacheItem(key);

            // Assert
            Assert.IsNotNull(item);
            Assert.AreEqual(newItemVersion, item.Version);
        }
Example #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AppFabricCachingProvider"/> class.
        /// </summary>
        /// <param name="cacheFactory">The cache factory.</param>
        /// <param name="cacheName">Name of the cache.</param>
        public AppFabricCachingProvider(DataCacheFactory cacheFactory, string cacheName = null)
        {
            CacheFactory = cacheFactory ?? throw new ArgumentNullException("cacheFactory");

            // TODO: don't know enough about AppFabric to know if we should use the GetDefaultCache() if no cache name provided, or if we should use our own name like SharpRepository
            Cache = String.IsNullOrEmpty(cacheName) ? cacheFactory.GetDefaultCache() : cacheFactory.GetCache(cacheName);
        }
        public DataCache ConstructCache(string endPointConfig)
        {
            #if NET35
            if (string.IsNullOrEmpty(endPointConfig))
                endPointConfig = DEFAULT_EndpointConfig;
            #else
            if (string.IsNullOrWhiteSpace(endPointConfig))
                endPointConfig = DEFAULT_EndpointConfig;
            #endif

            var endPoints = ParseConfig(endPointConfig);
            var dataCacheEndpoints = new List<DataCacheServerEndpoint>();
            endPoints.ForEach(e => dataCacheEndpoints.Add(new DataCacheServerEndpoint(e.IPAddressOrHostName,e.Port)));

            var config = new DataCacheFactoryConfiguration();
            config.Servers = dataCacheEndpoints;
            SetSecuritySettings(config);

            try
            {
                var factory = new DataCacheFactory(config);
                DataCacheClientLogManager.ChangeLogLevel(System.Diagnostics.TraceLevel.Error);

                // Note: When setting up AppFabric. The configured cache needs to be created by the admin using the New-Cache powershell command
                //var cache = factory.GetCache(WebConfigSettings.DistributedCacheName);
                var cache = factory.GetDefaultCache();
                return cache;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
        }
Example #12
0
        public CacheManager(string key)
        {
            DataCacheFactory slurmCacheFactory = new DataCacheFactory();

            _cache = slurmCacheFactory.GetDefaultCache();
            _key   = key;
        }
        public void Start(IDictionary <string, string> properties)
        {
            CacheClientConfiguration configuration;

            try {
                var tenantName = properties["cache.region_prefix"];

                bool   enableCompression = false;
                string enableCompressionString;
                if (properties.TryGetValue("compression_enabled", out enableCompressionString))
                {
                    enableCompression = Boolean.Parse(enableCompressionString);
                }

                var pca = new DefaultPlatformConfigurationAccessor();
                configuration = CacheClientConfiguration.FromPlatformConfiguration(tenantName, Constants.DatabaseCacheSettingNamePrefix, pca);
                configuration.CompressionIsEnabled = enableCompression;
                configuration.Validate();
            }
            catch (Exception ex) {
                throw new Exception(String.Format("The {0} configuration settings are missing or invalid.", Constants.DatabaseCacheFeatureName), ex);
            }

            _dataCacheFactory = configuration.CreateCache();
            _dataCache        = _dataCacheFactory.GetDefaultCache();
        }
Example #14
0
        internal static T GetFromCache <T>(string tenant, string key, Func <T> @default) where T : class
        {
            var result = default(T);

            using (var factory = new DataCacheFactory())
            {
                var       success = false;
                DataCache cache   = factory.GetDefaultCache();
                result = cache.Get(key.ToLowerInvariant(), tenant.ToLowerInvariant()) as T;
                if (result != null)
                {
                    success = true;
                }
                else if (@default != null)
                {
                    result = @default();
                    if (result != null)
                    {
                        AddToCache(tenant.ToLowerInvariant(), key.ToLowerInvariant(), result);
                    }
                }
                TraceHelper.TraceInformation("cache {2} for {0} [{1}]", key, tenant, success ? "hit" : "miss");
            }

            return(result);
        }
        public Location Get(int id)
        {
            Location location = null;

            // TODO: Place cache initialization here
            DataCacheFactory cacheFactory = new DataCacheFactory();
            DataCache        cache        = cacheFactory.GetDefaultCache();

            // TODO: Find the location entity in the cache
            string cacheKey = "location_" + id.ToString();

            location = cache.Get(cacheKey) as Location;

            if (location == null)
            {
                using (TravelCompanionContext context = new TravelCompanionContext())
                {
                    var locations = from l in context.Locations
                                    where l.LocationId == id
                                    select l;

                    location = locations.FirstOrDefault();

                    // TODO: Add the location to the cache
                    cache.Put(cacheKey, location);
                }
            }

            return(location);
        }
        public DataCache ConstructCache()
        {
            ParseConfig(AppFabricConstants.DEFAULT_ServerAddress, AppFabricConstants.DEFAULT_Port);
            var dataCacheEndpoints = new List <DataCacheServerEndpoint>();

            CacheConfiguration.ServerNodes.ForEach(e => dataCacheEndpoints.Add(new DataCacheServerEndpoint(e.IPAddressOrHostName, e.Port)));

            var factoryConfig = new DataCacheFactoryConfiguration();

            factoryConfig.Servers = dataCacheEndpoints;

            var configMapper = new FactoryConfigConverter(Logger);

            configMapper.MapSettingsFromConfigToAppFabricSettings(CacheConfiguration, factoryConfig);
            IsLocalCacheEnabled = configMapper.IsLocalCacheEnabled;
            //SetSecuritySettings(config, factoryConfig);

            try
            {
                Logger.WriteInfoMessage("Constructing AppFabric Cache");

                var factory = new DataCacheFactory(factoryConfig);
                DataCacheClientLogManager.ChangeLogLevel(System.Diagnostics.TraceLevel.Error);

                // Note: When setting up AppFabric. The configured cache needs to be created by the admin using the New-Cache powershell command
                string cacheName;
                // Prefer the new config mechanism over the explicit entry but still support it. So we
                // try and extract config from the ProviderSpecificValues first.
                if (CacheConfiguration.ProviderSpecificValues.ContainsKey(AppFabricConstants.CONFIG_CacheNameKey))
                {
                    cacheName = CacheConfiguration.ProviderSpecificValues[AppFabricConstants.CONFIG_CacheNameKey];
                }
                else
                {
                    cacheName = MainConfig.Default.DistributedCacheName;
                }

                Logger.WriteInfoMessage(string.Format("Appfabric Cache Name: [{0}]", cacheName));

                DataCache cache = null;
                if (string.IsNullOrWhiteSpace(cacheName))
                {
                    cache = factory.GetDefaultCache();
                }
                else
                {
                    cache = factory.GetCache(cacheName);
                }

                Logger.WriteInfoMessage("AppFabric cache constructed.");

                return(cache);
            }
            catch (Exception ex)
            {
                Logger.WriteException(ex);
                throw;
            }
        }
        public WindowsAzureCacheProvider(DataCacheFactory cacheFactory, string cacheName = null)
        {
            Guard.AgainstNullArgument(cacheFactory);

            _dataChache = String.IsNullOrEmpty(cacheName)
                                ? cacheFactory.GetDefaultCache()
                                : cacheFactory.GetCache(cacheName);
        }
 private DataCache GetDataCache(string cacheName)
 {
     if (dcf == null)
     {
         dcf = new DataCacheFactory();
     }
     return(dcf.GetCache((ProductName + "_" + cacheName).ToUpper()) ?? dcf.GetDefaultCache());
 }
Example #19
0
 internal static void RemoveFromCache(string tenant, string key)
 {
     using (var factory = new DataCacheFactory())
     {
         DataCache cache = factory.GetDefaultCache();
         cache.Remove(key.ToLowerInvariant(), tenant.ToLowerInvariant());
     }
 }
Example #20
0
 public override void Initialise()
 {
     if (_cache == null)
     {
         _factory = new DataCacheFactory();
         _cache   = _factory.GetDefaultCache();
     }
 }
Example #21
0
 public AzureCache()
 {
     if (cache == null)
     {
         DataCacheFactoryConfiguration cfg = new DataCacheFactoryConfiguration();
         cfg.AutoDiscoverProperty = new DataCacheAutoDiscoverProperty(true, "CacheWorkerRole1");
         dataCacheFactory         = new DataCacheFactory(cfg);
         cache = dataCacheFactory.GetDefaultCache();
     }
 }
Example #22
0
        private static ICache CreateAppFabricCache()
        {
            var server = new List<DataCacheServerEndpoint>();
            server.Add(new DataCacheServerEndpoint("localhost", 22233));

            var conf = new DataCacheFactoryConfiguration();
            conf.Servers = server;

            DataCacheFactory fac = new DataCacheFactory(conf);
            return new AppFabricCache(fac.GetDefaultCache());
        }
        public List <string> GetProducts()
        {
            List <string> products = null;

            DataCache dataCache = null;

            if (this.enableCache)
            {
                try
                {
                    dataCache = cacheFactory.GetDefaultCache();
                    products  = dataCache.Get("products") as List <string>;
                    if (products != null)
                    {
                        products[0] = "(from cache)";
                        return(products);
                    }
                }
                catch (DataCacheException ex)
                {
                    if (ex.ErrorCode != DataCacheErrorCode.RetryLater)
                    {
                        throw;
                    }

                    // ignore temporary failures
                }
            }

            NorthwindEntities context = new NorthwindEntities();

            try
            {
                var query = from product in context.Products
                            select product.ProductName;
                products = query.ToList();
            }
            finally
            {
                if (context != null)
                {
                    context.Dispose();
                }
            }

            products.Insert(0, "(from data source)");

            if (this.enableCache && dataCache != null)
            {
                dataCache.Add("products", products, TimeSpan.FromSeconds(30));
            }

            return(products);
        }
Example #24
0
        private static DataCache GetCache()
        {
            var cacheConfig = new DataCacheFactoryConfiguration("default") {MaxConnectionsToServer = 6};

            DataCacheFactoryConfiguration.CreateNamedConfiguration("ConfigWithConnectionPooling", cacheConfig, true);

            var configWithPooling = new DataCacheFactoryConfiguration("ConfigWithConnectionPooling");
            var factory = new DataCacheFactory(configWithPooling);

            return factory.GetDefaultCache();
        }
 public AzureCacheClient(string cacheName = null)
 {
     CacheFactory = new DataCacheFactory();
     if (string.IsNullOrEmpty(cacheName))
     {
         DataCache = CacheFactory.GetDefaultCache();
     }
     else
     {
         DataCache = CacheFactory.GetCache(cacheName);
     }
 }
Example #26
0
 internal static void AddToCache <T>(string tenant, string key, T @object) where T : class
 {
     using (var factory = new DataCacheFactory())
     {
         DataCache cache = factory.GetDefaultCache();
         if (!cache.GetSystemRegions().Contains(tenant.ToLowerInvariant()))
         {
             cache.CreateRegion(tenant.ToLowerInvariant());
         }
         cache.Put(key.ToLowerInvariant(), @object, tenant.ToLowerInvariant());
     }
 }
        public AppFabricCacheProvider()
        {
            dynamic app = new AppConfig();


            var configuration = new DataCacheFactoryConfiguration();

            DataCacheClientLogManager.ChangeLogLevel(System.Diagnostics.TraceLevel.Off);

            _factory = new DataCacheFactory(configuration);

            _cache = _factory.GetDefaultCache();
        }
Example #28
0
        private static DataCache GetCache()
        {
            if (_cache != null)
            {
                return(_cache);
            }

            // Disable tracing to avoid informational / verbose messages on the web page
            DataCacheClientLogManager.ChangeLogLevel(TraceLevel.Off);

            _factory = new DataCacheFactory();
            _cache   = _factory.GetDefaultCache();
            return(_cache);
        }
Example #29
0
        private static ICache CreateAppFabricCache()
        {
            var server = new List <DataCacheServerEndpoint>();

            server.Add(new DataCacheServerEndpoint("localhost", 22233));

            var conf = new DataCacheFactoryConfiguration();

            conf.Servers = server;

            DataCacheFactory fac = new DataCacheFactory(conf);

            return(new AppFabricCache(fac.GetDefaultCache()));
        }
Example #30
0
        private static void Init()
        {
            while (cache == null)
            {
                try
                {
                    DataCacheFactory cacheFactory = new DataCacheFactory();
                    cache = cacheFactory.GetDefaultCache();
                    Trace.WriteLine("IpLocation cache initialized.");
                }
                catch (Exception e)
                {
                    cache = null;
                    System.Threading.Thread.Sleep(2000);
                    Trace.WriteLine("Cannot initialize IpLocation cache. " + e.Message);
                }
            }

            while (maxMindDbStream == null)
            {

                //CloudBlobContainer container = new CloudBlobContainer(new Uri(Settings.GetSettings("MaxMindContainer")), AzureStorage.BlobClient.Credentials);
                CloudBlobContainer container = AzureStorage.BlobClient.GetContainerReference(Settings.GetSettings("MaxMindContainer"));
                var maxMindDbBlob = container.GetBlockBlobReference(Settings.GetSettings("MaxMindDatabase"));                                
                try
                {
                    maxMindDbStream = new MemoryStream();
                    if (RoleEnvironment.IsAvailable)
                    {
                        maxMindDbBlob.DownloadToStream(maxMindDbStream);
                        Trace.WriteLine("MaxMind DB transferred to memory.");
                    }
                    else
                    {
                        using (FileStream filestream = File.OpenRead(HttpContext.Current.Server.MapPath(Settings.GetSettings("GeoIpPath"))))
                        {
                            maxMindDbStream.SetLength(filestream.Length);
                            filestream.Read(maxMindDbStream.GetBuffer(), 0, (int)filestream.Length);
                        }
                    }
                }
                catch (Exception e)
                {
                    Trace.WriteLine("Cannot initialize MaxMind database. " + e.Message);
                    maxMindDbStream = null;
                    System.Threading.Thread.Sleep(2000);
                }
            }
        }
Example #31
0
        public CacheManager(string method, List <string> inputs)
        {
            var formattedInputs = string.Empty;

            if (inputs.Count() > 0)
            {
                formattedInputs = string.Join("-", inputs);
            }

            _key = string.Format("{0}-{1}", method, formattedInputs).ToLowerInvariant();

            DataCacheFactory slurmCacheFactory = new DataCacheFactory();

            _cache = slurmCacheFactory.GetDefaultCache();
        }
Example #32
0
        /// <summary>
        /// Gets an instance of a data cache [client].
        /// </summary>
        /// <param name="cacheName">The name of the AppFabric cache to get the data cache [client] for.</param>
        /// <param name="useDefault">A flag to determine whether or not the default cache should be used if the named cache
        /// does not exist.</param>
        /// <returns>A data cache [client].</returns>
        public DataCache GetCache(string cacheName, bool useDefault = false)
        {
            try
            {
                return(_cacheCluster.GetCache(cacheName));
            }
            catch (DataCacheException ex)
            {
                if (ex.ErrorCode == DataCacheErrorCode.NamedCacheDoesNotExist && useDefault)
                {
                    return(_cacheCluster.GetDefaultCache());
                }

                throw;
            }
        }
        public static void TryRegisterAzureCacheProvider(this Container container)
        {
#if AZURE
            try
            {
                var factory = new DataCacheFactory();
                factory.GetDefaultCache();
                container.RegisterAzureCacheProvider();
            }
            catch (Exception ex)
            {
                var config = new DotNetConfigurationManager();
                var logger = new ElmahExceptionLogger(config.DefaultMailFromAddress, config.EmergencyMailAddresses);
                logger.Log(ex);
            }
#endif
        }
Example #34
0
        public InRoleCacheStore(ICacheConfiguration configuration)
            : base(configuration)
        {
            var args = new CommandArgs(configuration.Parameters);

            if (_cacheFactory == null)
            {
                _cacheFactory = new DataCacheFactory();
            }

            _cache = args.ContainsKey("cacheName")
                ? _cacheFactory.GetCache(args.GetValue("cacheName", "default"))
                : _cacheFactory.GetDefaultCache();

            _policy            = args.GetValue("policy", CachePolicy.AlwaysLive.ToString()).ToEnum <CachePolicy>();
            _durationInMinutes = int.Parse(args.GetValue("duration", "10"));
        }
Example #35
0
        public AzureCache()
        {
            var token = new System.Security.SecureString();
            foreach (var c in AuthenticationToken.ToCharArray())
            {
                token.AppendChar(c);
            }

            var securityProperties = new DataCacheSecurity(token);

            var factory = new DataCacheFactory(new DataCacheFactoryConfiguration()
            {
                SecurityProperties = securityProperties,
                Servers = new List<DataCacheServerEndpoint> { new DataCacheServerEndpoint(CacheHost, CachePort) }
            });
            
            this._cacheClient = factory.GetDefaultCache();
        }
Example #36
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AzureCache"/> class.
        /// </summary>
        public AzureCache()
        {
            // Create a DataCacheFactoryConfiguration object
            var config           = new DataCacheFactoryConfiguration();
            var cacheEndPoint    = CloudConfigurationManager.GetSetting("CacheEndPoint");
            var cacheSecurityKey = CloudConfigurationManager.GetSetting("CacheSecurityKey");

            // Enable the AutoDiscoveryProperty
            config.AutoDiscoverProperty = new DataCacheAutoDiscoverProperty(true, cacheEndPoint);

            // Configure the access key and sslEnabled setting.
            config.SecurityProperties = new DataCacheSecurity(cacheSecurityKey, false);

            bool localCacheEnabled;

            if (!bool.TryParse(CloudConfigurationManager.GetSetting("LocalCacheEnabled"), out localCacheEnabled))
            {
                localCacheEnabled = true;
            }

            // Configure the Local Cache if its enabled
            if (localCacheEnabled)
            {
                int localCacheItemTimeout;
                int localCacheObjectCount;
                if (!int.TryParse(CloudConfigurationManager.GetSetting("LocalCacheTimeoutMinutes"), out localCacheItemTimeout))
                {
                    localCacheItemTimeout = 10;
                }
                if (!int.TryParse(CloudConfigurationManager.GetSetting("LocalCacheObjectCount"), out localCacheObjectCount))
                {
                    localCacheObjectCount = 500000;
                }

                config.LocalCacheProperties = new DataCacheLocalCacheProperties(localCacheObjectCount, TimeSpan.FromMinutes(localCacheItemTimeout), DataCacheLocalCacheInvalidationPolicy.TimeoutBased);
            }

            // Create a DataCacheFactory object with the configuration settings:
            var factory = new DataCacheFactory(config);

            var cacheName = CloudConfigurationManager.GetSetting("CacheName");

            _azureCache = string.IsNullOrEmpty(cacheName) ? factory.GetDefaultCache() : factory.GetCache(cacheName);
        }
        public void ShouldGetFromCache()
        {
            var expectedValue = TestContext.TestName;
            var key = "Key" + TestContext.TestName;
            var dcf = new DataCacheFactory();
            var dc = dcf.GetDefaultCache();

            dc.Remove(key);

            // Add the value
            dc.Add(key, expectedValue);

            var sut = new DataCacheGet<string> {Key = key};

            var value = WorkflowInvoker.Invoke(sut);

            // Assert
            Assert.AreEqual(expectedValue, value);
        }
        public DataCache CreateCache() {
            var dataCacheFactoryConfiguration = new DataCacheFactoryConfiguration {
                MaxConnectionsToServer = 32,
                UseLegacyProtocol = false,
                IsCompressionEnabled = CompressionIsEnabled
            };

            dataCacheFactoryConfiguration.AutoDiscoverProperty = new DataCacheAutoDiscoverProperty(true, HostIdentifier);
            if (!String.IsNullOrEmpty(AuthorizationToken))
                dataCacheFactoryConfiguration.SecurityProperties = new DataCacheSecurity(AuthorizationToken, sslEnabled: false);

            var dataCacheFactory = new DataCacheFactory(dataCacheFactoryConfiguration);

            if (!String.IsNullOrEmpty(CacheName)) {
                return dataCacheFactory.GetCache(CacheName);
            }

            return dataCacheFactory.GetDefaultCache();
        }
Example #39
0
        public static ISimpleCache GetCache(string keyPrefix = null, TimeSpan?duration = null)
        {
            duration = duration ?? TimeSpan.FromHours(1);
            switch (cacheType)
            {
            case CacheType.Azure:
                try
                {
                    var cache = dataCacheFactory.GetDefaultCache();
                    return(new SimpleCacheAzure(cache, keyPrefix));
                }
                catch (Exception ex)
                {
                    // If we've got one error, let's bail on trying to use Azure, and just default to the simple cache.
                    cacheType = CacheType.Simple;

                    logger.Error("Unable to instantiate Azure cache; returning simple cache. Error = " + ex);
                    return(new SimpleCache(duration.Value));
                }

            case CacheType.Redis:
                try
                {
                    return(new SimpleCacheRedis(redisCs, keyPrefix, null, duration));
                }
                catch (Exception ex)
                {
                    // If we've got one error, let's bail on trying to use Azure, and just default to the simple cache.
                    cacheType = CacheType.Simple;

                    logger.Error("Unable to instantiate Redis cache; returning simple cache. Error = " + ex);
                    return(new SimpleCache(duration.Value));
                }

            case CacheType.PassThrough:
                return(new SimpleCachePassThroughProd());
            }

            // Return a short timespan because this will almost always just be used in testing
            return(new SimpleCache(TimeSpan.FromMinutes(5)));
        }
        protected void buscarDoCache_Click(object sender, EventArgs e)
        {
            try
            {
                var itens = new List<Tuple<string, string, string>>();

                using (DataCacheFactory dataCacheFactory = new DataCacheFactory())
                {
                    DataCache dataCache = dataCacheFactory.GetDefaultCache();

                    itens = dataCache.Get("itens") as List<Tuple<string, string, string>>;
                }

                this.GridView1.DataSource = itens;
                this.GridView1.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message + " <br> " + " <br> " + ex.InnerException.Message + ex.StackTrace);
            }
        }
Example #41
0
        public DataCache ConstructCache(string endPointConfig)
        {
#if NET35
            if (string.IsNullOrEmpty(endPointConfig))
            {
                endPointConfig = DEFAULT_EndpointConfig;
            }
#else
            if (string.IsNullOrWhiteSpace(endPointConfig))
            {
                endPointConfig = DEFAULT_EndpointConfig;
            }
#endif

            var endPoints          = ParseConfig(endPointConfig);
            var dataCacheEndpoints = new List <DataCacheServerEndpoint>();
            endPoints.ForEach(e => dataCacheEndpoints.Add(new DataCacheServerEndpoint(e.IPAddressOrHostName, e.Port)));

            var config = new DataCacheFactoryConfiguration();
            config.Servers = dataCacheEndpoints;
            SetSecuritySettings(config);


            try
            {
                var factory = new DataCacheFactory(config);
                DataCacheClientLogManager.ChangeLogLevel(System.Diagnostics.TraceLevel.Error);

                // Note: When setting up AppFabric. The configured cache needs to be created by the admin using the New-Cache powershell command
                //var cache = factory.GetCache(WebConfigSettings.DistributedCacheName);
                var cache = factory.GetDefaultCache();
                return(cache);
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
        }
Example #42
0
        public void Start(IDictionary<string, string> properties) {
            CacheClientConfiguration configuration;

            try {
                var tenantName = properties["cache.region_prefix"];

                bool enableCompression = false;
                string enableCompressionString;
                if (properties.TryGetValue("compression_enabled", out enableCompressionString))
                    enableCompression = Boolean.Parse(enableCompressionString);

                var pca = new DefaultPlatformConfigurationAccessor();
                configuration = CacheClientConfiguration.FromPlatformConfiguration(tenantName, Constants.DatabaseCacheSettingNamePrefix, pca);
                configuration.CompressionIsEnabled = enableCompression;
                configuration.Validate();
            }
            catch (Exception ex) {
                throw new Exception(String.Format("The {0} configuration settings are missing or invalid.", Constants.DatabaseCacheFeatureName), ex);
            }

            _dataCacheFactory = configuration.CreateCache();
            _dataCache = _dataCacheFactory.GetDefaultCache();
        }
        protected void colocarNoCache_Click(object sender, EventArgs e)
        {
            try
            {
                var itens = new List<Tuple<string, string, string>>();

                using (DataCacheFactory dataCacheFactory = new DataCacheFactory())
                {
                    DataCache dataCache = dataCacheFactory.GetDefaultCache();

                    for (int i = 0; i < 300; i++)
                    {
                        itens.Add(new Tuple<string, string, string>("item " + i + 1, "item " + i + 1, "item " + i + 1));
                    }

                    dataCache.Put("itens", itens);
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message + " <br> " + " <br> " + ex.InnerException.Message + ex.StackTrace);
            }
        }
        public void ShouldFailRemoveFromCacheLockHandleWithUpdate()
        {
            var expectedOldValue = TestContext.TestName;
            var expectedNewValue = "Updated " + TestContext.TestName;
            var key = "Key" + TestContext.TestName;
            var dcf = new DataCacheFactory();
            var dc = dcf.GetDefaultCache();

            dc.Remove(key);

            // Add the value
            var itemVersion = dc.Add(key, expectedOldValue);
            // Will update the item version
            var newItemVersion = dc.Put(key, expectedNewValue, itemVersion);

            DataCacheLockHandle lockHandle;
            dc.GetAndLock(key, TimeSpan.FromMinutes(5), out lockHandle);

            var sut = new DataCacheRemove();

            // Using input arguments
            var input = new Dictionary<string, object>
                            {
                                {"Key", key},
                                {"LockHandle", lockHandle},
                            };

            WorkflowInvoker.Invoke(sut, input);

            var item = dc.GetCacheItem(key);

            // Assert

            // Version does not matter when removing with a lock handle
            Assert.IsNull(item);
        }
 public AzureCache()
 {
     DataCacheFactory factory = new DataCacheFactory();
     cache = factory.GetDefaultCache();
 }
        public void ShouldRemoveFromCacheRegion()
        {
            var expectedValue = TestContext.TestName;
            var key = "Key" + TestContext.TestName;
            var region = "Region" + TestContext.TestName;
            var dcf = new DataCacheFactory();
            var dc = dcf.GetDefaultCache();

            dc.CreateRegion(region);
            dc.Remove(key, region);

            // Add the value
            dc.Add(key, expectedValue, region);

            var sut = new DataCacheRemove {Key = key, Region = region};

            WorkflowInvoker.Invoke(sut);

            var value = dc.Get(key, region);

            // Assert
            Assert.IsNull(value);
        }
        public void PutKeyValueRegionTagsTimeoutShouldUpdateCache()
        {
            const int expectedCount = 1;
            var expectedOldValue = TestContext.TestName;
            var expectedNewValue = "Updated " + TestContext.TestName;
            var expectedOldTimeout = TimeSpan.FromMinutes(20);
            var expectedNewTimeout = TimeSpan.FromMinutes(30);

            var key = "Key" + TestContext.TestName;
            var region = "Region" + TestContext.TestName;
            var tags = new List<DataCacheTag>
                           {
                               new DataCacheTag("tag1" + TestContext.TestName),
                               new DataCacheTag("tag2" + TestContext.TestName),
                               new DataCacheTag("tag3" + TestContext.TestName)
                           };
            var dcf = new DataCacheFactory();
            var dc = dcf.GetDefaultCache();

            // Clean up previous entries
            dc.CreateRegion(region);
            dc.Remove(key, region);

            dc.Add(key, expectedOldValue, expectedOldTimeout, region);

            var sut = new DataCachePut<string>();
            // To use Object Initialization syntax you would do the following
            // { Key = key, Value = expectedValue, Region = region, Tags = new LambdaValue<IEnumerable<DataCacheTag>>((env) =>tags)};

            // Using input arguments
            var input = new Dictionary<string, object>
                            {
                                {"Key", key},
                                {"Value", expectedNewValue},
                                {"Region", region},
                                {"Tags", tags},
                                {"Timeout", expectedNewTimeout}
                            };

            // Put an item in the cache using the activity
            var itemVersion = WorkflowInvoker.Invoke(sut, input);

            // Get it from the cache
            var values = dc.GetObjectsByAllTags(tags, region);
            var item = dc.GetCacheItem(key, region);

            // Assert
            Assert.IsNotNull(itemVersion);
            Assert.AreEqual(expectedCount, values.Count());
            Assert.AreEqual(expectedNewValue, item.Value);

            // The timeout counts down so it should be greater than the old timeout
            Assert.IsTrue(item.Timeout > expectedOldTimeout);
        }
        public void ShouldRemoveFromCacheItemVersion()
        {
            var expectedValue = TestContext.TestName;
            var key = "Key" + TestContext.TestName;
            var dcf = new DataCacheFactory();
            var dc = dcf.GetDefaultCache();

            dc.Remove(key);

            // Add the value
            var itemVersion = dc.Add(key, expectedValue);

            var sut = new DataCacheRemove();

            // Using input arguments
            var input = new Dictionary<string, object>
                            {
                                {"Key", key},
                                {"ItemVersion", itemVersion},
                            };

            WorkflowInvoker.Invoke(sut, input);

            var value = dc.Get(key);

            // Assert
            Assert.IsNull(value);
        }
        public void ShouldRemoveFromCacheLockHandleRegion()
        {
            var expectedValue = TestContext.TestName;
            var key = "Key" + TestContext.TestName;
            var region = "Region" + TestContext.TestName;
            var dcf = new DataCacheFactory();
            var dc = dcf.GetDefaultCache();

            dc.CreateRegion(region);
            dc.Remove(key, region);

            // Add the value
            var itemVersion = dc.Add(key, expectedValue, region);
            DataCacheLockHandle lockHandle;
            dc.GetAndLock(key, TimeSpan.FromMinutes(5), out lockHandle, region);

            var sut = new DataCacheRemove();

            // Using input arguments
            var input = new Dictionary<string, object>
                            {
                                {"Key", key},
                                {"Region", region},
                                {"LockHandle", lockHandle},
                            };

            WorkflowInvoker.Invoke(sut, input);

            var value = dc.Get(key, region);

            // Assert
            Assert.IsNull(value);
        }
 public FabricCacheOperationInvoker(IOperationInvoker operationInvoker, DataCacheFactory dataCacheFactory)
 {
     this.operationInvoker = operationInvoker;
     this.datacache = dataCacheFactory.GetDefaultCache();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ServerAppFabricServiceCache"/> class.
 /// </summary>
 /// <param name="cacheFactory">The cache factory.</param>
 public ServerAppFabricServiceCache(DataCacheFactory cacheFactory)
     : this(cacheFactory.GetDefaultCache())
 {
     CacheFactory = cacheFactory;
 }
Example #52
0
        private static DataCache GetCache()
        {
            if (_cache != null) return _cache;

            // Disable tracing to avoid informational / verbose messages on the web page
            DataCacheClientLogManager.ChangeLogLevel(TraceLevel.Off);

            _factory = new DataCacheFactory();
            _cache = _factory.GetDefaultCache();

            return _cache;
        }
        public void AddKeyValueShouldAddToCache()
        {
            var expectedValue = TestContext.TestName;
            var key = "Key" + TestContext.TestName;
            var dcf = new DataCacheFactory();
            var dc = dcf.GetDefaultCache();

            dc.Remove(key);

            var sut = new DataCacheAdd<string> {Key = key, Value = expectedValue};

            // Put an item in the cache using the activity
            var itemVersion = WorkflowInvoker.Invoke(sut);

            // Get it from the cache
            var value = dc.Get(key) as string;

            // Assert
            Assert.IsNotNull(itemVersion);
            Assert.AreEqual(expectedValue, value);
        }
        public void AddKeyValueRegionTagsShouldAddToCache()
        {
            const int expectedCount = 1;
            var expectedValue = TestContext.TestName;
            var key = "Key" + TestContext.TestName;
            var region = "Region" + TestContext.TestName;
            var tags = new List<DataCacheTag>
                           {
                               new DataCacheTag("tag1" + TestContext.TestName),
                               new DataCacheTag("tag2" + TestContext.TestName),
                               new DataCacheTag("tag3" + TestContext.TestName)
                           };
            var dcf = new DataCacheFactory();
            var dc = dcf.GetDefaultCache();

            // Clean up previous entries
            dc.CreateRegion(region);
            dc.Remove(key, region);

            var sut = new DataCacheAdd<string>();
            // To use Object Initialization syntax you would do the following
            // { Key = key, Value = expectedValue, Region = region, Tags = new LambdaValue<IEnumerable<DataCacheTag>>((env) =>tags)};

            // Using input arguments
            var input = new Dictionary<string, object>
                            {
                                {"Key", key},
                                {"Value", expectedValue},
                                {"Region", region},
                                {"Tags", tags},
                            };

            // Put an item in the cache using the activity
            var itemVersion = WorkflowInvoker.Invoke(sut, input);

            // Get it from the cache
            var values = dc.GetObjectsByAllTags(tags, region);

            // Assert
            Assert.IsNotNull(itemVersion);
            Assert.AreEqual(expectedCount, values.Count());
            Assert.AreEqual(expectedValue, values.First().Value);
        }
 public AzureCacheProvider()
 {
     //Creating a cache object by using DataCacheFactory
     DataCacheFactory cacheFactory = new DataCacheFactory();
      dataCache = cacheFactory.GetDefaultCache();
 }
Example #56
0
        public DataCache InstanceDataCache()
        {
            cacheFactory = InstanceDataFactory();
            cacheNegocio = cacheFactory.GetDefaultCache();

            return cacheNegocio;
        }
Example #57
0
 private DataCacheSingleton()
 {
     _CacheFactory = new DataCacheFactory();
     _Cache = _CacheFactory.GetDefaultCache();
 }
        private void InitializeCache()
        {
            String cacheNamespace = RoleEnvironment.GetConfigurationSettingValue("Namespace");
            String cacheHost = String.Format("{0}.cache.windows.net", cacheNamespace);
            Boolean SslEnabled = true;
            Int32 cachePort = SslEnabled ? 22243 : 22233;
            Int32 sizeLocalCache = 100;

            DataCacheLocalCacheProperties localCacheProperties = new DataCacheLocalCacheProperties(
                sizeLocalCache, TimeSpan.FromSeconds(60), DataCacheLocalCacheInvalidationPolicy.TimeoutBased);

            List<DataCacheServerEndpoint> servers = new List<DataCacheServerEndpoint>();
            servers.Add(new DataCacheServerEndpoint(cacheHost, cachePort));

            DataCacheTransportProperties dataCacheTransportProperties = new DataCacheTransportProperties() { MaxBufferSize = 10000, ReceiveTimeout = TimeSpan.FromSeconds(45) };

            DataCacheFactoryConfiguration cacheFactoryConfiguration = new DataCacheFactoryConfiguration()
            {
                LocalCacheProperties = localCacheProperties,
                SecurityProperties = GetSecurityToken(SslEnabled),
                Servers = servers,
                TransportProperties = dataCacheTransportProperties
            };

            DataCacheFactory dataCacheFactory = new DataCacheFactory(cacheFactoryConfiguration);
            dataCache = dataCacheFactory.GetDefaultCache();
        }