public BackupSyncSettingsService(IPersistentKeyValueCache cache, IBackupSyncTargetsJsonSerializer serializer)
        {
            _cache      = cache;
            _serializer = serializer;

            LoadData();
        }
예제 #2
0
 public RelationalDatabaseWrapper(string connectionString, IKeyValueCache cache, string rootQueriesDir, ILogger logger)
 {
     _connectionString = connectionString;
     _cache            = cache;
     _rootQueriesDir   = rootQueriesDir;
     _logger           = logger;
 }
예제 #3
0
        /// <summary>
        /// 初始化
        /// </summary>
        public GenericConfigManager()
        {
            var cacheFactory = Application.Ioc.Resolve <ICacheFactory>();

            AttributeCache   = new ConcurrentDictionary <Type, GenericConfigAttribute>();
            ConfigValueCache = cacheFactory.CreateCache <Type, object>();
        }
예제 #4
0
 /// <summary>
 /// Initialize
 /// </summary>
 /// <param name="isolationPolicies">Cache isolation policies</param>
 /// <param name="underlyingCache">Underlying cache</param>
 public IsolatedKeyValueCache(
     IList <ICacheIsolationPolicy> isolationPolicies,
     IKeyValueCache <IsolatedCacheKey <TKey>, TValue> underlyingCache)
 {
     IsolationPolicies = isolationPolicies;
     UnderlyingCache   = underlyingCache;
 }
예제 #5
0
        //--- Extension Methods ---

        /// <summary>
        /// Retrieve a value from the cache.
        /// </summary>
        /// <typeparam name="T">Type the value to be returned.</typeparam>
        /// <param name="cache">The cache instance to operate on.</param>
        /// <param name="key">Key to identify the value by.</param>
        /// <returns>The cached value or <see langword="null"/> if the value is not in cache.</returns>
        public static T Get <T>(this IKeyValueCache cache, string key)
        {
            T ret;

            cache.TryGet(key, out ret);
            return(ret);
        }
예제 #6
0
        /// <summary>
        /// Render widget
        /// Return render result
        /// </summary>
        /// <param name="context">Template context</param>
        /// <param name="widget">Template widget</param>
        /// <returns></returns>
        public virtual string RenderWidget(Context context, TemplateWidget widget)
        {
            // Get from cache
            var info = GetWidgetInfo(widget.Path);
            IKeyValueCache <string, string> renderCache = null;
            string key          = widget.GetCacheKey();
            string renderResult = null;

            if (info.CacheTime > 0)
            {
                renderCache = WidgetRenderCache.GetOrAdd(info.CacheBy ?? "", _ => {
                    var cacheFactory = Application.Ioc.Resolve <ICacheFactory>();
                    var policyNames  = info.GetCacheIsolationPolicyNames();
                    return(cacheFactory.CreateCache <string, string>(
                               CacheFactoryOptions.Default.WithIsolationPolicies(policyNames)));
                });
                renderResult = renderCache.GetOrDefault(key);
                if (renderResult != null)
                {
                    return(renderResult);
                }
            }
            // Render widget
            var renderer = Application.Ioc.Resolve <ITemplateWidgetRenderer>();

            renderResult = renderer.Render(context, widget);
            // Store to cache
            if (info.CacheTime > 0)
            {
                renderCache.Put(key, renderResult, TimeSpan.FromSeconds(info.CacheTime));
            }
            return(renderResult);
        }
예제 #7
0
        public static async Task <string> GetString(this IKeyValueCache cache, string key)
        {
            var bytes = await cache.GetBytes(key);

            var str = Encoding.UTF8.GetString(bytes);

            return(str);
        }
예제 #8
0
		/// <summary>
		/// Initialize
		/// </summary>
		public TranslateManager() {
			var configManager = Application.Ioc.Resolve<WebsiteConfigManager>();
			var cacheFactory = Application.Ioc.Resolve<ICacheFactory>();
			TranslateCacheTime = TimeSpan.FromSeconds(
				configManager.WebsiteConfig.Extra.GetOrDefault(ExtraConfigKeys.TranslateCacheTime, 3));
			TranslateCache = cacheFactory.CreateCache<Pair<string, string>, string>();
			TranslateProvidersCache = cacheFactory.CreateCache<string, List<ITranslateProvider>>();
		}
예제 #9
0
		/// <summary>
		/// 初始化
		/// </summary>
		public VisualWidgetManager() {
			var configManager = Application.Ioc.Resolve<WebsiteConfigManager>();
			var cacheFactory = Application.Ioc.Resolve<ICacheFactory>();
			var extra = configManager.WebsiteConfig.Extra;
			WidgetsCacheTime = TimeSpan.FromSeconds(extra.GetOrDefault(
				VisualEditorExtraConfigKeys.WidgetsCacheTime, 15));
			WidgetsCache = cacheFactory.CreateCache<int, IList<VisualWidgetGroup>>();
		}
예제 #10
0
 public TranslationRepository(
     ISession session,
     IKeyValueCache keyValueCache
     )
 {
     _session       = session;
     _keyValueCache = keyValueCache;
 }
 public TranslationRepository(
     ISession session,
     IKeyValueCache keyValueCache
 )
 {
     _session = session;
     _keyValueCache = keyValueCache;
 }
예제 #12
0
        /// <summary>
        /// Initialize
        /// </summary>
        public TemplateFileSystem()
        {
            var configManager = Application.Ioc.Resolve <WebsiteConfigManager>();
            var cacheFactory  = Application.Ioc.Resolve <ICacheFactory>();

            TemplateCacheTime = TimeSpan.FromSeconds(
                configManager.WebsiteConfig.Extra.GetOrDefault(ExtraConfigKeys.TemplateCacheTime, 180));
            TemplateCache = cacheFactory.CreateCache <string, Pair <Template, DateTime> >();
        }
예제 #13
0
 public WeatherForecastController(
     ILogger <WeatherForecastController> logger,
     IKeyValueCache <string, IChannel> channelCache,
     IZaabeeRabbitMqClient mqClient)
 {
     _logger       = logger;
     _channelCache = channelCache;
     _mqClient     = mqClient;
 }
예제 #14
0
 public MongoDatabaseStorage(IMongoDatabase db, MongoDatabaseStorageInitOptions opt = null, IKeyValueCache cache = null)
 {
     opt ??= new MongoDatabaseStorageInitOptions();
     _useCache       = opt.UseCache;
     _cache          = cache ?? new RamCache(1000);
     _db             = db;
     _collectionName = opt.CollectionName;
     _collection     = _db.GetCollection <BsonDocument>(_collectionName);
     _collection.EnsureIndex("key").Wait();
 }
        /// <summary>
        /// 初始化
        /// </summary>
        public ProductPropertyManager()
        {
            var configManager = Application.Ioc.Resolve <WebsiteConfigManager>();
            var cacheFactory  = Application.Ioc.Resolve <ICacheFactory>();
            var extra         = configManager.WebsiteConfig.Extra;

            CategoryCacheTime = TimeSpan.FromSeconds(extra.GetOrDefault(
                                                         ProductExtraConfigKeys.ProductCategoryCacheTime, 180));
            PropertyListCache = cacheFactory.CreateCache <int, List <ProductProperty> >();
        }
예제 #16
0
        /// <summary>
        /// 初始化
        /// </summary>
        public PaymentApiManager()
        {
            var configManager = Application.Ioc.Resolve <WebsiteConfigManager>();
            var cacheFactory  = Application.Ioc.Resolve <ICacheFactory>();
            var extra         = configManager.WebsiteConfig.Extra;

            PaymentApiCacheTime = TimeSpan.FromSeconds(extra.GetOrDefault(
                                                           PaymentExtraConfigKeys.PaymentApiCacheTime, 3));
            PaymentApiCache  = cacheFactory.CreateCache <Guid, PaymentApi>();
            PaymentApisCache = cacheFactory.CreateCache <Pair <Guid, string>, IList <PaymentApi> >();
        }
예제 #17
0
        /// <summary>
        /// 初始化
        /// </summary>
        public GenericTagManager()
        {
            var configManager = Application.Ioc.Resolve <WebsiteConfigManager>();
            var cacheFactory  = Application.Ioc.Resolve <ICacheFactory>();
            var extra         = configManager.WebsiteConfig.Extra;

            TagCacheTime = TimeSpan.FromSeconds(extra.GetOrDefault(
                                                    GenericTagExtraConfigKeys.TagCacheTime, 15));
            TagCache     = cacheFactory.CreateCache <Guid, Entities.GenericTag>();
            TagListCache = cacheFactory.CreateCache <string, IList <Entities.GenericTag> >();
        }
예제 #18
0
        /// <summary>
        /// 初始化
        /// </summary>
        public LogisticsManager()
        {
            var configManager = Application.Ioc.Resolve <WebsiteConfigManager>();
            var cacheFactory  = Application.Ioc.Resolve <ICacheFactory>();
            var extra         = configManager.WebsiteConfig.Extra;

            LogisticsCacheTime = TimeSpan.FromSeconds(extra.GetOrDefault(
                                                          LogisticsExtraConfigKeys.LogisticsCacheTime, 3));
            LogisticsCache     = cacheFactory.CreateCache <Guid, Entities.Logistics>();
            LogisticsListCache = cacheFactory.CreateCache <Guid, IList <Entities.Logistics> >();
        }
예제 #19
0
 /// <summary>
 /// Инициализирует экземпляр <see cref="InvocationWeaveDataProviderFactory"/>.
 /// </summary>
 public InvocationWeaveDataProviderFactory(
     IComponentHolder <IAspectWeavePredicate> weavePredicateHolder,
     IComponentHolder <IAspectFactory> preInitializerHolder,
     IComponentHolder <IInvocationPipelineFactory> pipelineFactoryHolder,
     IKeyValueCacheFactory cacheFactory)
 {
     _weavePredicateHolder  = weavePredicateHolder;
     _preInitializerHolder  = preInitializerHolder;
     _pipelineFactoryHolder = pipelineFactoryHolder;
     _providerCache         = cacheFactory.Create <TypePair, IInvocationWeaveDataProvider>();
 }
예제 #20
0
 public static async Task SetString(this IKeyValueCache cache, string key, string str, DateTime?expiresIn = null)
 {
     if (str == null)
     {
         await cache.Remove(key);
     }
     else
     {
         var bytes = Encoding.UTF8.GetBytes(str);
         await cache.SetBytes(key, bytes, expiresIn);
     }
 }
예제 #21
0
        /// <summary>
        /// Get cached value<br/>
        /// Return default value if no exist value or exist value expired<br/>
        /// 获取缓存值<br/>
        /// 如果值不存在或已过期则返回默认值<br/>
        /// </summary>
        /// <param name="cache">Cache</param>
        /// <param name="key">Key</param>
        /// <param name="defaultValue">The default value</param>
        /// <returns></returns>
        /// <example>
        /// <code language="cs">
        /// var cache = new MemoryCache&lt;int, string&gt;();
        /// var cached = cache.GetOrDefault(1, "default");
        /// </code>
        /// </example>
        public static TValue GetOrDefault <TKey, TValue>(
            this IKeyValueCache <TKey, TValue> cache,
            TKey key, TValue defaultValue = default(TValue))
        {
            TValue value;

            if (cache.TryGetValue(key, out value))
            {
                return(value);
            }
            return(defaultValue);
        }
예제 #22
0
 //--- Constructors ---
 public SearchBL(IDekiDataSession session, IKeyValueCache cache, string wikiid, XUri apiUri, Plug searchPlug, UserBE user, IInstanceSettings settings, SearchQueryParser parser, Func <bool> adaptiveSearchEnabled, ILog log)
 {
     _log                   = log;
     _session               = session;
     _cache                 = cache;
     _wikiid                = wikiid;
     _apiUri                = apiUri;
     _searchPlug            = searchPlug;
     _user                  = user;
     _settings              = settings;
     _parser                = parser;
     _adaptiveSearchEnabled = adaptiveSearchEnabled;
 }
예제 #23
0
        public static async Task <string> TryGetString(this IKeyValueCache cache, string key)
        {
            try
            {
                var str = await cache.GetString(key);

                return(str);
            }
            catch
            {
                return(null);
            }
        }
예제 #24
0
        public static async Task <byte[]> TryGetBytes(this IKeyValueCache cache, string key)
        {
            try
            {
                var bytes = await cache.GetBytes(key);

                return(bytes);
            }
            catch
            {
                return(null);
            }
        }
 public ClipboardDataControlPackageFactory(
     IEnumerable<IClipboardDataControlFactory> dataFactories,
     IEnumerable<IMemoryUnwrapper> memoryUnwrappers,
     IKeyValueCache<uint, byte[]> clipboardCache,
     IClipboardHandleFactory clipboardSessionFactory,
     IUserInterfaceThread userInterfaceThread)
 {
     this.dataFactories = dataFactories;
     this.memoryUnwrappers = memoryUnwrappers;
     this.clipboardCache = clipboardCache;
     this.clipboardSessionFactory = clipboardSessionFactory;
     this.userInterfaceThread = userInterfaceThread;
 }
예제 #26
0
        /// <summary>
        /// Get cached value<br/>
        /// Generate a new value and store it to cache if the no exist value or exist value expired<br/>
        /// Attention: This is not an atomic operation<br/>
        /// 获取缓存值<br/>
        /// 如果值不存在或已过期则创建一个新的值并储存<br/>
        /// 注意: 这不是原子操作</summary>
        /// <param name="cache">Cache</param>
        /// <param name="key">Key</param>
        /// <param name="creator">Function to create default value</param>
        /// <param name="keepTime">Keep time</param>
        /// <returns></returns>
        /// <example>
        /// <code language="cs">
        /// var cache = new MemoryCache&lt;int, string&gt;();
        /// var cached = cache.GetOrDefault(1, () =&gt; "123", TimeSpan.FromSeconds(100));
        /// </code>
        /// </example>
        public static TValue GetOrCreate <TKey, TValue>(
            this IKeyValueCache <TKey, TValue> cache,
            TKey key, Func <TValue> creator, TimeSpan keepTime)
        {
            TValue value;

            if (keepTime == TimeSpan.Zero || !cache.TryGetValue(key, out value))
            {
                value = creator();
                cache.Put(key, value, keepTime);
            }
            return(value);
        }
예제 #27
0
 public ClipboardDataControlPackageFactory(
     IEnumerable <IClipboardDataControlFactory> dataFactories,
     IEnumerable <IMemoryUnwrapper> memoryUnwrappers,
     IKeyValueCache <uint, byte[]> clipboardCache,
     IClipboardHandleFactory clipboardSessionFactory,
     IUserInterfaceThread userInterfaceThread)
 {
     this.dataFactories           = dataFactories;
     this.memoryUnwrappers        = memoryUnwrappers;
     this.clipboardCache          = clipboardCache;
     this.clipboardSessionFactory = clipboardSessionFactory;
     this.userInterfaceThread     = userInterfaceThread;
 }
        public ActiveWindowService(
            IWindowNativeApi windowNativeApi,
            IWindowThreadMerger windowThreadMerger,
            IProcessManager processManager,
            IKeyValueCache <IntPtr, Process> windowProcessCache)
        {
            this.windowNativeApi    = windowNativeApi;
            this.windowThreadMerger = windowThreadMerger;
            this.processManager     = processManager;
            this.windowProcessCache = windowProcessCache;

            callbackPointer = OnWindowChanged;
            GC.KeepAlive(callbackPointer);
        }
예제 #29
0
        public LiteDatabaseStorage(LiteDatabaseStorageInitOptions opt = null, IKeyValueCache cache = null)
        {
            opt ??= new LiteDatabaseStorageInitOptions();
            _useCache = opt.UseCache;
            _cache    = cache ?? new RamCache(1000);

            _collectionName = opt.CollectionName;
            _dbFilePath     = opt.DbFilePath;
            using (var _db = new LiteDatabase(_dbFilePath))
            {
                var _collection = _db.GetCollection <BsonDocument>(_collectionName);
                _collection.EnsureIndex("_id");
            }
        }
예제 #30
0
        public DataSourceService(
            IImagePersistenceService imagePersistenceService,
            IActiveWindowService activeWindowService,
            IWindowNativeApi windowNativeApi,
            IKeyValueCache <IntPtr, byte[]> dataSourceIconCacheSmall,
            IKeyValueCache <IntPtr, byte[]> dataSourceIconCacheLarge)
        {
            this.imagePersistenceService = imagePersistenceService;
            this.activeWindowService     = activeWindowService;
            this.windowNativeApi         = windowNativeApi;

            this.dataSourceIconCacheLarge = dataSourceIconCacheLarge;
            this.dataSourceIconCacheSmall = dataSourceIconCacheSmall;
        }
예제 #31
0
        /// <summary>
        /// 初始化
        /// </summary>
        public ArticleManager()
        {
            var configManager = Application.Ioc.Resolve <WebsiteConfigManager>();
            var extra         = configManager.WebsiteConfig.Extra;
            var cacheFactory  = Application.Ioc.Resolve <ICacheFactory>();

            ArticleApiInfoCacheTime = TimeSpan.FromSeconds(extra.GetOrDefault(
                                                               ArticleExtraConfigKeys.ArticleApiInfoCacheTime, 15));
            ArticleApiInfoCache = cacheFactory.CreateCache <Guid, object>(
                CacheFactoryOptions.Default.WithIsolationPolicies("Ident", "Locale"));
            ArticleSearchResultCacheTime = TimeSpan.FromSeconds(extra.GetOrDefault(
                                                                    ArticleExtraConfigKeys.ArticleSearchResultCacheTime, 15));
            ArticleSearchResultCache = cacheFactory.CreateCache <int, StaticTableSearchResponse>(
                CacheFactoryOptions.Default.WithIsolationPolicies("Ident", "Locale", "Url"));
        }
예제 #32
0
        /// <summary>
        /// 初始化
        /// </summary>
        public ImageManager()
        {
            var configManager = Application.Ioc.Resolve <WebsiteConfigManager>();
            var cacheFactory  = Application.Ioc.Resolve <ICacheFactory>();
            var extra         = configManager.WebsiteConfig.Extra;

            ImageQuality            = 90;
            ImageExtension          = ".jpg";
            ImageThumbnailExtension = ".thumb.jpg";
            ImageBasePathFormat     = "/static/cms.image_browser.images/{0}";
            ImageThumbnailSize      = new Size(135, 135);
            ImageNamesCacheTime     = TimeSpan.FromSeconds(extra.GetOrDefault(
                                                               ImageBrowserExtraConfigKeys.ImageNamesCacheTime, 15));
            ImageNamesCache = cacheFactory.CreateCache <string, List <string> >();
        }
예제 #33
0
        //--- Constructor ---
        public DekiInstance(DekiWikiService deki, string id, XDoc instanceConfig) {
            if(deki == null) {
                throw new ArgumentNullException("deki");
            }
            if(string.IsNullOrEmpty(id)) {
                throw new ArgumentNullException("id");
            }

            this.Id = id;
            this.TimerFactory = TaskTimerFactory.Create(this);
            this.Cache = new DreamCache(TimerFactory);
            var cacheFactory = new InMemoryKeyValueCacheFactory(TimerFactory);
            var searchSerializer = new SearchSerializer();
            cacheFactory.SetSerializer<SearchResult>(searchSerializer);
            cacheFactory.SetSerializer<SearchResultDetail>(searchSerializer);
            this.SearchCache = cacheFactory.Create();
            this.Config = instanceConfig;
            this.Log = LogManager.GetLogger(deki.GetType().Name + "_" + id);
            _deki = deki;
            _status = DekiInstanceStatus.CREATED;
            foreach(XDoc hostDoc in Config["host"]) {
                string host = hostDoc.Contents;
                if(!StringUtil.EqualsInvariantIgnoreCase(host, "*")) {
                    string port = hostDoc["@port"].AsText;
                    string scheme = hostDoc["@https"].AsBool.GetValueOrDefault() ? "https://" : "http://";
                    string uri = scheme + host + (string.IsNullOrEmpty(port) ? "" : ":" + port);
                    _canonicalUri = new XUri(uri);
                    _log.DebugFormat("divined canonical use from hosts as {0}", _canonicalUri);
                    break;
                }
            }
            if(_canonicalUri == null) {

                // Note (arnec): this is a best guess fallback. It will only work in these scenarios:
                // a) The host was set up with a uri.public that has ends in @api and with the @api points to the site uri, or
                // b) The api lives on the same machine as the site, so that deriving uri.public for the host from the machine
                // IP happens to point to the same machine
                // Either way it relies on the hard-coded assumption that the api is accessible via {site}/@api
                _canonicalUri = DreamContext.Current.ServerUri;
                if(_canonicalUri.LastSegment.EqualsInvariantIgnoreCase("@api")) {
                    _canonicalUri = _canonicalUri.WithoutLastSegment();
                }
                _log.DebugFormat("using server uri as canonical uri: {0}", _canonicalUri);
            } else {

                // Note (arnec): Propagating a much hard-coded assumption, i.e. that the Api for any Deki instance can be accessed
                // at the instances' canonical uri plus @api

                // register the api uri with the dream host so that requests originating from within Dream are guaranteed to be locally routed
                _deki.Env.At("status", "aliases").Post(new XDoc("aliases").Elem("uri.alias", _canonicalUri.At("@api")), new Result<DreamMessage>());
            }
        }
예제 #34
0
 public DomainNameResolver(
     IKeyValueCache<string, IPAddress[]> domainResolveCache)
 {
     this.domainResolveCache = domainResolveCache;
 }