private static CacheManagerConfiguration GetFromConfiguration(IConfigurationSection configuration)
        {
            var managerConfiguration = new CacheManagerConfiguration();

            configuration.Bind(managerConfiguration);

            var handlesConfiguration = configuration.GetSection(HandlesSection);

            if (handlesConfiguration.GetChildren().Count() == 0)
            {
                throw new InvalidOperationException(
                          $"No cache handles defined in '{configuration.Path}'.");
            }

            foreach (var handleConfiguration in handlesConfiguration.GetChildren())
            {
                var cacheHandleConfiguration = GetHandleFromConfiguration(handleConfiguration);
                managerConfiguration.CacheHandleConfigurations.Add(cacheHandleConfiguration);
            }

            GetBackplaneConfiguration(managerConfiguration, configuration);
            GetLoggerFactoryConfiguration(managerConfiguration, configuration);
            GetSerializerConfiguration(managerConfiguration, configuration);

            return(managerConfiguration);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RedisCacheBackPlate"/> class.
        /// </summary>
        /// <param name="configuration">The cache manager configuration.</param>
        /// <param name="cacheName">The cache name.</param>
        public RedisCacheBackPlate(CacheManagerConfiguration configuration, string cacheName)
            : base(configuration, cacheName)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            this.channelName = string.Format(
                CultureInfo.InvariantCulture,
                "CacheManagerBackPlate_{0}",
                cacheName);

            this.identifier = Guid.NewGuid().ToString();

            RetryHelper.Retry(
                () =>
                {
                    // throws an exception if not found for the name
                    var cfg = RedisConfigurations.GetConfiguration(this.Name);

                    var connection = RedisConnectionPool.Connect(cfg);

                    this.redisSubscriper = connection.GetSubscriber();
                },
                configuration.RetryTimeout,
                configuration.MaxRetries);

            this.Subscribe();
        }
        private static void GetSerializerConfiguration(CacheManagerConfiguration managerConfiguration, IConfigurationSection configuration)
        {
            var serializerSection = configuration.GetSection(SerializerSection);

            if (serializerSection.GetChildren().Count() == 0)
            {
                // no serializer
                return;
            }

            var knownType = serializerSection[ConfigurationKnownType];
            var type      = serializerSection[ConfigurationType];

            if (string.IsNullOrWhiteSpace(knownType) && string.IsNullOrWhiteSpace(type))
            {
                throw new InvalidOperationException(
                          $"No '{ConfigurationType}' or '{ConfigurationKnownType}' defined in serializer configuration '{serializerSection.Path}'.");
            }

            if (string.IsNullOrWhiteSpace(type))
            {
                managerConfiguration.SerializerType = GetKnownSerializerType(knownType, serializerSection.Path);
            }
            else
            {
                managerConfiguration.SerializerType = Type.GetType(type, true);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RedisCacheBackPlate"/> class.
        /// </summary>
        /// <param name="configuration">The cache manager configuration.</param>
        public RedisCacheBackPlate(CacheManagerConfiguration configuration)
            : base(configuration)
        {
            NotNull(configuration, nameof(configuration));

            this.logger = configuration.LoggerFactory.CreateLogger(this);
            this.channelName = configuration.BackPlateChannelName ?? "CacheManagerBackPlate";
            this.identifier = Guid.NewGuid().ToString();

            RetryHelper.Retry(
                () =>
                {
                    // throws an exception if not found for the name
                    var cfg = RedisConfigurations.GetConfiguration(this.ConfigurationKey);

                    var connection = RedisConnectionPool.Connect(cfg);

                    this.redisSubscriper = connection.GetSubscriber();
                },
                configuration.RetryTimeout,
                configuration.MaxRetries,
                this.logger);

            this.Subscribe();
        }
        private static void GetLoggerFactoryConfiguration(CacheManagerConfiguration managerConfiguration, IConfigurationSection configuration)
        {
            var loggerFactorySection = configuration.GetSection(LoggerFactorySection);

            if (loggerFactorySection.GetChildren().Count() == 0)
            {
                // no logger factory
                return;
            }

            var knownType = loggerFactorySection[ConfigurationKnownType];
            var type      = loggerFactorySection[ConfigurationType];

            if (string.IsNullOrWhiteSpace(knownType) && string.IsNullOrWhiteSpace(type))
            {
                throw new InvalidOperationException(
                          $"No '{ConfigurationType}' or '{ConfigurationKnownType}' defined in logger factory configuration '{loggerFactorySection.Path}'.");
            }

            if (string.IsNullOrWhiteSpace(type))
            {
                managerConfiguration.LoggerFactoryType = GetKnownLoggerFactoryType(knownType, loggerFactorySection.Path);
            }
            else
            {
                managerConfiguration.LoggerFactoryType = Type.GetType(type, true);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RedisCacheBackplane"/> class.
        /// </summary>
        /// <param name="configuration">The cache manager configuration.</param>
        /// <param name="loggerFactory">The logger factory</param>
        public RedisCacheBackplane(CacheManagerConfiguration configuration, ILoggerFactory loggerFactory)
            : base(configuration)
        {
            NotNull(configuration, nameof(configuration));
            NotNull(loggerFactory, nameof(loggerFactory));

            this.logger = loggerFactory.CreateLogger(this);
            this.channelName = configuration.BackplaneChannelName ?? "CacheManagerBackplane";
            this.identifier = Guid.NewGuid().ToString();

            var cfg = RedisConfigurations.GetConfiguration(this.ConfigurationKey);
            this.connection = new RedisConnectionManager(
                cfg,
                loggerFactory);

            RetryHelper.Retry(() => this.Subscribe(), configuration.RetryTimeout, configuration.MaxRetries, this.logger);
        }
        private static void GetBackPlateConfiguration(CacheManagerConfiguration managerConfiguration, IConfigurationSection configuration)
        {
            var backPlateSection = configuration.GetSection("backPlate");

            if (backPlateSection.GetChildren().Count() == 0)
            {
                // no backplate
                return;
            }

            var type        = backPlateSection[ConfigurationType];
            var knownType   = backPlateSection[ConfigurationKnownType];
            var key         = backPlateSection[ConfigurationKey];
            var channelName = backPlateSection["channelName"];

            if (string.IsNullOrEmpty(type) && string.IsNullOrEmpty(knownType))
            {
                throw new InvalidOperationException(
                          $"No '{ConfigurationType}' or '{ConfigurationKnownType}' defined in back plate configuration '{backPlateSection.Path}'.");
            }

            if (string.IsNullOrWhiteSpace(type))
            {
                var keyRequired = false;
                managerConfiguration.BackPlateType = GetKnownBackPlateType(knownType, backPlateSection.Path, out keyRequired);
                if (keyRequired && string.IsNullOrWhiteSpace(key))
                {
                    throw new InvalidOperationException(
                              $"The key property is required for the '{knownType}' back plate, but is not configured in '{backPlateSection.Path}'.");
                }
            }
            else
            {
                managerConfiguration.BackPlateType = Type.GetType(type, true);
            }

            managerConfiguration.BackPlateChannelName      = channelName;
            managerConfiguration.BackPlateConfigurationKey = key;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ConfigurationBuilder"/> class
 /// which provides fluent configuration methods.
 /// Creates a builder which allows to modify the existing <paramref name="configuration"/>.
 /// </summary>
 /// <param name="configuration">The configuration the builder should be instantiated for.</param>
 public ConfigurationBuilder(CacheManagerConfiguration configuration)
     : base(configuration)
 {
 }
        internal static CacheManagerConfiguration LoadFromSection(CacheManagerSection section, string configName)
        {
            NotNullOrWhiteSpace(configName, nameof(configName));

            var handleDefsSection = section.CacheHandleDefinitions;

            Ensure(handleDefsSection.Count > 0, "There are no cache handles defined.");

            // load handle definitions as lookup
            var handleDefs = new SortedList<string, CacheHandleConfiguration>();
            foreach (CacheHandleDefinition def in handleDefsSection)
            {
                //// don't validate at this point, otherwise we will get an exception if any defined handle doesn't match with the requested type...
                //// CacheReflectionHelper.ValidateCacheHandleGenericTypeArguments(def.HandleType, cacheValue);

                var normId = def.Id.ToUpper(CultureInfo.InvariantCulture);
                handleDefs.Add(
                    normId,
                    new CacheHandleConfiguration(def.Id)
                    {
                        HandleType = def.HandleType,
                        ExpirationMode = def.DefaultExpirationMode,
                        ExpirationTimeout = GetTimeSpan(def.DefaultTimeout, "defaultTimeout")
                    });
            }

            // retrieve the handles collection with the correct name
            CacheManagerHandleCollection managerCfg = section.CacheManagers.FirstOrDefault(p => p.Name.Equals(configName, StringComparison.OrdinalIgnoreCase));

            EnsureNotNull(managerCfg, "No cache manager configuration found for name [{0}]", configName);

            int? maxRetries = managerCfg.MaximumRetries;
            if (maxRetries.HasValue && maxRetries.Value <= 0)
            {
                throw new InvalidOperationException("Maximum number of retries must be greater than zero.");
            }

            int? retryTimeout = managerCfg.RetryTimeout;
            if (retryTimeout.HasValue && retryTimeout.Value < 0)
            {
                throw new InvalidOperationException("Retry timeout must be greater than or equal to zero.");
            }

            // build configuration
            var cfg = new CacheManagerConfiguration()
            {
                UpdateMode = managerCfg.UpdateMode,
                MaxRetries = maxRetries.HasValue ? maxRetries.Value : 50,
                RetryTimeout = retryTimeout.HasValue ? retryTimeout.Value : 100
            };

            if (string.IsNullOrWhiteSpace(managerCfg.BackplaneType))
            {
                if (!string.IsNullOrWhiteSpace(managerCfg.BackplaneName))
                {
                    throw new InvalidOperationException("Backplane type cannot be null if backplane name is specified.");
                }
            }
            else
            {
                if (string.IsNullOrWhiteSpace(managerCfg.BackplaneName))
                {
                    throw new InvalidOperationException("Backplane name cannot be null if backplane type is specified.");
                }

                var backplaneType = Type.GetType(managerCfg.BackplaneType, false);
                EnsureNotNull(backplaneType, "Backplane type not found, '{0}'. Make sure to install the corresponding nuget package.", managerCfg.BackplaneType);

                cfg.BackplaneType = backplaneType;
                cfg.BackplaneConfigurationKey = managerCfg.BackplaneName;
            }

            // build serializer if set
            if (!string.IsNullOrWhiteSpace(managerCfg.SerializerType))
            {
                var serializerType = Type.GetType(managerCfg.SerializerType, false);
                EnsureNotNull(serializerType, "Serializer type not found, {0}.", managerCfg.SerializerType);

                cfg.SerializerType = serializerType;
            }

            foreach (CacheManagerHandle handleItem in managerCfg)
            {
                var normRefId = handleItem.RefHandleId.ToUpper(CultureInfo.InvariantCulture);

                Ensure(
                    handleDefs.ContainsKey(normRefId),
                    "Referenced cache handle [{0}] cannot be found in cache handles definition.",
                    handleItem.RefHandleId);

                var handleDef = handleDefs[normRefId];

                var handle = new CacheHandleConfiguration(handleItem.Name)
                {
                    HandleType = handleDef.HandleType,
                    ExpirationMode = handleDef.ExpirationMode,
                    ExpirationTimeout = handleDef.ExpirationTimeout,
                    EnableStatistics = managerCfg.EnableStatistics,
                    EnablePerformanceCounters = managerCfg.EnablePerformanceCounters,
                    IsBackplaneSource = handleItem.IsBackplaneSource
                };

                // override default timeout if it is defined in this section.
                if (!string.IsNullOrWhiteSpace(handleItem.Timeout))
                {
                    handle.ExpirationTimeout = GetTimeSpan(handleItem.Timeout, "timeout");
                }

                // override default expiration mode if it is defined in this section.
                if (!string.IsNullOrWhiteSpace(handleItem.ExpirationMode))
                {
                    try
                    {
                        handle.ExpirationMode = (ExpirationMode)Enum.Parse(typeof(ExpirationMode), handleItem.ExpirationMode);
                    }
                    catch (ArgumentException ex)
                    {
                        throw new InvalidOperationException("Invalid value '" + handleItem.ExpirationMode + "'for expiration mode", ex);
                    }
                }

                if (handle.ExpirationMode != ExpirationMode.None && handle.ExpirationTimeout == TimeSpan.Zero)
                {
                    throw new InvalidOperationException(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            "Expiration mode set without a valid timeout specified for handle [{0}]",
                            handle.Name));
                }

                cfg.CacheHandleConfigurations.Add(handle);
            }

            Ensure(cfg.CacheHandleConfigurations.Count > 0, "There are no valid cache handles linked to the cache manager configuration [{0}]", configName);

            return cfg;
        }
 internal ConfigurationBuilderCachePart()
 {
     Configuration = new CacheManagerConfiguration();
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseCacheManager{TCacheValue}"/> class
        /// using the specified <paramref name="configuration"/>.
        /// If the name of the <paramref name="configuration"/> is defined, the cache manager will
        /// use it. Otherwise a random string will be generated.
        /// </summary>
        /// <param name="configuration">
        /// The configuration which defines the structure and complexity of the cache manager.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// When <paramref name="configuration"/> is null.
        /// </exception>
        /// <see cref="CacheFactory"/>
        /// <see cref="ConfigurationBuilder"/>
        /// <see cref="BaseCacheHandle{TCacheValue}"/>
        public BaseCacheManager(IServiceProvider sp,
                                ILogger <BaseCacheManager <TKey, TValue> > logger,
                                IOptions <CacheManagerConfiguration <TKey, TValue> > configuration,
                                IEnumerable <IBaseCacheHandle <TKey, TValue> > handles)
        {
            CacheManagerConfiguration <TKey, TValue> config = configuration.Value;

            NotNullOrWhiteSpace(config.Name, nameof(config.Name));

            Configuration = configuration.Value;

            //var serializer = CacheReflectionHelper.CreateSerializer(configuration, loggerFactory);

            Logger = logger;

            _logTrace = Logger.IsEnabled(LogLevel.Trace);

            Logger.LogInformation("Cache manager: adding cache handles...");

            try
            {
                _cacheHandles = handles.ToArray();//CacheReflectionHelper.CreateCacheHandles(this, loggerFactory, serializer).ToArray();

                var index = 0;
                foreach (var handle in _cacheHandles)
                {
                    var handleIndex = index;
                    handle.OnCacheSpecificRemove += (sender, args) =>
                    {
                        // added sync for using backplane with in-memory caches on cache specific removal
                        // but commented for now, this is not really needed if all instances use the same expiration etc, would just cause dublicated events
                        ////if (_cacheBackplane != null && handle.Configuration.IsBackplaneSource && !handle.IsDistributedCache)
                        ////{
                        ////    if (string.IsNullOrEmpty(args.Region))
                        ////    {
                        ////        _cacheBackplane.NotifyRemove(args.Key);
                        ////    }
                        ////    else
                        ////    {
                        ////        _cacheBackplane.NotifyRemove(args.Key, args.Region);
                        ////    }
                        ////}

                        // base cache handle does logging for this

                        if (Configuration.UpdateMode == CacheUpdateMode.Up)
                        {
                            if (_logTrace)
                            {
                                Logger.LogTrace($"Cleaning handles above '{handleIndex}' because of remove event.");
                            }

                            EvictFromHandlesAbove(args.Key, handleIndex);
                        }

                        // moving down below cleanup, optherwise the item could still be in memory
                        TriggerOnRemoveByHandle(args.Key, args.Reason, handleIndex + 1, args.Value);
                    };

                    index++;
                }

                _cacheBackplane = sp.GetService <ICacheBackplane <TKey, TValue> >();
                if (_cacheBackplane != null)
                {
                    RegisterCacheBackplane(_cacheBackplane);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error occurred while creating the cache manager.");
                throw;
            }
        }
        private static void GetBackplaneConfiguration(CacheManagerConfiguration managerConfiguration, IConfigurationSection configuration)
        {
            var backplaneSection = configuration.GetSection("backplane");
            if (backplaneSection.GetChildren().Count() == 0)
            {
                // no backplane
                return;
            }

            var type = backplaneSection[ConfigurationType];
            var knownType = backplaneSection[ConfigurationKnownType];
            var key = backplaneSection[ConfigurationKey];
            var channelName = backplaneSection["channelName"];

            if (string.IsNullOrEmpty(type) && string.IsNullOrEmpty(knownType))
            {
                throw new InvalidOperationException(
                    $"No '{ConfigurationType}' or '{ConfigurationKnownType}' defined in backplane configuration '{backplaneSection.Path}'.");
            }

            if (string.IsNullOrWhiteSpace(type))
            {
                var keyRequired = false;
                managerConfiguration.BackplaneType = GetKnownBackplaneType(knownType, backplaneSection.Path, out keyRequired);
                if (keyRequired && string.IsNullOrWhiteSpace(key))
                {
                    throw new InvalidOperationException(
                        $"The key property is required for the '{knownType}' backplane, but is not configured in '{backplaneSection.Path}'.");
                }
            }
            else
            {
                managerConfiguration.BackplaneType = Type.GetType(type, true);
            }

            managerConfiguration.BackplaneChannelName = channelName;
            managerConfiguration.BackplaneConfigurationKey = key;
        }
        private static CacheManagerConfiguration GetFromConfiguration(IConfigurationSection configuration)
        {
            var managerConfiguration = new CacheManagerConfiguration();
            configuration.Bind(managerConfiguration);

            var handlesConfiguration = configuration.GetSection(HandlesSection);

            if (handlesConfiguration.GetChildren().Count() == 0)
            {
                throw new InvalidOperationException(
                    $"No cache handles defined in '{configuration.Path}'.");
            }

            foreach (var handleConfiguration in handlesConfiguration.GetChildren())
            {
                var cacheHandleConfiguration = GetHandleFromConfiguration(handleConfiguration);
                managerConfiguration.CacheHandleConfigurations.Add(cacheHandleConfiguration);
            }

            GetBackplaneConfiguration(managerConfiguration, configuration);
            GetLoggerFactoryConfiguration(managerConfiguration, configuration);
            GetSerializerConfiguration(managerConfiguration, configuration);

            return managerConfiguration;
        }
Esempio n. 14
0
 /// <summary>
 /// <para>Instantiates a cache manager using the given <paramref name="configuration"/>.</para>
 /// </summary>
 /// <param name="cacheName">The name of the cache.</param>
 /// <param name="configuration">
 /// The configured which will be used to configure the cache manager instance.
 /// </param>
 /// <typeparam name="TCacheValue">The type of the cache item value.</typeparam>
 /// <returns>The cache manager instance.</returns>
 /// <see cref="ConfigurationBuilder"/>
 /// <exception cref="System.ArgumentNullException">
 /// Thrown if the <paramref name="configuration"/> is null.
 /// </exception>
 /// <exception cref="System.InvalidOperationException">
 /// Thrown on certain configuration errors related to the cache handles.
 /// </exception>
 public static ICacheManager <TCacheValue> FromConfiguration <TCacheValue>(string cacheName, CacheManagerConfiguration configuration)
 {
     NotNull(configuration, nameof(configuration));
     configuration.Name = cacheName;
     return(new BaseCacheManager <TCacheValue>(configuration));
 }
Esempio n. 15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ConfigurationBuilder"/> class
 /// which provides fluent configuration methods.
 /// Creates a builder which allows to modify the existing <paramref name="configuration"/>.
 /// </summary>
 /// <param name="configuration">The configuration the builder should be instantiated for.</param>
 public ConfigurationBuilder(CacheManagerConfiguration configuration)
     : base(configuration)
 {
 }
Esempio n. 16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ConfigurationBuilder"/> class
 /// which provides fluent configuration methods.
 /// Creates a builder which allows to modify the existing <paramref name="configuration"/>.
 /// </summary>
 /// <param name="name">The name of the cache manager.</param>
 /// <param name="configuration">The configuration the builder should be instantiated for.</param>
 public ConfigurationBuilder(string name, CacheManagerConfiguration configuration)
     : base(configuration)
 {
     NotNullOrWhiteSpace(name, nameof(name));
     this.Configuration.Name = name;
 }
        private static void GetLoggerFactoryConfiguration(CacheManagerConfiguration managerConfiguration, IConfigurationSection configuration)
        {
            var loggerFactorySection = configuration.GetSection(LoggerFactorySection);

            if (loggerFactorySection.GetChildren().Count() == 0)
            {
                // no logger factory
                return;
            }

            var knownType = loggerFactorySection[ConfigurationKnownType];
            var type = loggerFactorySection[ConfigurationType];

            if (string.IsNullOrWhiteSpace(knownType) && string.IsNullOrWhiteSpace(type))
            {
                throw new InvalidOperationException(
                    $"No '{ConfigurationType}' or '{ConfigurationKnownType}' defined in logger factory configuration '{loggerFactorySection.Path}'.");
            }

            if (string.IsNullOrWhiteSpace(type))
            {
                managerConfiguration.LoggerFactoryType = GetKnownLoggerFactoryType(knownType, loggerFactorySection.Path);
            }
            else
            {
                managerConfiguration.LoggerFactoryType = Type.GetType(type, true);
            }
        }
        internal static CacheManagerConfiguration LoadFromSection(CacheManagerSection section, string configName)
        {
            NotNullOrWhiteSpace(configName, nameof(configName));

            var handleDefsSection = section.CacheHandleDefinitions;

            Ensure(handleDefsSection.Count > 0, "There are no cache handles defined.");

            // load handle definitions as lookup
            var handleDefs = new SortedList <string, CacheHandleConfiguration>();

            foreach (var def in handleDefsSection)
            {
                //// don't validate at this point, otherwise we will get an exception if any defined handle doesn't match with the requested type...
                //// CacheReflectionHelper.ValidateCacheHandleGenericTypeArguments(def.HandleType, cacheValue);

                var normId = def.Id.ToUpper(CultureInfo.InvariantCulture);
                handleDefs.Add(
                    normId,
                    new CacheHandleConfiguration(def.Id)
                {
                    HandleType        = def.HandleType,
                    ExpirationMode    = def.DefaultExpirationMode,
                    ExpirationTimeout = GetTimeSpan(def.DefaultTimeout, "defaultTimeout")
                });
            }

            // retrieve the handles collection with the correct name
            var managerCfg = section.CacheManagers.FirstOrDefault(p => p.Name.Equals(configName, StringComparison.OrdinalIgnoreCase));

            EnsureNotNull(managerCfg, "No cache manager configuration found for name [{0}]", configName);

            var maxRetries = managerCfg.MaximumRetries;

            if (maxRetries.HasValue && maxRetries.Value <= 0)
            {
                throw new InvalidOperationException("Maximum number of retries must be greater than zero.");
            }

            var retryTimeout = managerCfg.RetryTimeout;

            if (retryTimeout.HasValue && retryTimeout.Value < 0)
            {
                throw new InvalidOperationException("Retry timeout must be greater than or equal to zero.");
            }

            // build configuration
            var cfg = new CacheManagerConfiguration()
            {
                UpdateMode   = managerCfg.UpdateMode,
                MaxRetries   = maxRetries ?? 50,
                RetryTimeout = retryTimeout ?? 100
            };

            if (string.IsNullOrWhiteSpace(managerCfg.BackplaneType))
            {
                if (!string.IsNullOrWhiteSpace(managerCfg.BackplaneName))
                {
                    throw new InvalidOperationException("Backplane type cannot be null if backplane name is specified.");
                }
            }
            else
            {
                if (string.IsNullOrWhiteSpace(managerCfg.BackplaneName))
                {
                    throw new InvalidOperationException("Backplane name cannot be null if backplane type is specified.");
                }

                var backplaneType = Type.GetType(managerCfg.BackplaneType, false);
                EnsureNotNull(backplaneType, "Backplane type not found, '{0}'. Make sure to install the corresponding nuget package.", managerCfg.BackplaneType);

                cfg.BackplaneType             = backplaneType;
                cfg.BackplaneConfigurationKey = managerCfg.BackplaneName;
            }

            // build serializer if set
            if (!string.IsNullOrWhiteSpace(managerCfg.SerializerType))
            {
                var serializerType = Type.GetType(managerCfg.SerializerType, false);
                EnsureNotNull(serializerType, "Serializer type not found, {0}.", managerCfg.SerializerType);

                cfg.SerializerType = serializerType;
            }

            foreach (var handleItem in managerCfg)
            {
                var normRefId = handleItem.RefHandleId.ToUpper(CultureInfo.InvariantCulture);

                Ensure(
                    handleDefs.ContainsKey(normRefId),
                    "Referenced cache handle [{0}] cannot be found in cache handles definition.",
                    handleItem.RefHandleId);

                var handleDef = handleDefs[normRefId];

                var handle = new CacheHandleConfiguration(handleItem.Name)
                {
                    HandleType                = handleDef.HandleType,
                    ExpirationMode            = handleDef.ExpirationMode,
                    ExpirationTimeout         = handleDef.ExpirationTimeout,
                    EnableStatistics          = managerCfg.EnableStatistics,
                    EnablePerformanceCounters = managerCfg.EnablePerformanceCounters,
                    IsBackplaneSource         = handleItem.IsBackplaneSource
                };

                // override default timeout if it is defined in this section.
                if (!string.IsNullOrWhiteSpace(handleItem.Timeout))
                {
                    handle.ExpirationTimeout = GetTimeSpan(handleItem.Timeout, "timeout");
                }

                // override default expiration mode if it is defined in this section.
                if (!string.IsNullOrWhiteSpace(handleItem.ExpirationMode))
                {
                    try
                    {
                        handle.ExpirationMode = (ExpirationMode)Enum.Parse(typeof(ExpirationMode), handleItem.ExpirationMode);
                    }
                    catch (ArgumentException ex)
                    {
                        throw new InvalidOperationException("Invalid value '" + handleItem.ExpirationMode + "'for expiration mode", ex);
                    }
                }

                if (handle.ExpirationMode != ExpirationMode.None && handle.ExpirationTimeout == TimeSpan.Zero)
                {
                    throw new InvalidOperationException(
                              string.Format(
                                  CultureInfo.InvariantCulture,
                                  "Expiration mode set without a valid timeout specified for handle [{0}]",
                                  handle.Name));
                }

                cfg.CacheHandleConfigurations.Add(handle);
            }

            Ensure(cfg.CacheHandleConfigurations.Count > 0, "There are no valid cache handles linked to the cache manager configuration [{0}]", configName);

            return(cfg);
        }
        private static void GetSerializerConfiguration(CacheManagerConfiguration managerConfiguration, IConfigurationSection configuration)
        {
            var serializerSection = configuration.GetSection(SerializerSection);

            if (serializerSection.GetChildren().Count() == 0)
            {
                // no serializer
                return;
            }

            var knownType = serializerSection[ConfigurationKnownType];
            var type = serializerSection[ConfigurationType];

            if (string.IsNullOrWhiteSpace(knownType) && string.IsNullOrWhiteSpace(type))
            {
                throw new InvalidOperationException(
                    $"No '{ConfigurationType}' or '{ConfigurationKnownType}' defined in serializer configuration '{serializerSection.Path}'.");
            }

            if (string.IsNullOrWhiteSpace(type))
            {
                managerConfiguration.SerializerType = GetKnownSerializerType(knownType, serializerSection.Path);
            }
            else
            {
                managerConfiguration.SerializerType = Type.GetType(type, true);
            }
        }
 internal ConfigurationBuilderCachePart(CacheManagerConfiguration forConfiguration)
 {
     NotNull(forConfiguration, nameof(forConfiguration));
     Configuration = forConfiguration;
 }
Esempio n. 21
0
 /// <summary>
 /// <para>Instantiates a cache manager using the given <paramref name="configuration"/>.</para>
 /// </summary>
 /// <param name="cacheName">The name of the cache.</param>
 /// <param name="configuration">
 /// The configured which will be used to configure the cache manager instance.
 /// </param>
 /// <typeparam name="TCacheValue">The type of the cache item value.</typeparam>
 /// <returns>The cache manager instance.</returns>
 /// <see cref="ConfigurationBuilder"/>
 /// <exception cref="System.ArgumentNullException">
 /// Thrown if the <paramref name="configuration"/> is null.
 /// </exception>
 /// <exception cref="System.InvalidOperationException">
 /// Thrown on certain configuration errors related to the cache handles.
 /// </exception>
 public static ICacheManager <TCacheValue> FromConfiguration <TCacheValue>(string cacheName, CacheManagerConfiguration configuration)
 => new BaseCacheManager <TCacheValue>(cacheName, configuration);
Esempio n. 22
0
 /// <summary>
 /// <para>Instantiates a cache manager using the given <paramref name="configuration"/>.</para>
 /// </summary>
 /// <example>
 /// The following example show how to build a <c>CacheManagerConfiguration</c> and then
 /// using the <c>CacheFactory</c> to create a new cache manager instance.
 /// <code>
 /// <![CDATA[
 /// var managerConfiguration = ConfigurationBuilder.BuildConfiguration<object>(settings =>
 /// {
 ///     settings.WithUpdateMode(CacheUpdateMode.Up)
 ///         .WithDictionaryCacheHandle<object>>()
 ///             .EnablePerformanceCounters()
 ///             .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(10));
 /// });
 ///
 /// var cache = CacheFactory.FromConfiguration<object>(managerConfiguration);
 /// cache.Add("key", "value");
 /// ]]>
 /// </code>
 /// </example>
 /// <param name="configuration">
 /// The configured which will be used to configure the cache manager instance.
 /// </param>
 /// <typeparam name="TCacheValue">The type of the cache item value.</typeparam>
 /// <returns>The cache manager instance.</returns>
 /// <see cref="ConfigurationBuilder"/>
 /// <exception cref="System.ArgumentNullException">
 /// Thrown if the <paramref name="configuration"/> is null.
 /// </exception>
 /// <exception cref="System.InvalidOperationException">
 /// Thrown on certain configuration errors related to the cache handles.
 /// </exception>
 public static ICacheManager <TCacheValue> FromConfiguration <TCacheValue>(CacheManagerConfiguration configuration)
 => FromConfiguration <TCacheValue>(Guid.NewGuid().ToString("N"), configuration);
Esempio n. 23
0
        /// <summary>
        /// Instantiates a cache manager using the given <paramref name="cacheValueType"/> and <paramref name="configuration"/>.
        /// Use this overload only if you cannot use the generic overload. The return type will be <c>Object</c>.
        /// This method can be used for example in conjunction with dependency injection frameworks.
        /// </summary>
        /// <param name="cacheValueType">The type of the cache item value.</param>
        /// <param name="cacheName">The name of the cache.</param>
        /// <param name="configuration">
        /// The configured which will be used to configure the cache manager instance.
        /// </param>
        /// <returns>The cache manager instance.</returns>
        /// <see cref="ConfigurationBuilder"/>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if the <c>cacheValueType</c>, <c>cacheName</c> or <c>configuration</c> is null.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        /// Thrown on certain configuration errors related to the cache handles.
        /// </exception>
        public static object FromConfiguration(Type cacheValueType, string cacheName, CacheManagerConfiguration configuration)
        {
            NotNull(cacheValueType, nameof(cacheValueType));

            var type = typeof(BaseCacheManager <>).MakeGenericType(new[] { cacheValueType });

            return(Activator.CreateInstance(type, new object[] { cacheName, configuration }));
        }
Esempio n. 24
0
 internal ConfigurationBuilderCachePart(CacheManagerConfiguration forConfiguration)
 {
     NotNull(forConfiguration, nameof(forConfiguration));
     this.Configuration = forConfiguration;
 }
Esempio n. 25
0
 /// <summary>
 /// Instantiates a cache manager using the given <paramref name="cacheValueType"/> and <paramref name="configuration"/>.
 /// Use this overload only if you cannot use the generic overload. The return type will be <c>Object</c>.
 /// This method can be used for example in conjunction with dependency injection frameworks.
 /// </summary>
 /// <param name="cacheValueType">The type of the cache item value.</param>
 /// <param name="configuration">
 /// The configured which will be used to configure the cache manager instance.
 /// </param>
 /// <returns>The cache manager instance.</returns>
 /// <see cref="ConfigurationBuilder"/>
 /// <exception cref="System.ArgumentNullException">
 /// Thrown if the <paramref name="cacheValueType"/> or <paramref name="configuration"/> are null.
 /// </exception>
 /// <exception cref="System.InvalidOperationException">
 /// Thrown on certain configuration errors related to the cache handles.
 /// </exception>
 public static object FromConfiguration(Type cacheValueType, CacheManagerConfiguration configuration)
 => FromConfiguration(cacheValueType, Guid.NewGuid().ToString("N"), configuration);
Esempio n. 26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ConfigurationBuilder"/> class
 /// which provides fluent configuration methods.
 /// Creates a builder which allows to modify the existing <paramref name="configuration"/>.
 /// </summary>
 /// <param name="name">The name of the cache manager.</param>
 /// <param name="configuration">The configuration the builder should be instantiated for.</param>
 public ConfigurationBuilder(string name, CacheManagerConfiguration configuration)
     : base(configuration)
 {
     NotNullOrWhiteSpace(name, nameof(name));
     this.Configuration.Name = name;
 }
Esempio n. 27
0
        /// <summary>
        /// Instantiates a cache manager using the given <paramref name="cacheValueType"/> and <paramref name="configuration"/>.
        /// Use this overload only if you cannot use the generic overload. The return type will be <c>Object</c>.
        /// This method can be used for example in conjunction with dependency injection frameworks.
        /// </summary>
        /// <param name="cacheValueType">The type of the cache item value.</param>
        /// <param name="cacheName">The name of the cache.</param>
        /// <param name="configuration">
        /// The configured which will be used to configure the cache manager instance.
        /// </param>
        /// <returns>The cache manager instance.</returns>
        /// <see cref="ConfigurationBuilder"/>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if the <c>cacheValueType</c>, <c>cacheName</c> or <c>configuration</c> is null.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        /// Thrown on certain configuration errors related to the cache handles.
        /// </exception>
        public static object FromConfiguration(Type cacheValueType, string cacheName, CacheManagerConfiguration configuration)
        {
            if (cacheValueType == null)
            {
                throw new ArgumentNullException("cacheValueType");
            }

            var type = typeof(BaseCacheManager <>).MakeGenericType(new[] { cacheValueType });

            return(Activator.CreateInstance(type, new object[] { cacheName, configuration }));
        }