public AzureCacheClient(string cacheName = null, string endpointUrl = null, string authorizationToken = null, bool useLocalCache = true)
        {
            if (!String.IsNullOrEmpty(endpointUrl) && !String.IsNullOrEmpty(authorizationToken))
            {
                var config = new DataCacheFactoryConfiguration {
                    AutoDiscoverProperty = new DataCacheAutoDiscoverProperty(true, endpointUrl),
                    SecurityProperties   = new DataCacheSecurity(authorizationToken, false)
                };
                if (useLocalCache)
                {
                    config.LocalCacheProperties = new DataCacheLocalCacheProperties(10000, TimeSpan.FromMinutes(5), DataCacheLocalCacheInvalidationPolicy.TimeoutBased);
                }
                CacheFactory = new DataCacheFactory(config);
            }
            else
            {
                CacheFactory = new DataCacheFactory();
            }

            if (string.IsNullOrEmpty(cacheName))
            {
                DataCache = CacheFactory.GetDefaultCache();
            }
            else
            {
                DataCache = CacheFactory.GetCache(cacheName);
            }
        }
Example #2
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);
        }
Example #3
0
        private static void PrepareClient()
        {
            myCacheFactory = new DataCacheFactory();
            var cacheName = ConfigurationManager.AppSettings["CacheId"];

            myDefaultCache = myCacheFactory.GetCache(cacheName);
        }
        public ProductsRepository(bool enableCache, bool enableLocalCache)
        {
            this.enableCache = enableCache;
            this.enableLocalCache = enableLocalCache;

            if (enableCache)
            {
                if (enableLocalCache && (factoryConfig == null || !factoryConfig.LocalCacheProperties.IsEnabled))
                {
                    TimeSpan localTimeout = new TimeSpan(0, 0, 30);
                    DataCacheLocalCacheProperties localCacheConfig = new DataCacheLocalCacheProperties(10000, localTimeout, DataCacheLocalCacheInvalidationPolicy.TimeoutBased);
                    factoryConfig = new DataCacheFactoryConfiguration();

                    factoryConfig.LocalCacheProperties = localCacheConfig;
                    cacheFactory = new DataCacheFactory(factoryConfig);
                }
                else if (!enableLocalCache && (factoryConfig == null || factoryConfig.LocalCacheProperties.IsEnabled))
                {
                    cacheFactory = null;
                }
            }

            if (cacheFactory == null)
            {
                factoryConfig = new DataCacheFactoryConfiguration();
                cacheFactory = new DataCacheFactory(factoryConfig);
            }
        } 
Example #5
0
        private static DataCache GetCache()
        {
            if (dataCache != null)
            {
                return(dataCache);
            }

            Console.WriteLine(APPFABRIC_SERVER_HOSTNAME);
            Console.WriteLine(APPFABRIC_SERVER_PORT);

            var servers = new List <DataCacheServerEndpoint>(1)
            {
                new DataCacheServerEndpoint(APPFABRIC_SERVER_HOSTNAME, APPFABRIC_SERVER_PORT)
            };

            var configuration = new DataCacheFactoryConfiguration
            {
                Servers = servers,
                LocalCacheProperties = new DataCacheLocalCacheProperties()
            };

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

            dataCacheFactory = new DataCacheFactory(configuration);
            dataCache        = dataCacheFactory.GetCache(APPFABRIC_CACHENAME);

            return(dataCache);
        }
Example #6
0
        public CacheManager(string key)
        {
            DataCacheFactory slurmCacheFactory = new DataCacheFactory();

            _cache = slurmCacheFactory.GetDefaultCache();
            _key   = key;
        }
Example #7
0
        public static DataCache GetCache()
        {
            if (_cache != null)
            {
                return(_cache);
            }

            if (string.IsNullOrEmpty(HostName))
            {
                HostName = "adevweb019";
            }

            CachePort = 22233;
            CacheName = "default";

            List <DataCacheServerEndpoint> servers = new List <DataCacheServerEndpoint>(1);

            servers.Add(new DataCacheServerEndpoint(HostName, CachePort));

            Configuration = new DataCacheFactoryConfiguration();

            Configuration.SecurityProperties = CacheSecurity;

            Configuration.Servers = servers;

            Configuration.LocalCacheProperties = new DataCacheLocalCacheProperties();

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

            _factory = new DataCacheFactory(Configuration);

            _cache = _factory.GetCache(CacheName);

            return(_cache);
        }
Example #8
0
        /// <summary>
        /// Do not use this constructor. Use MdCache.Instance instead.
        /// </summary>
        public AzureMdCache(MdCacheConfig config)
        {
            Validate.NotNull(config, "config");

            _config = config;

            DataCacheFactoryConfiguration factoryConfig = new DataCacheFactoryConfiguration()
            {
                SerializationProperties = new DataCacheSerializationProperties(
                    DataCacheObjectSerializerType.CustomSerializer,
                    new AzureMdCacheSerializer()
                    ),
                IsCompressionEnabled = true,
                AutoDiscoverProperty = new DataCacheAutoDiscoverProperty(true, config.Identifier)
            };

            if (!string.IsNullOrEmpty(config.AuthorizationToken))
            {
                factoryConfig.SecurityProperties = new DataCacheSecurity(config.AuthorizationToken);
            }

            DataCacheFactory factory = new DataCacheFactory(factoryConfig);

            _dataCache = factory.GetCache(config.CacheName);
        }
Example #9
0
        public ProductsRepository(bool enableCache, bool enableLocalCache)
        {
            this.enableCache      = enableCache;
            this.enableLocalCache = enableLocalCache;

            if (enableCache)
            {
                if (enableLocalCache && (factoryConfig == null || !factoryConfig.LocalCacheProperties.IsEnabled))
                {
                    TimeSpan localTimeout = new TimeSpan(0, 0, 30);
                    DataCacheLocalCacheProperties localCacheConfig = new DataCacheLocalCacheProperties(10000, localTimeout, DataCacheLocalCacheInvalidationPolicy.TimeoutBased);
                    factoryConfig = new DataCacheFactoryConfiguration();

                    factoryConfig.LocalCacheProperties = localCacheConfig;
                    cacheFactory = new DataCacheFactory(factoryConfig);
                }
                else if (!enableLocalCache && (factoryConfig == null || factoryConfig.LocalCacheProperties.IsEnabled))
                {
                    cacheFactory = null;
                }
            }

            if (cacheFactory == null)
            {
                factoryConfig = new DataCacheFactoryConfiguration();
                cacheFactory  = new DataCacheFactory(factoryConfig);
            }
        }
Example #10
0
        public OutOfProcessMemoryCache()
        {
            var configuration = new DataCacheFactoryConfiguration();
            var factory       = new DataCacheFactory(configuration);

            cache = factory.GetCache(CacheName);
        }
Example #11
0
        static CacheFactory()
        {
            if (dataCacheFactory != null)
            {
                return;
            }

            redisCs = CloudConfigurationManager.GetSetting("redisCacheConnectionString");
            var cacheSystem = (CloudConfigurationManager.GetSetting("cacheSystem") ?? "").ToLowerInvariant();
            var cacheName   = CloudConfigurationManager.GetSetting("azureCacheName");

            if (cacheSystem == "azure")
            {
                cacheType = CacheType.Azure;
                var config = new DataCacheFactoryConfiguration(cacheName);

                // Default is 15 seconds - see http://msdn.microsoft.com/en-us/library/ee790816(v=azure.10).aspx
                config.RequestTimeout = TimeSpan.FromSeconds(10);

                dataCacheFactory = new DataCacheFactory(config);
            }
            else if (cacheSystem == "redis")
            {
                cacheType = CacheType.Redis;
            }
            else if (cacheSystem == "passthrough")
            {
                cacheType = CacheType.PassThrough;
            }
            else
            {
                cacheType = CacheType.Simple;
            }
        }
        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 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 #14
0
        public AzureCacheProvider()
        {
            //Creating a cache object by using DataCacheFactory
            DataCacheFactory cacheFactory = new DataCacheFactory();

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

            cache = cacheFactory.GetDefaultCache();
        }
        //
        // GET: /Cache/
        public ActionResult Index()
        {
            DataCacheFactoryConfiguration factoryConfig = new DataCacheFactoryConfiguration();

            DataCacheServerEndpoint[] servers = new DataCacheServerEndpoint[1] {
                new DataCacheServerEndpoint(factoryConfig.Servers.First().HostName, 22233) };

            factoryConfig.Servers = servers;

            DataCacheFactory mycacheFactory = new DataCacheFactory(factoryConfig);

            DataCache cache = mycacheFactory.GetCache("default");

            var list = new List<CacheEntryViewModel>();

            if (cache.Get("Time") == null)
            {
                cache.Put("Time", DateTime.Now);
            }

            list.Add(new CacheEntryViewModel()
            {
                Key= "Time",
                Value = ((DateTime)cache.Get("Time")).ToLongTimeString()
            });

            return View(list);
        }
Example #17
0
        public static DataCache GetCache()
        {
            if (_cache != null)
            {
                return _cache;
            }

            //Define Array for 1 Cache Host
            var servers = new List<DataCacheServerEndpoint>(1);

            //Specify Cache Host Details
            //  Parameter 1 = host name
            //  Parameter 2 = cache port number
            servers.Add(new DataCacheServerEndpoint("DevMongoDB2", 22233));

            //Create cache configuration
            var configuration = new DataCacheFactoryConfiguration
                {
                    Servers = servers,
                    LocalCacheProperties = new DataCacheLocalCacheProperties()
                };

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

            //Pass configuration settings to cacheFactory constructor

            //_factory = new DataCacheFactory(configuration);
            _factory = new DataCacheFactory(configuration: configuration);

            //Get reference to named cache called "default"
            _cache = _factory.GetCache("default");

            return _cache;
        }
Example #18
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);
        }
Example #19
0
        public static DataCache GetCache()
        {
            if (_cache != null)
                return _cache;

            //Define Array for 1 Cache Host
            List<DataCacheServerEndpoint> servers = new List<DataCacheServerEndpoint>(1);

            //Specify Cache Host Details
            //  Parameter 1 = host name
            //  Parameter 2 = cache port number
            servers.Add(new DataCacheServerEndpoint("192.168.1.31", 22233));

            //Create cache configuration
            DataCacheFactoryConfiguration configuration = new DataCacheFactoryConfiguration();

            //Set the cache host(s)
            configuration.Servers = servers;

            //Set default properties for local cache (local cache disabled)
            configuration.LocalCacheProperties = new DataCacheLocalCacheProperties();

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

            //Pass configuration settings to cacheFactory constructor
            _factory = new DataCacheFactory(configuration);

            //Get reference to named cache called "default"
            _cache = _factory.GetCache("default");

            return _cache;
        }
        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;
            }
        }
        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 #22
0
        private DataCache GetDataCache(string name)
        {
            DataCache cache = null;

            HandleBadDataCacheBug(() =>
            {
                var factorySecurity = new DataCacheSecurity(EnvironmentUtils.GetConfigSettingStr("AzureCache_Token"));

                var factoryConfig = new DataCacheFactoryConfiguration();
                factoryConfig.SecurityProperties   = factorySecurity;
                factoryConfig.AutoDiscoverProperty = new DataCacheAutoDiscoverProperty(true,
                                                                                       EnvironmentUtils.GetConfigSettingStr(
                                                                                           "AzureCache_Endpoint"));

                factoryConfig.UseLegacyProtocol      = false;
                factoryConfig.MaxConnectionsToServer = 1;
                factoryConfig.ChannelOpenTimeout     = TimeSpan.FromSeconds(3);
                factoryConfig.RequestTimeout         = TimeSpan.FromSeconds(3);

                factoryConfig.IsCompressionEnabled = true;

                var dataCacheFactory = new DataCacheFactory(factoryConfig);

                cache = dataCacheFactory.GetCache(name);
            });

            return(cache);
        }
Example #23
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 #25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ReliableCloudCacheStorage"/> class using the specified storage account information, custom retry policy
        /// and custom implementation of <see cref="ICloudStorageEntitySerializer"/> interface.
        /// </summary>
        /// <param name="endpointInfo">The endpoint details for Windows Azure Caching Service.</param>
        /// <param name="retryPolicy">The custom retry policy that will ensure reliable access to the Caching Service.</param>
        /// <param name="dataSerializer">An instance of the component which performs custom serialization and deserialization of cache items.</param>
        public ReliableCloudCacheStorage(CachingServiceEndpointInfo endpointInfo, RetryPolicy retryPolicy, ICloudStorageEntitySerializer dataSerializer)
        {
            Guard.ArgumentNotNull(endpointInfo, "endpointInfo");
            Guard.ArgumentNotNull(retryPolicy, "retryPolicy");
            Guard.ArgumentNotNull(dataSerializer, "dataSerializer");

            this.retryPolicy    = retryPolicy;
            this.dataSerializer = dataSerializer;

            var cacheServers = new List <DataCacheServerEndpoint>(1);

            cacheServers.Add(new DataCacheServerEndpoint(endpointInfo.ServiceHostName, endpointInfo.CachePort));

            var cacheConfig = new DataCacheFactoryConfiguration()
            {
                Servers = cacheServers,
                MaxConnectionsToServer = 1,
                IsCompressionEnabled   = false,
                SecurityProperties     = new DataCacheSecurity(endpointInfo.SecureAuthenticationToken, endpointInfo.SslEnabled),
                // As per recommendations in http://blogs.msdn.com/b/akshar/archive/2011/05/01/azure-appfabric-caching-errorcode-lt-errca0017-gt-substatus-lt-es0006-gt-what-to-do.aspx
                TransportProperties = new DataCacheTransportProperties()
                {
                    ReceiveTimeout = TimeSpan.FromSeconds(45)
                }
            };

            this.cacheFactory = new DataCacheFactory(cacheConfig);
            this.cache        = this.retryPolicy.ExecuteAction <DataCache>(() =>
            {
                return(this.cacheFactory.GetDefaultCache());
            });
        }
Example #26
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();
        }
Example #27
0
        public static DataCache GetCache()
        {
            if (_cache != null)
            {
                return(_cache);
            }

            //Define Array for 1 Cache Host
            List <DataCacheServerEndpoint> servers = new List <DataCacheServerEndpoint>(1);

            //Specify Cache Host Details
            //  Parameter 1 = host name
            //  Parameter 2 = cache port number
            servers.Add(new DataCacheServerEndpoint("192.168.1.31", 22233));

            //Create cache configuration
            DataCacheFactoryConfiguration configuration = new DataCacheFactoryConfiguration();

            //Set the cache host(s)
            configuration.Servers = servers;

            //Set default properties for local cache (local cache disabled)
            configuration.LocalCacheProperties = new DataCacheLocalCacheProperties();

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

            //Pass configuration settings to cacheFactory constructor
            _factory = new DataCacheFactory(configuration);

            //Get reference to named cache called "default"
            _cache = _factory.GetCache("default");

            return(_cache);
        }
        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);
        }
        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                string cacheName = ConfigurationManager.AppSettings["CacheName"] ?? "default";
                string region = ConfigurationManager.AppSettings["LogRegion"];
                DataCacheFactoryConfiguration config = new DataCacheFactoryConfiguration();
                DataCacheFactory factory = new DataCacheFactory();
                DataCache cache = factory.GetCache(cacheName);
                List<KeyValuePair<string, object>> objects = cache.GetObjectsInRegion(region).ToList();

                logEntries = new List<KeyValuePair<long, string>>();
                for (int i = 0; i < objects.Count; i++)
                {
                    long key;
                    if (long.TryParse(objects[i].Key, out key))
                    {
                        logEntries.Add(new KeyValuePair<long, string>(key, objects[i].Value.ToString()));
                    }
                }
                logEntries.Sort((a, b) => a.Key.CompareTo(b.Key));
                Grid.ItemsSource = logEntries;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error getting objects from cache: " + ex.Message);
            }
        }
        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;
            }
        }
Example #31
0
        public DataNavigate2(DataReaderFactory factory, String code, double time)
        {
            DataCacheFactory  cacheFactory   = new DataCacheFactory(factory);
            IDataCache_Code   cache          = cacheFactory.CreateCache_Code(code);
            ITradingDayReader openDateReader = cache.GetOpenDateReader();

            Init(factory, code, time, openDateReader.FirstOpenDate, openDateReader.LastOpenDate);
        }
Example #32
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 #33
0
        public void RegisterCache()
        {
            var factory   = new DataCacheFactory();
            var dataCache = factory.GetCache(configuredCacheName);

            container.RegisterInstance(configuredCacheName, dataCache);
            container.RegisterAbsoluteCacheItemPolicyFactory(configuredCacheName);
        }
Example #34
0
    public DataCacheHelper()
    {
        DataCacheFactory factory = new DataCacheFactory();

        HttpContext.Current.Application.Lock();
        HttpContext.Current.Application["dcf"] = factory;
        HttpContext.Current.Application.Unock();
    }
        public WindowsAzureCacheProvider(DataCacheFactory cacheFactory, string cacheName = null)
        {
            Guard.AgainstNullArgument(cacheFactory);

            _dataChache = String.IsNullOrEmpty(cacheName)
                                ? cacheFactory.GetDefaultCache()
                                : cacheFactory.GetCache(cacheName);
        }
Example #36
0
        public AppFabricCache(string name)
        {
            Guard.ArgumentNotNullOrEmpty(name, "name");
            _name = name;

            _dataCacheFactory = new DataCacheFactory();
            _cache            = _dataCacheFactory.GetCache(name);
        }
Example #37
0
 public override void Initialise()
 {
     if (_cache == null)
     {
         _factory = new DataCacheFactory();
         _cache   = _factory.GetDefaultCache();
     }
 }
 private DataCache GetDataCache(string cacheName)
 {
     if (dcf == null)
     {
         dcf = new DataCacheFactory();
     }
     return(dcf.GetCache((ProductName + "_" + cacheName).ToUpper()) ?? dcf.GetDefaultCache());
 }
        private static DataCache GetCache()
        {
            if (_cache != null) return _cache;

            var configuration = new DataCacheFactoryConfiguration();
            _factory = new DataCacheFactory(configuration);
            _cache = _factory.GetCache("default");

            return _cache;
        }
Example #40
0
 protected override void InitialiseInternal()
 {
     if (_cache == null)
     {
         var cacheName = CacheConfiguration.Current.DefaultCacheName.Replace(".", "-");
         Log.Debug("AppFabricCache.Initialise - initialising with cache name: {0}", cacheName);
         _factory = new DataCacheFactory();
         _cache = _factory.GetCache(cacheName);
     }
 }
Example #41
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();
        }
Example #42
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 #43
0
        public CloudCacheService(IConfiguration configuration)
        {
            DataCacheFactoryConfiguration cacheConfig = new DataCacheFactoryConfiguration();
            cacheConfig.Servers = new[] {
                new DataCacheServerEndpoint(configuration.AzureCacheEndpoint, 22233)
            };
            SecureString key = configuration.AzureCacheKey.ToSecureString();
            DataCacheSecurity security = new DataCacheSecurity(key);
            cacheConfig.SecurityProperties = security;

            _cacheFactory = new DataCacheFactory(cacheConfig);
        }
        public static void TestSetUp()
        {
            var config = new DataCacheFactoryConfiguration
            {
                Servers = new List<DataCacheServerEndpoint>
                {
                    new DataCacheServerEndpoint("C012A4700", 22233)
                }
            };
            var factory = new DataCacheFactory(config);

            cache = factory.GetCache(CacheName);
        }
Example #45
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);
                }
            }
        }
        static VelocityCacheResolver()
        {
            _Factory = new DataCacheFactory();
            _Cache = _Factory.GetCache(ConstantHelper.VelocityCacheName);

            try
            {
                _Cache.CreateRegion(REGION_NAME, false);
            }
            catch
            {
                // if the region already exists, this will throw an exception.
                // Velocity has no API to check if a region exists or not.
            }
        }
 public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
 {
     var server = new List<DataCacheServerEndpoint>();
     server.Add(new DataCacheServerEndpoint("localhost", 22233));
     var conf = new DataCacheFactoryConfiguration();
     conf.Servers = server;
     DataCacheFactory dataCacheFactory = new DataCacheFactory(conf);
     foreach (OperationDescription operation in endpoint.Contract.Operations)
     {
         if (operation.Behaviors.Contains(typeof(FabricCacheOperationInvokerOperationBehavior)))
         {
             continue;
         }
         operation.Behaviors.Add(new FabricCacheOperationInvokerOperationBehavior(dataCacheFactory));
     }
 }
 public static AppFabricCacheProvider GetInstance()
 {
     lock (locker)
     {
         if (instance == null)
         {
             var configuration = new DataCacheFactoryConfiguration();
             instance = new AppFabricCacheProvider();
             configuration.SecurityProperties = new DataCacheSecurity(DataCacheSecurityMode.None, DataCacheProtectionLevel.None);
             DataCacheFactory factory = new DataCacheFactory(configuration);
             string cacheName = ConfigurationSettings.AppSettings["CacheName"];
             cache = factory.GetCache(cacheName);
         }
     }
     return instance;
 }
Example #49
0
        public DataCache GetCache()
        {
            if (_cache != null)
                return _cache;

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

            //Pass configuration settings to cacheFactory constructor
            _factory = new DataCacheFactory();

            //Get reference to named cache called "default"
            _cache = _factory.GetCache("default");

            return _cache;
        }
        public void Initialize()
        {
            var hostName = ConfigurationManager.AppSettings["CacheHost"] ?? "localhost";
            var cachePort = string.IsNullOrEmpty(ConfigurationManager.AppSettings["CachePort"]) ? 22233 : int.Parse(ConfigurationManager.AppSettings["CachePort"]);
            var cacheName = ConfigurationManager.AppSettings["CacheName"] ?? "default";

            List<DataCacheServerEndpoint> servers = new List<DataCacheServerEndpoint>(1);
            servers.Add(new DataCacheServerEndpoint(hostName, cachePort));
            DataCacheFactoryConfiguration configuration = new DataCacheFactoryConfiguration();
            configuration.TransportProperties.MaxBufferSize = Int32.MaxValue;
            configuration.TransportProperties.MaxBufferPoolSize = Int32.MaxValue;
            configuration.Servers = servers;
            configuration.LocalCacheProperties = new DataCacheLocalCacheProperties(10000, new TimeSpan(0, 5, 0), DataCacheLocalCacheInvalidationPolicy.TimeoutBased);
            DataCacheClientLogManager.ChangeLogLevel(System.Diagnostics.TraceLevel.Off);
            cacheFactory = new DataCacheFactory(configuration);
            defaultCache = cacheFactory.GetCache(cacheName);
        }
        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 #52
0
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            try
            {
                string cachename = "default";

                string key = "KEY";

                var val = DateTime.Now.ToString();

                if (args != null)
                {
                    if (args.Length == 1)
                        cachename = args[0];

                    if (args.Length == 2)
                        key = args[1];

                    if (args.Length == 3)
                        val = args[2];
                }

                Console.WriteLine("Initializing...");

                DataCacheFactory dcf = new DataCacheFactory();

                Console.WriteLine("Factory created.");

                Console.WriteLine("Connecting to cache '{0}'.", cachename);

                DataCache mycache = dcf.GetCache(cachename);

                Console.WriteLine("Connected successfully to cache.");

                mycache.Add(key, val);

                Console.WriteLine("Added value to cache {0}-{1}", key, val);
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                trace(ex);
            }
        }
Example #53
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();
        }
        public void WaitForItemNotificationShouldGetBulkNotification()
        {
            var expectedKey = "Key" + TestContext.TestName;
            var expectedOldValue = "oldValue" + TestContext.TestName;
            var expectedNewValue = "newValue" + TestContext.TestName;

            var dcf = new DataCacheFactory();
            var dc = dcf.GetCache(NotificationCacheName);

            // Create a workflow that waits for a notification
            var sut = WorkflowApplicationTest.Create(new WaitForCacheBulkNotification
                                                         {
                                                             CacheName = NotificationCacheName,
                                                         });

            // Will catch if the workflow aborts
            sut.Aborted = (args) => TestContext.WriteLine("Workflow Aborted {0}", args.Reason);

            sut.TestActivity();

            // Wait for the workflow to go idle
            Assert.IsTrue(sut.WaitForIdleEvent(), "WaitForCacheBulkNotification did not go idle");

            dc.Remove(expectedKey);
            dc.Add(expectedKey, expectedOldValue);

            // Update the item
            var expectedVersion = dc.Put(expectedKey, expectedNewValue);

            Assert.IsTrue(sut.WaitForCompletedEvent(2000), "WaitForCacheBulkNotification did not complete");

            // Assert Out Arguments
            sut.AssertOutArgument.IsNotNull("NotificationDescriptor");
            sut.AssertOutArgument.IsNotNull("Operations");

            var operations = (IEnumerable<DataCacheOperationDescriptor>) sut.Results.Output["Operations"];

            // Notifications are timing sensitive - the RemoveItem may or may not be included in the bulk get
            //Assert.AreEqual(DataCacheOperations.RemoveItem, operations.ElementAt(0).OperationType);
            //Assert.AreEqual(DataCacheOperations.AddItem, operations.ElementAt(1).OperationType);
            //Assert.AreEqual(DataCacheOperations.ReplaceItem, operations.ElementAt(2).OperationType);

            sut.Tracking.Trace();
        }
        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();
        }
        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 void WaitForCacheNotificationShouldGetNotificationOnReplaceWithRegion()
        {
            var expectedKey = "Key" + TestContext.TestName;
            var expectedOldValue = "oldValue" + TestContext.TestName;
            var expectedNewValue = "newValue" + TestContext.TestName;
            var expectedRegion = "Region" + TestContext.TestName;

            var dcf = new DataCacheFactory();
            var dc = dcf.GetCache(NotificationCacheName);

            dc.CreateRegion(expectedRegion);
            dc.Remove(expectedKey, expectedRegion);
            dc.Add(expectedKey, expectedOldValue, expectedRegion);

            // Create a workflow that waits for a notification
            var sut = WorkflowApplicationTest.Create(new WaitForRegionNotification
                                                         {
                                                             CacheName = NotificationCacheName,
                                                             Filter = DataCacheOperations.ReplaceItem,
                                                             Region = expectedRegion
                                                         });

            // Will catch if the workflow aborts
            sut.Aborted = (args) => TestContext.WriteLine("Workflow Aborted {0}", args.Reason);

            sut.TestActivity();

            // Wait for the workflow to go idle
            Assert.IsTrue(sut.WaitForIdleEvent(), "WaitForRegionNotification did not go idle");

            // Update the item
            var expectedVersion = dc.Put(expectedKey, expectedNewValue, expectedRegion);

            Assert.IsTrue(sut.WaitForCompletedEvent(2000), "WaitForRegionNotification did not complete");

            // Assert Out Arguments
            sut.AssertOutArgument.IsNotNull("NotificationDescriptor");
            sut.AssertOutArgument.AreEqual("Version", expectedVersion);
            sut.AssertOutArgument.AreEqual("CacheOperation", DataCacheOperations.ReplaceItem);
            sut.Tracking.Trace();
        }
        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 #59
0
        static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(OrganizitionService)))
            {
                host.Open();
                var server = new List<DataCacheServerEndpoint>();
                server.Add(new DataCacheServerEndpoint("localhost", 22233));
                // Set up the DataCacheFactory configuration
                var conf = new DataCacheFactoryConfiguration();
                conf.Servers = server;
                DataCacheFactory factory = new DataCacheFactory(conf);
                //foreach (var operation in host.Description.Endpoints[0].Contract.Operations)
                //{
                //    operation.Behaviors.Add(new FabricCacheOperationInvoker(factory));
                //}

                Console.WriteLine("Service is running");
                Console.Write("Press ENTER to close the host");
                Console.ReadLine();
                host.Close();
            }
        }
Example #60
0
        public static DataCache GetCache()
        {
            if (_cache != null)
                return _cache;

            //Define Array for 1 Cache Host
            List<DataCacheServerEndpoint> servers = new List<DataCacheServerEndpoint>(1);

            //Specify Cache Host Details
            //  Parameter 1 = host name
            //  Parameter 2 = cache port number
            servers.Add(new DataCacheServerEndpoint(System.Environment.MachineName, 22233));

            //Create cache configuration
            DataCacheFactoryConfiguration configuration = new DataCacheFactoryConfiguration();

            //Set the cache host(s)
            configuration.Servers = servers;

            //Set default properties for local cache (local cache disabled)
            configuration.LocalCacheProperties = new DataCacheLocalCacheProperties();
            //configuration.ChannelOpenTimeout = System.TimeSpan.FromMinutes(2);
            configuration.RequestTimeout = TimeSpan.FromSeconds(1);
            configuration.ChannelOpenTimeout = TimeSpan.FromSeconds(45);
            configuration.TransportProperties.ReceiveTimeout = TimeSpan.FromSeconds(45);
            configuration.TransportProperties.ChannelInitializationTimeout = TimeSpan.FromSeconds(10);
            configuration.MaxConnectionsToServer = 1;
            //Disable tracing to avoid informational/verbose messages on the web page
            DataCacheClientLogManager.ChangeLogLevel(System.Diagnostics.TraceLevel.Off);

            //Pass configuration settings to cacheFactory constructor
            _factory = new DataCacheFactory(configuration);

            //Get reference to named cache called "default"
            _cache = _factory.GetCache("default");

            return _cache;
        }