Ejemplo n.º 1
0
        /// <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();
        }
Ejemplo n.º 2
0
        internal static ICacheSerializer CreateSerializer(CacheManagerConfiguration configuration, ILoggerFactory loggerFactory)
        {
            NotNull(configuration, nameof(configuration));
            NotNull(loggerFactory, nameof(loggerFactory));

#if !DOTNET5_2
            if (configuration.SerializerType == null)
            {
                return(new BinaryCacheSerializer());
            }
#endif
            if (configuration.SerializerType != null)
            {
                CheckImplements <ICacheSerializer>(configuration.SerializerType);

                var args = new object[] { configuration, loggerFactory };
                if (configuration.SerializerTypeArguments != null)
                {
                    args = configuration.SerializerTypeArguments.Concat(args).ToArray();
                }

                return((ICacheSerializer)CreateInstance(configuration.SerializerType, args));
            }

            return(null);
        }
Ejemplo n.º 3
0
        internal static CacheBackplane CreateBackplane(CacheManagerConfiguration configuration, ILoggerFactory loggerFactory)
        {
            NotNull(configuration, nameof(configuration));
            NotNull(loggerFactory, nameof(loggerFactory));

            if (configuration.BackplaneType != null)
            {
                if (!configuration.CacheHandleConfigurations.Any(p => p.IsBackplaneSource))
                {
                    throw new InvalidOperationException(
                              "At least one cache handle must be marked as the backplane source if a backplane is defined via configuration.");
                }

                CheckExtends <CacheBackplane>(configuration.BackplaneType);

                var args = new object[] { configuration, loggerFactory };
                if (configuration.BackplaneTypeArguments != null)
                {
                    args = configuration.BackplaneTypeArguments.Concat(args).ToArray();
                }

                return((CacheBackplane)CreateInstance(configuration.BackplaneType, args));
            }

            return(null);
        }
        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);
            }
        }
        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);
            }
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DictionaryCacheHandle{TCacheValue}"/> class.
 /// </summary>
 /// <param name="managerConfiguration">The manager configuration.</param>
 /// <param name="configuration">The cache handle configuration.</param>
 /// <param name="loggerFactory">The logger factory.</param>
 public DictionaryCacheHandle(CacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory)
     : base(managerConfiguration, configuration)
 {
     NotNull(loggerFactory, nameof(loggerFactory));
     this.Logger = loggerFactory.CreateLogger(this);
     this.cache  = new ConcurrentDictionary <string, CacheItem <TCacheValue> >();
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BucketCacheHandle{TCacheValue}"/> class.
        /// </summary>
        /// <param name="managerConfiguration">The manager configuration.</param>
        /// <param name="configuration">The cache handle configuration.</param>
        /// <param name="loggerFactory">The logger factory.</param>
        /// <exception cref="System.InvalidOperationException">
        /// If <c>configuration.HandleName</c> is not valid.
        /// </exception>
        public BucketCacheHandle(CacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory)
            : base(managerConfiguration, configuration)
        {
            NotNull(configuration, nameof(configuration));
            NotNull(loggerFactory, nameof(loggerFactory));

            this.Logger = loggerFactory.CreateLogger(this);

            // we can configure the bucket name by having "<configKey>:<bucketName>" as handle's
            // name value
            var nameParts = configuration.Key.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries);

            Ensure(nameParts.Length > 0, "Handle key is not valid {0}", configuration.Key);

            this.configurationName = nameParts[0];

            if (nameParts.Length == 2)
            {
                this.bucketName = nameParts[1];
            }

            this.configuration       = CouchbaseConfigurationManager.GetConfiguration(this.configurationName);
            this.bucketConfiguration = CouchbaseConfigurationManager.GetBucketConfiguration(this.configuration, this.bucketName);
            this.bucket = CouchbaseConfigurationManager.GetBucket(this.configuration, this.configurationName, this.bucketName);
        }
        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);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CacheBackPlate" /> class.
        /// </summary>
        /// <param name="configuration">The cache manager configuration.</param>
        /// <param name="cacheName">The cache name.</param>
        /// <exception cref="System.ArgumentNullException">If configuration is null.</exception>
        /// <exception cref="System.ArgumentException">Parameter cacheName cannot be null or empty.</exception>
        protected CacheBackPlate(CacheManagerConfiguration configuration, string cacheName)
        {
            NotNull(configuration, nameof(configuration));
            NotNullOrWhiteSpace(cacheName, nameof(cacheName));

            this.CacheConfiguration = configuration;
            this.Name      = configuration.BackPlateName;
            this.CacheName = cacheName;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RedisCacheBackPlate"/> class.
        /// </summary>
        /// <param name="configuration">The cache manager configuration.</param>
        /// <param name="loggerFactory">The logger factory</param>
        public RedisCacheBackPlate(CacheManagerConfiguration configuration, ILoggerFactory loggerFactory)
            : base(configuration)
        {
            NotNull(configuration, nameof(configuration));
            NotNull(loggerFactory, nameof(loggerFactory));

            this.logger      = 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();

            this.timer = new Timer(
                (obj) =>
            {
                lock (this.messageLock)
                {
                    try
                    {
                        if (this.messages != null && this.messages.Count > 0)
                        {
                            var msgs = string.Join(",", this.messages);
                            if (this.logger.IsEnabled(LogLevel.Debug))
                            {
                                this.logger.LogDebug("Back-plate is sending {0} messages ({1} skipped).", this.messages.Count, this.skippedMessages);
                            }

                            this.Publish(msgs);
                            this.skippedMessages = 0;
                            this.messages.Clear();
                        }
                    }
                    catch (Exception ex)
                    {
                        this.logger.LogError(ex, "Error occurred sending back plate messages.");
                        throw;
                    }
                }
            },
                this,
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(100));
        }
Ejemplo n.º 11
0
 static SmartCache()
 {
     cfg = ConfigurationBuilder.BuildConfiguration(settings =>
     {
         settings.WithUpdateMode(CacheUpdateMode.Up)
         .WithSystemRuntimeCacheHandle("SmartCache")
         .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromMinutes(60));
     });
 }
 public MockCacheHandle(CacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory)
     : base(managerConfiguration, configuration)
 {
     this.Logger     = loggerFactory.CreateLogger(this);
     this.AddCall    = () => true;
     this.PutCall    = () => { };
     this.RemoveCall = () => { };
     this.UpdateCall = () => { };
 }
Ejemplo n.º 13
0
        public SystemWebCacheHandle(CacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory)
            : base(managerConfiguration, configuration)
        {
            NotNull(loggerFactory, nameof(loggerFactory));
            this.Logger = loggerFactory.CreateLogger(this);

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

            this.CreateInstanceToken();
        }
Ejemplo n.º 14
0
        public RedisCacheHandle(CacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory, ICacheSerializer serializer)
            : base(managerConfiguration, configuration)
        {
            NotNull(loggerFactory, nameof(loggerFactory));
            NotNull(managerConfiguration, nameof(managerConfiguration));
            EnsureNotNull(serializer, "A serializer is required for the redis cache handle");

            this.managerConfiguration = managerConfiguration;
            this.Logger         = loggerFactory.CreateLogger(this);
            this.valueConverter = new RedisValueConverter(serializer);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MemoryCacheHandle{TCacheValue}"/> class.
        /// </summary>
        /// <param name="managerConfiguration">The manager configuration.</param>
        /// <param name="configuration">The cache handle configuration.</param>
        /// <param name="loggerFactory">The logger factory.</param>
        public MemoryCacheHandle(CacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory)
            : base(managerConfiguration, configuration)
        {
            NotNull(configuration, nameof(configuration));
            NotNull(loggerFactory, nameof(loggerFactory));

            this.Logger      = loggerFactory.CreateLogger(this);
            this.cacheName   = configuration.Name;
            this.cache       = new MemoryCache(new MemoryCacheOptions());
            this.instanceKey = Guid.NewGuid().ToString();

            this.CreateInstanceToken();
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseCacheHandle{TCacheValue}"/> class.
        /// </summary>
        /// <param name="managerConfiguration">The manager's configuration.</param>
        /// <param name="configuration">The configuration.</param>
        /// <exception cref="System.ArgumentNullException">
        /// If <paramref name="managerConfiguration"/> or <paramref name="configuration"/> are null.
        /// </exception>
        /// <exception cref="System.ArgumentException">If <paramref name="configuration"/> name is empty.</exception>
        protected BaseCacheHandle(CacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration)
        {
            NotNull(configuration, nameof(configuration));
            NotNull(managerConfiguration, nameof(managerConfiguration));
            NotNullOrWhiteSpace(configuration.Name, nameof(configuration.Name));

            this.Configuration = configuration;

            this.Stats = new CacheStats <TCacheValue>(
                managerConfiguration.Name,
                this.Configuration.Name,
                this.Configuration.EnableStatistics,
                this.Configuration.EnablePerformanceCounters);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RedisCacheHandle{TCacheValue}"/> class.
        /// </summary>
        /// <param name="managerConfiguration">The manager configuration.</param>
        /// <param name="configuration">The cache handle configuration.</param>
        /// <param name="loggerFactory">The logger factory.</param>
        /// <param name="serializer">The serializer.</param>
        public RedisCacheHandle(CacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory, ICacheSerializer serializer)
            : base(managerConfiguration, configuration)
        {
            NotNull(loggerFactory, nameof(loggerFactory));
            NotNull(managerConfiguration, nameof(managerConfiguration));
            NotNull(configuration, nameof(configuration));
            EnsureNotNull(serializer, "A serializer is required for the redis cache handle");

            this.managerConfiguration = managerConfiguration;
            this.Logger             = loggerFactory.CreateLogger(this);
            this.valueConverter     = new RedisValueConverter(serializer);
            this.redisConfiguration = RedisConfigurations.GetConfiguration(configuration.Key);
            this.connection         = new RedisConnectionManager(this.redisConfiguration, loggerFactory);
            this.isLuaAllowed       = this.connection.Features.Scripting;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CacheBackPlate" /> class.
        /// </summary>
        /// <param name="configuration">The cache manager configuration.</param>
        /// <param name="cacheName">The cache name.</param>
        /// <exception cref="System.ArgumentNullException">If configuration is null.</exception>
        /// <exception cref="System.ArgumentException">Parameter cacheName cannot be null or empty.</exception>
        protected CacheBackPlate(CacheManagerConfiguration configuration, string cacheName)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }
            if (string.IsNullOrWhiteSpace(cacheName))
            {
                throw new ArgumentException("Parameter cacheName cannot be null or empty.");
            }

            this.CacheConfiguration = configuration;
            this.Name      = configuration.BackPlateName;
            this.CacheName = cacheName;
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CacheBackPlate" /> class.
        /// </summary>
        /// <param name="configuration">The cache manager configuration.</param>
        /// <param name="cacheName">The cache name.</param>
        /// <exception cref="System.ArgumentNullException">If configuration is null.</exception>
        /// <exception cref="System.ArgumentException">Parameter cacheName cannot be null or empty.</exception>
        protected CacheBackPlate(CacheManagerConfiguration configuration, string cacheName)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }
            if (string.IsNullOrWhiteSpace(cacheName))
            {
                throw new ArgumentException("Parameter cacheName cannot be null or empty.");
            }

            this.CacheConfiguration = configuration;
            this.Name = configuration.BackPlateName;
            this.CacheName = cacheName;
        }
Ejemplo n.º 20
0
        public CacheManager(CacheManagerConfiguration configuration)
        {
            Contract.Requires <ArgumentNullException>(configuration != null);

            CacheConfiguration conf = configuration.CacheConfigurations[configuration.DefaultCache];

            if (!string.IsNullOrEmpty(conf.StaticInstanceProperty.Trim()))
            {
                //GetType(conf.Type).GetMethod("Run", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static).Invoke(null, null); // invoke static method
                innerCache = (ObjectCache)GetType(conf.Type).GetProperty(conf.StaticInstanceProperty, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static).GetValue(null); // get static property
            }
            else
            {
                innerCache = (string.IsNullOrEmpty(conf.Type.Trim()) ? MemoryCache.Default : (ObjectCache)System.Activator.CreateInstance(GetType(conf.Type)));
            }
        }
Ejemplo n.º 21
0
        /// <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);
        }
Ejemplo n.º 22
0
        internal static ILoggerFactory CreateLoggerFactory(CacheManagerConfiguration configuration)
        {
            NotNull(configuration, nameof(configuration));

            if (configuration.LoggerFactoryType == null)
            {
                return(new NullLoggerFactory());
            }

            CheckImplements <ILoggerFactory>(configuration.LoggerFactoryType);

            var args = new object[] { configuration };

            if (configuration.LoggerFactoryTypeArguments != null)
            {
                args = configuration.LoggerFactoryTypeArguments.Concat(args).ToArray();
            }

            return((ILoggerFactory)CreateInstance(configuration.LoggerFactoryType, args));
        }
Ejemplo n.º 23
0
        public MemcachedCacheHandle(CacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory)
            : base(managerConfiguration, configuration)
        {
            NotNull(configuration, nameof(configuration));
            NotNull(loggerFactory, nameof(loggerFactory));

            Ensure(typeof(TCacheValue).IsSerializable, "The cache value type must be serializable but {0} is not.", typeof(TCacheValue).ToString());

            this.Logger = loggerFactory.CreateLogger(this);

            // initialize memcached client with section name which must be equal to handle name...
            // Default is "enyim.com/memcached"
            try
            {
                var sectionName = GetEnyimSectionName(configuration.Key);
                this.Cache = new MemcachedClient(sectionName);
            }
            catch (ConfigurationErrorsException ex)
            {
                throw new InvalidOperationException("Failed to initialize " + this.GetType().Name + ". " + ex.BareMessage, ex);
            }
        }
        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;
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MemoryCacheHandle{TCacheValue}"/> class.
        /// </summary>
        /// <param name="managerConfiguration">The manager configuration.</param>
        /// <param name="configuration">The cache handle configuration.</param>
        /// <param name="loggerFactory">The logger factory.</param>
        public MemoryCacheHandle(CacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory)
            : base(managerConfiguration, configuration)
        {
            NotNull(configuration, nameof(configuration));
            NotNull(loggerFactory, nameof(loggerFactory));

            this.Logger    = loggerFactory.CreateLogger(this);
            this.cacheName = configuration.Name;

            if (this.cacheName.ToUpper(CultureInfo.InvariantCulture).Equals(DefaultName.ToUpper(CultureInfo.InvariantCulture)))
            {
                this.cache = MemoryCache.Default;
            }
            else
            {
                this.cache = new MemoryCache(this.cacheName);
            }

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

            this.CreateInstanceToken();
        }
Ejemplo n.º 26
0
        /// <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.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.Subscribe();
        }
Ejemplo n.º 27
0
 public SystemWebCacheHandleWrapper(CacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory)
     : base(managerConfiguration, configuration, loggerFactory)
 {
 }
Ejemplo n.º 28
0
        private static void InitializePlatform(
            IAppBuilder app,
            IUnityContainer container,
            IPathMapper pathMapper,
            string connectionString,
            HangfireLauncher hangfireLauncher,
            string modulesPath,
            ModuleInitializerOptions moduleInitializerOptions)
        {
            container.RegisterType <ICurrentUser, CurrentUser>(new HttpContextLifetimeManager());
            container.RegisterType <IUserNameResolver, UserNameResolver>();

            #region Setup database

            using (var db = new SecurityDbContext(connectionString))
            {
                new IdentityDatabaseInitializer().InitializeDatabase(db);
            }

            using (var context = new PlatformRepository(connectionString, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor()))
            {
                new PlatformDatabaseInitializer().InitializeDatabase(context);
            }

            hangfireLauncher.ConfigureDatabase();

            #endregion

            Func <IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository(connectionString, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor());
            container.RegisterType <IPlatformRepository>(new InjectionFactory(c => platformRepositoryFactory()));
            container.RegisterInstance(platformRepositoryFactory);
            var moduleCatalog = container.Resolve <IModuleCatalog>();

            #region Caching

            //Cure for System.Runtime.Caching.MemoryCache freezing
            //https://www.zpqrtbnk.net/posts/appdomains-threads-cultureinfos-and-paracetamol
            app.SanitizeThreadCulture();
            ICacheManager <object> cacheManager = null;

            var redisConnectionString = ConfigurationHelper.GetConnectionStringValue("RedisConnectionString");

            //Try to load cache configuration from web.config first
            //Should be aware to using Web cache cache handle because it not worked in native threads. (Hangfire jobs)
            if (ConfigurationManager.GetSection(CacheManagerSection.DefaultSectionName) is CacheManagerSection cacheManagerSection)
            {
                CacheManagerConfiguration configuration = null;

                var defaultCacheManager = cacheManagerSection.CacheManagers.FirstOrDefault(p => p.Name.EqualsInvariant("platformCache"));
                if (defaultCacheManager != null)
                {
                    configuration = ConfigurationBuilder.LoadConfiguration(defaultCacheManager.Name);
                }

                var redisCacheManager = cacheManagerSection.CacheManagers.FirstOrDefault(p => p.Name.EqualsInvariant("redisPlatformCache"));
                if (redisConnectionString != null && redisCacheManager != null)
                {
                    configuration = ConfigurationBuilder.LoadConfiguration(redisCacheManager.Name);
                }

                if (configuration != null)
                {
                    configuration.LoggerFactoryType          = typeof(CacheManagerLoggerFactory);
                    configuration.LoggerFactoryTypeArguments = new object[] { container.Resolve <ILog>() };
                    cacheManager = CacheFactory.FromConfiguration <object>(configuration);
                }
            }

            // Create a default cache manager if there is no any others
            if (cacheManager == null)
            {
                cacheManager = CacheFactory.Build("platformCache", settings =>
                {
                    settings.WithUpdateMode(CacheUpdateMode.Up)
                    .WithSystemRuntimeCacheHandle("memCacheHandle")
                    .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromMinutes(5));
                });
            }

            container.RegisterInstance(cacheManager);

            #endregion

            #region Settings

            var platformModuleManifest = new ModuleManifest
            {
                Id              = "VirtoCommerce.Platform",
                Version         = PlatformVersion.CurrentVersion.ToString(),
                PlatformVersion = PlatformVersion.CurrentVersion.ToString(),
                Settings        = new[]
                {
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SendGrid",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SendGrid.ApiKey",
                                ValueType   = ModuleSetting.TypeSecureString,
                                Title       = "SendGrid API key",
                                Description = "Your SendGrid API key"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SendingJob",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SendingJob.TakeCount",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Job Take Count",
                                Description = "Take count for sending job"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SmtpClient",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Host",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Smtp server host",
                                Description = "Smtp server host"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Port",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Smtp server port",
                                Description = "Smtp server port"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Login",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Smtp server login",
                                Description = "Smtp server login"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Password",
                                ValueType   = ModuleSetting.TypeSecureString,
                                Title       = "Smtp server password",
                                Description = "Smtp server password"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.UseSsl",
                                ValueType   = ModuleSetting.TypeBoolean,
                                Title       = "Use SSL",
                                Description = "Use secure connection"
                            },
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Security",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.Security.AccountTypes",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Account types",
                                Description  = "Dictionary for possible account types",
                                IsArray      = true,
                                ArrayValues  = Enum.GetNames(typeof(AccountType)),
                                DefaultValue = AccountType.Manager.ToString()
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|User Profile",
                        Settings = new[]
                        {
                            new ModuleSetting
                            {
                                Name      = "VirtoCommerce.Platform.UI.MainMenu.State",
                                ValueType = ModuleSetting.TypeJson,
                                Title     = "Persisted state of main menu"
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.Language",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Language",
                                Description  = "Default language (two letter code from ISO 639-1, case-insensitive). Example: en, de",
                                DefaultValue = "en"
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.RegionalFormat",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Regional format",
                                Description  = "Default regional format (CLDR locale code, with dash or underscore as delemiter, case-insensitive). Example: en, en_US, sr_Cyrl, sr_Cyrl_RS",
                                DefaultValue = "en"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.UI.TimeZone",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Time zone",
                                Description = "Default time zone (IANA time zone name [tz database], exactly as in database, case-sensitive). Examples: America/New_York, Europe/Moscow"
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.ShowMeridian",
                                ValueType    = ModuleSetting.TypeBoolean,
                                Title        = "Meridian labels based on user preferences",
                                Description  = "When set to true (by default), system will display time in format like '12 hour format' when possible",
                                DefaultValue = true.ToString()
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.UseTimeAgo",
                                ValueType    = ModuleSetting.TypeBoolean,
                                Title        = "Use time ago format when is possible",
                                Description  = "When set to true (by default), system will display date in format like 'a few seconds ago' when possible",
                                DefaultValue = true.ToString()
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.UI.FullDateThreshold",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Full date threshold",
                                Description = "Number of units after time ago format will be switched to full date format"
                            },
                            new ModuleSetting
                            {
                                Name          = "VirtoCommerce.Platform.UI.FullDateThresholdUnit",
                                ValueType     = ModuleSetting.TypeString,
                                Title         = "Full date threshold unit",
                                Description   = "Unit of full date threshold",
                                DefaultValue  = "Never",
                                AllowedValues = new[]
                                {
                                    "Never",
                                    "Seconds",
                                    "Minutes",
                                    "Hours",
                                    "Days",
                                    "Weeks",
                                    "Months",
                                    "Quarters",
                                    "Years"
                                }
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.FourDecimalsInMoney",
                                ValueType    = ModuleSetting.TypeBoolean,
                                Title        = "Show 4 decimal digits for money",
                                Description  = "Set to true to show 4 decimal digits for money. By default - false, 2 decimal digits are shown.",
                                DefaultValue = "false",
                            },
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|User Interface",
                        Settings = new[]
                        {
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.Customization",
                                ValueType    = ModuleSetting.TypeJson,
                                Title        = "Customization",
                                Description  = "JSON contains personalization settings of manager UI",
                                DefaultValue = "{\n" +
                                               "  \"title\": \"Virto Commerce\",\n" +
                                               "  \"logo\": \"Content/themes/main/images/logo.png\",\n" +
                                               "  \"contrast_logo\": \"Content/themes/main/images/contrast-logo.png\",\n" +
                                               "  \"favicon\": \"favicon.ico\"\n" +
                                               "}"
                            }
                        }
                    }
                }
            };

            var settingsManager = new SettingsManager(moduleCatalog, platformRepositoryFactory, cacheManager, new[] { new ManifestModuleInfo(platformModuleManifest) });
            container.RegisterInstance <ISettingsManager>(settingsManager);

            #endregion

            #region Dynamic Properties

            container.RegisterType <IDynamicPropertyService, DynamicPropertyService>(new ContainerControlledLifetimeManager());

            #endregion

            #region Notifications

            // Redis
            if (!string.IsNullOrEmpty(redisConnectionString))
            {
                // Cache
                RedisConfigurations.AddConfiguration(new RedisConfiguration("redisConnectionString", redisConnectionString));

                // SignalR
                // https://stackoverflow.com/questions/29885470/signalr-scaleout-on-azure-rediscache-connection-issues
                GlobalHost.DependencyResolver.UseRedis(new RedisScaleoutConfiguration(redisConnectionString, "VirtoCommerce.Platform.SignalR"));
            }

            // SignalR
            var tempCounterManager = new TempPerformanceCounterManager();
            GlobalHost.DependencyResolver.Register(typeof(IPerformanceCounterManager), () => tempCounterManager);
            var hubConfiguration = new HubConfiguration {
                EnableJavaScriptProxies = false
            };
            app.MapSignalR("/" + moduleInitializerOptions.RoutePrefix + "signalr", hubConfiguration);

            var hubSignalR = GlobalHost.ConnectionManager.GetHubContext <ClientPushHub>();
            var notifier   = new InMemoryPushNotificationManager(hubSignalR);
            container.RegisterInstance <IPushNotificationManager>(notifier);

            var resolver = new LiquidNotificationTemplateResolver();
            container.RegisterInstance <INotificationTemplateResolver>(resolver);

            var notificationTemplateService = new NotificationTemplateServiceImpl(platformRepositoryFactory);
            container.RegisterInstance <INotificationTemplateService>(notificationTemplateService);

            var notificationManager = new NotificationManager(resolver, platformRepositoryFactory, notificationTemplateService);
            container.RegisterInstance <INotificationManager>(notificationManager);

            IEmailNotificationSendingGateway emailNotificationSendingGateway = null;

            var emailNotificationSendingGatewayName = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:Gateway", "Default");

            if (string.Equals(emailNotificationSendingGatewayName, "Default", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new DefaultSmtpEmailNotificationSendingGateway(settingsManager);
            }
            else if (string.Equals(emailNotificationSendingGatewayName, "SendGrid", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new SendGridEmailNotificationSendingGateway(settingsManager);
            }

            if (emailNotificationSendingGateway != null)
            {
                container.RegisterInstance(emailNotificationSendingGateway);
            }

            ISmsNotificationSendingGateway smsNotificationSendingGateway = null;
            var smsNotificationSendingGatewayName = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:SmsGateway", "Default");

            if (smsNotificationSendingGatewayName.EqualsInvariant("Default"))
            {
                smsNotificationSendingGateway = new DefaultSmsNotificationSendingGateway();
            }
            else if (smsNotificationSendingGatewayName.EqualsInvariant("Twilio"))
            {
                smsNotificationSendingGateway = new TwilioSmsNotificationSendingGateway(new TwilioSmsGatewayOptions
                {
                    AccountId       = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:SmsGateway:AccountId"),
                    AccountPassword = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:SmsGateway:AccountPassword"),
                    Sender          = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:SmsGateway:Sender"),
                });
            }
            else if (smsNotificationSendingGatewayName.EqualsInvariant("ASPSMS"))
            {
                smsNotificationSendingGateway = new AspsmsSmsNotificationSendingGateway(new AspsmsSmsGatewayOptions
                {
                    AccountId       = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:SmsGateway:AccountId"),
                    AccountPassword = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:SmsGateway:AccountPassword"),
                    Sender          = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:SmsGateway:Sender"),
                    JsonApiUri      = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:SmsGateway:ASPSMS:JsonApiUri"),
                });
            }

            if (smsNotificationSendingGateway != null)
            {
                container.RegisterInstance(smsNotificationSendingGateway);
            }

            #endregion

            #region Assets

            var blobConnectionString = BlobConnectionString.Parse(ConfigurationHelper.GetConnectionStringValue("AssetsConnectionString"));

            if (string.Equals(blobConnectionString.Provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var fileSystemBlobProvider = new FileSystemBlobProvider(NormalizePath(pathMapper, blobConnectionString.RootPath), blobConnectionString.PublicUrl);

                container.RegisterInstance <IBlobStorageProvider>(fileSystemBlobProvider);
                container.RegisterInstance <IBlobUrlResolver>(fileSystemBlobProvider);
            }
            else if (string.Equals(blobConnectionString.Provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var azureBlobProvider = new AzureBlobProvider(blobConnectionString.ConnectionString, blobConnectionString.CdnUrl);
                container.RegisterInstance <IBlobStorageProvider>(azureBlobProvider);
                container.RegisterInstance <IBlobUrlResolver>(azureBlobProvider);
            }

            container.RegisterType <IAssetEntryService, AssetEntryService>(new ContainerControlledLifetimeManager());
            container.RegisterType <IAssetEntrySearchService, AssetEntryService>(new ContainerControlledLifetimeManager());

            #endregion

            #region Modularity

            var modulesDataSources    = ConfigurationHelper.SplitAppSettingsStringValue("VirtoCommerce:ModulesDataSources");
            var externalModuleCatalog = new ExternalManifestModuleCatalog(moduleCatalog.Modules, modulesDataSources, container.Resolve <ILog>());
            container.RegisterType <ModulesController>(new InjectionConstructor(externalModuleCatalog, new ModuleInstaller(modulesPath, externalModuleCatalog), notifier, container.Resolve <IUserNameResolver>(), settingsManager));

            #endregion

            #region ChangeLogging

            var changeLogService = new ChangeLogService(platformRepositoryFactory);
            container.RegisterInstance <IChangeLogService>(changeLogService);

            #endregion

            #region Security
            container.RegisterInstance <IPermissionScopeService>(new PermissionScopeService());
            container.RegisterType <IRoleManagementService, RoleManagementService>(new ContainerControlledLifetimeManager());

            var apiAccountProvider = new ApiAccountProvider(platformRepositoryFactory, cacheManager);
            container.RegisterInstance <IApiAccountProvider>(apiAccountProvider);

            container.RegisterType <IClaimsIdentityProvider, ApplicationClaimsIdentityProvider>(new ContainerControlledLifetimeManager());

            container.RegisterInstance(app.GetDataProtectionProvider());
            container.RegisterType <SecurityDbContext>(new InjectionConstructor(connectionString));
            container.RegisterType <IUserStore <ApplicationUser>, ApplicationUserStore>();
            container.RegisterType <IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
            container.RegisterType <ApplicationUserManager>();
            container.RegisterType <ApplicationSignInManager>();

            var nonEditableUsers = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:NonEditableUsers", string.Empty);
            container.RegisterInstance <ISecurityOptions>(new SecurityOptions(nonEditableUsers));

            container.RegisterType <ISecurityService, SecurityService>();

            container.RegisterType <IPasswordCheckService, PasswordCheckService>();

            #endregion

            #region ExportImport
            container.RegisterType <IPlatformExportImportManager, PlatformExportImportManager>();
            #endregion

            #region Serialization

            container.RegisterType <IExpressionSerializer, XmlExpressionSerializer>();

            #endregion

            #region Events
            var inProcessBus = new InProcessBus();
            container.RegisterInstance <IHandlerRegistrar>(inProcessBus);
            container.RegisterInstance <IEventPublisher>(inProcessBus);

            inProcessBus.RegisterHandler <UserChangedEvent>(async(message, token) => await container.Resolve <LogChangesUserChangedEventHandler>().Handle(message));
            inProcessBus.RegisterHandler <UserPasswordChangedEvent>(async(message, token) => await container.Resolve <LogChangesUserChangedEventHandler>().Handle(message));
            inProcessBus.RegisterHandler <UserResetPasswordEvent>(async(message, token) => await container.Resolve <LogChangesUserChangedEventHandler>().Handle(message));
            #endregion
        }
Ejemplo n.º 29
0
 public RedisCacheHandle2(CacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ILoggerFactory loggerFactory, ICacheSerializer serializer)
     : base(managerConfiguration, configuration, loggerFactory, serializer)
 {
 }
Ejemplo n.º 30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CacheBackPlate" /> class.
 /// </summary>
 /// <param name="configuration">The cache manager configuration.</param>
 /// <exception cref="System.ArgumentNullException">If configuration is null.</exception>
 protected CacheBackPlate(CacheManagerConfiguration configuration)
 {
     NotNull(configuration, nameof(configuration));
     this.CacheConfiguration = configuration;
     this.ConfigurationKey = configuration.BackPlateConfigurationKey;
 }
Ejemplo n.º 31
0
 public SerializerTestCacheHandle(CacheManagerConfiguration managerConfiguration, CacheHandleConfiguration configuration, ICacheSerializer serializer)
     : base(managerConfiguration, configuration)
 {
     this.Serializer = serializer;
 }
Ejemplo n.º 32
0
        public void Main(string[] args)
        {
            int iterations = int.MaxValue;

            try
            {
                var builder = new Core.ConfigurationBuilder("myCache");
                builder.WithMicrosoftLogging(f =>
                {
                    // TODO: remove after logging upgrade to RC2
                    f.MinimumLevel = LogLevel.Debug;

                    f.AddConsole(LogLevel.Error);

                    // TODO: change to Debug after logging upgrade to RC2
                    f.AddDebug(LogLevel.Verbose);
                });

                builder.WithUpdateMode(CacheUpdateMode.Up);
                builder.WithRetryTimeout(1000);
                builder.WithMaxRetries(10);

#if DNXCORE50
                builder.WithDictionaryHandle("dic")
                .DisableStatistics();

                //Console.WriteLine("Using Dictionary cache handle");
#else
                builder.WithDictionaryHandle()
                .DisableStatistics();

                builder.WithRedisCacheHandle("redis", true)
                .DisableStatistics();

                builder.WithRedisBackPlate("redis");

                builder.WithRedisConfiguration("redis", config =>
                {
                    config
                    .WithAllowAdmin()
                    .WithDatabase(0)
                    .WithConnectionTimeout(5000)
                    .WithEndpoint("127.0.0.1", 6380)
                    .WithEndpoint("127.0.0.1", 6379);
                    //.WithEndpoint("192.168.178.34", 7001);
                });

                builder.WithJsonSerializer();

                Console.WriteLine("Using Redis cache handle");
#endif
                var cacheA = new BaseCacheManager <object>(builder.Build());
                cacheA.Clear();

                var manualConfig = new CacheManagerConfiguration();
                manualConfig.CacheHandleConfigurations.Add(new CacheHandleConfiguration()
                {
                    HandleType = typeof(Core.Internal.DictionaryCacheHandle <>)
                });
                var cacheB = new BaseCacheManager <string>("name", manualConfig);

                for (int i = 0; i < iterations; i++)
                {
                    try
                    {
                        Tests.PutAndMultiGetTest(cacheA);
                    }
                    catch (AggregateException ex)
                    {
                        ex.Handle((e) =>
                        {
                            Console.WriteLine(e);
                            return(true);
                        });
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error: " + e.Message + "\n" + e.StackTrace);
                        Thread.Sleep(1000);
                    }

                    Console.WriteLine("---------------------------------------------------------");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine("We are done...");
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.ReadKey();
        }