Example #1
0
 public MemoryAdapter(CacheSettings cacheSettings)
 {
     CacheSettings = cacheSettings;
     _memoryCache = new MemoryCache(cacheSettings.Name);
     _expirationType = cacheSettings.ExpirationType;
     _minutesToExpire = cacheSettings.TimeToLive;
 }
Example #2
0
 /// <summary>
 /// Initializing caching mechanism
 /// </summary>
 /// <param name="expirationType"></param>
 /// <param name="expirationPattern">Format shoud be in hh:mm:ss - for example 01:15:00</param>
 /// <param name="isUserContextAware">if [true] UserId will be added to cache key</param>
 /// <param name="prefix">if [null] fully qualified class name will be used for prefix</param>
 public CacheInterceptorAttribute(ExpirationType expirationType, string expirationPattern, string prefix = null, bool isUserContextAware = false)
 {
     _expirationType     = expirationType;
     _expirationPattern  = expirationPattern;
     _isUserContextAware = isUserContextAware;
     _prefix             = prefix;
 }
Example #3
0
        public async Task CacheInterceptorOptionsConfigured(ExpirationType expirationType, int seconds)
        {
            // Arrange
            var cacheValue = Guid.NewGuid().ToString();
            var cache      = Substitute.For <ICache>();

            cache.GetOrCreateAsync(Arg.Any <string>(),
                                   Arg.Any <CacheEntryOptions>(),
                                   Arg.Any <Func <string, Task <string> > >()
                                   )
            .Returns(cacheValue);

            var target = new Service(Guid.NewGuid().ToString());

            var serviceProvider = BuildServiceProvider(cache, target,
                                                       o =>
            {
                o.DefaultTtl            = TimeSpan.FromSeconds(seconds);
                o.DefaultExpirationType = expirationType;
            });
            var instance = serviceProvider.GetRequiredService <IService>();


            // Act
            var result = await instance.GetStuffAsync(CancellationToken.None);

            // Assert
            await cache.Received(1).GetOrCreateAsync(Arg.Any <string>(),
                                                     Arg.Is <CacheEntryOptions>(o =>
                                                                                o.Type == expirationType &&
                                                                                o.Ttl.TotalSeconds == seconds),
                                                     Arg.Any <Func <string, Task <string> > >(),
                                                     Arg.Any <CancellationToken>());
        }
Example #4
0
 /// <summary>
 ///   Convenience consructor uses the default storage style.
 ///   Todo extract default storage style out into a member of the enum.
 /// </summary>
 public Key(TimeSpan durationToStore, ExpirationType cacheExpirationType, string friendlyName)
     : this(durationToStore,
            StorageStyle.Unmodified,
            cacheExpirationType,
            friendlyName)
 {
 }
Example #5
0
 public CacheSettings(bool enabled, ExpirationType expirationType, TimeSpan expirationTime)
 {
     this.Enabled        = enabled;
     this.ExpirationType = expirationType;
     this.ExpirationTime = expirationTime;
     this.Flush          = false;
 }
Example #6
0
 public CacheAttribute(ExpirationType expirationType, string expirationPattern, string prefix = null, bool isUserContextAware = false)
 {
     ExpirationType     = expirationType;
     ExpirationPattern  = expirationPattern;
     Prefix             = prefix;
     IsUserContextAware = isUserContextAware;
 }
Example #7
0
        private void InitializeControls()
        {
            this.priorityComboBox.SelectedIndex = 1;

            // The form defaults to AbsoluteTime as the expiration for new items
            this.expirationComboBox.SelectedIndex = 0;
            this.expiration = ExpirationType.AbsoluteTime;
        }
Example #8
0
 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
     modelBuilder
     .Entity <OfferType>()
     .Property(e => e.ExpirationType)
     .HasConversion(
         e => e.Value,
         v => ExpirationType.FromValue(v)
         );
 }
Example #9
0
        public IConfig WithExpirationType(ExpirationType expType)
        {
            if (_settings == null)
            {
                _settings = new Settings();
            }

            _settings.ExpirationType = expType;

            return(this);
        }
        public ICacheImplementation Select(TimeSpan durationToCacheItemFor,
                                           StorageStyle cacheStorageStyle,
                                           ExpirationType expirationType)
        {
            Ensure.That(durationToCacheItemFor.IsGreaterThanZero(), "durationToCacheItemFor");

            return _selectorDelegate(durationToCacheItemFor,
                                     cacheStorageStyle,
                                     expirationType,
                                     _implementations);
        }
        //private static ValidatorRule parse(DummyType dummyType)
        //{
        //    return new DummyRule(dummyType.Value);
        //}

        private static IValidatorRule Parse(ExpirationType expirationType)
        {
            if (expirationType.Millis == 0)
            {
                return(new ExpirationRule());
            }
            else
            {
                return(new ExpirationSoonRule(expirationType.Millis ?? -1));
            }
        }
Example #12
0
        /// <summary>
        ///   Made public to make API more intuitive, even though it opens up
        ///   two routes to do the same thing (this plus the "ICacheKeyCreator.Create"
        ///   method.
        /// </summary>
        public Key(TimeSpan durationToStore, StorageStyle cacheStorageStyle, ExpirationType cacheExpirationType,
                   string friendlyName)
        {
            Ensure.That(durationToStore.IsGreaterThan(TimeSpan.Zero), "durationToStore must be greater than zero")
                .And(friendlyName.IsNotNullOrWhiteSpace(), "friendlyName not supplied")
                .And(friendlyName.Length.IsLessThan(MaxFriendlyNameLength), "friendlyName too long");

            DurationToStore = durationToStore;
            StorageStyle = cacheStorageStyle;
            CacheExpirationType = cacheExpirationType;
            FriendlyName = friendlyName;
        }
Example #13
0
        public static T AddOrGetExisting <T>(string publicKey, ExpirationType expirationType, TimeSpan expirationInterval, Func <T> loader, Action <CacheEntryUpdateArguments> expirationCallback = null)
            where T : class
        {
            var privateKey = KeyTransform <T>(publicKey);

            // Returns null if the string does not exist, prevents a race condition where the cache invalidates between the contains check and the retreival.
            var cachedItem = MemoryCache.Default.Get(privateKey) as CacheItem;

            if (cachedItem != null)
            {
                return(cachedItem.Value as T);
            }

            lock (LOCKS[privateKey])
            {
                // Check to see if anyone wrote to the cache while we were waiting our turn to write the new value.
                cachedItem = MemoryCache.Default.Get(privateKey) as CacheItem;

                if (cachedItem != null)
                {
                    return(cachedItem.Value as T);
                }

                var policy = new CacheItemPolicy();

                Action <CacheEntryUpdateArguments> defaultExpirationCallback = DefaultExpiredBehavior;
                var callback = expirationCallback != null ? (Action <CacheEntryUpdateArguments>)Delegate.Combine(defaultExpirationCallback, expirationCallback) : defaultExpirationCallback;
                policy.UpdateCallback = e => callback(e);

                switch (expirationType)
                {
                case ExpirationType.Absolute:
                    policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now + expirationInterval);
                    break;

                case ExpirationType.Sliding:
                    policy.SlidingExpiration = expirationInterval;
                    break;
                }

                // The value still did not exist so we now write it in to the cache.
                var data = loader();

                var cacheItem = new CacheItem(privateKey, data);
                MemoryCache.Default.Set(privateKey, cacheItem, policy);

                return(data);
            }
        }
        /// <summary>
        ///   This is the method to be supplied to the constructor of 
        ///   the base type as the delegate to use for cache selection.
        ///   Selects a cache based on the heuristic of duration to 
        ///   store for, followed by the availability of the requested 
        ///   caching functionality. This logic serves as a workable 
        ///   example, rather than a recommended strategy. For example, 
        ///   the fallback case is handled without error or warning.        
        ///   Public rather than protected for testing purposes.
        /// </summary>
        /// <remarks>
        ///   NOTE: BA; should we throw an exception if the user requests 
        ///   a storage strategy that cannot be fulfilled due to 
        ///   limitations of the underlying cache?
        ///   NOTE: BA; Potentially have a flag to indicate strictness of
        ///   choice of cache - i.e. does the cache really need to 
        ///   support all the desired features, or can we substitute 
        ///   them?
        ///   "narrow down choice of caches to those that can be used, 
        ///   then choose the enabled one according to priority".
        /// </remarks>
        /// <param name = "implementations">Ordered by preference of use 
        ///   with highest pref first.</param>
        public static ICacheImplementation SelectCacheImplementation(TimeSpan durationToCacheItemFor,
                                                                     StorageStyle cacheStorageStyle,
                                                                     ExpirationType cacheExpirationType,
                                                                     Dictionary<string, ICacheImplementation>
                                                                         implementations)
        {
            Ensure.That<FriendlyExceptions.ArgumentOutOfRangeException>(durationToCacheItemFor.IsGreaterThanZero(),
                                                                        "durationToCacheFor")
                .And<FriendlyExceptions.ArgumentNullException>(implementations.IsNotNull(), "implementations")
                .And<FriendlyExceptions.ArgumentException>(implementations.Count.Is(2), "implementations")
                .And<MissingCacheImplementationArgumentException>(
                    implementations.ContainsKey(MemcachedImplementationTypeName), "memcached missing")
                .And<MissingCacheImplementationArgumentException>(
                    implementations.ContainsKey(AspDotNetImplementationTypeName), "asp.net data cache missing");

            ICacheImplementation cacheToUse = null;

            //simply tries to select memcached if an extended caching period is requested
            //otherwise attempts to fallback to ASP.NET data cache. This might occur because
            //the caching expiration type is not supported by memcached.
            if (durationToCacheItemFor >= LongTermBoundary)
            {
                if (implementations[MemcachedImplementationTypeName].Supports((cacheExpirationType))
                    && implementations[MemcachedImplementationTypeName].IsEnabled)
                    cacheToUse = implementations[MemcachedImplementationTypeName];

                if (cacheToUse == null
                    && implementations[AspDotNetImplementationTypeName].Supports((cacheExpirationType))
                    && implementations[AspDotNetImplementationTypeName].IsEnabled)
                    cacheToUse = implementations[AspDotNetImplementationTypeName];

                Ensure.That(cacheToUse.IsNotNull(), () => { throw new CacheSelectionException(implementations); });
            }
            else
            {
                if (implementations[AspDotNetImplementationTypeName].Supports((cacheExpirationType))
                    && implementations[AspDotNetImplementationTypeName].IsEnabled)
                    cacheToUse = implementations[AspDotNetImplementationTypeName];

                if (cacheToUse == null
                    && implementations[MemcachedImplementationTypeName].Supports((cacheExpirationType))
                    && implementations[MemcachedImplementationTypeName].IsEnabled)
                    cacheToUse = implementations[MemcachedImplementationTypeName];

                Ensure.That(cacheToUse.IsNotNull(), () => { throw new CacheSelectionException(implementations); });
            }

            return cacheToUse;
        }
 internal MemoizerConfiguration(object function,
                              ExpirationType expirationType,
                              int expirationValue,
                              TimeUnit expirationTimeUnit,
                              Action<string> loggerMethod)
 {
     Function = function;
     bool firstTime = false;
     //this.FunctionId = (Int32)MemoizerHelper.GetObjectId(Function, ref firstTime);
     this.FunctionId = (Int32)HashHelper.GetObjectId(Function, ref firstTime);
     ExpirationType = expirationType;
     ExpirationValue = expirationValue;
     ExpirationTimeUnit = expirationTimeUnit;
     LoggerAction = loggerMethod;
 }
        public CacheConfig(string name,
                           long maxSize,
                           int lifespan,
                           ExpirationType expirationType = ExpirationType.Absolute)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentException($"{nameof(name)} cannot be null or empty.", nameof(name));
            }

            this.Name           = name;
            this.MaxSize        = maxSize;
            this.Lifespan       = lifespan;
            this.ExpirationType = expirationType;
        }
        internal MemoizerConfiguration(object function,
                                       ExpirationType expirationType,
                                       int expirationValue,
                                       TimeUnit expirationTimeUnit,
                                       Action <string> loggerMethod)
        {
            Function = function;
            bool firstTime = false;

            //this.FunctionId = (Int32)MemoizerHelper.GetObjectId(Function, ref firstTime);
            this.FunctionId    = (Int32)HashHelper.GetObjectId(Function, ref firstTime);
            ExpirationType     = expirationType;
            ExpirationValue    = expirationValue;
            ExpirationTimeUnit = expirationTimeUnit;
            LoggerAction       = loggerMethod;
        }
Example #18
0
        public void Add <T>(string key, Func <T> loader, ExpirationType expirationType, TimeSpan?expirationInterval = null)
        {
            var policy = new CacheItemPolicy();

            switch (expirationType)
            {
            case ExpirationType.Infinite:
            {
                policy.AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration;
            }
            break;

            case ExpirationType.Absolute:
            {
                if (!expirationInterval.HasValue)
                {
                    throw new ArgumentNullException(nameof(expirationInterval), "Expiration interval cannot be null due to the exipration type is absolute.");
                }

                policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now + expirationInterval.Value);
            }
            break;

            case ExpirationType.Sliding:
            {
                if (!expirationInterval.HasValue)
                {
                    throw new ArgumentNullException(nameof(expirationInterval), "Expiration interval cannot be null due to the exipration type is sliding.");
                }

                policy.SlidingExpiration = expirationInterval.Value;
            }
            break;

            case ExpirationType.None:
            default:
            {
                throw new NotSupportedException("Expiration type none is not supported.");
            }
            }

            var data = loader();

            var cacheItem = new CacheItem(key, data);

            _memoryCache.Set(key, cacheItem, policy);
        }
Example #19
0
        public CacheAspect(Type cacheType,
                           Type keyCreationStrategyType,
                           int durationToStoreInSeconds,
                           StorageStyle storageStyle,
                           ExpirationType expirationType)
        {
            Ensure.That<ArgumentNullException>(cacheType.IsNotNull(), "cacheType")
                .And<ArgumentNullException>(keyCreationStrategyType.IsNotNull(), "keyCreationStrategyType")
                .And<ArgumentException>(durationToStoreInSeconds.IsBetween(0, OneYearInSeconds),
                                        "durationToStoreInSeconds");

            _cacheType = cacheType;
            _keyCreationStrategyType = keyCreationStrategyType;
            _durationToStore = TimeSpan.FromSeconds(durationToStoreInSeconds);
            _storageStyle = storageStyle;
            _expirationType = expirationType;
        }
Example #20
0
 /// <summary>
 /// Insert customer data to cache
 /// </summary>
 public void StoreNewCustomerData(ExpirationType expirationType = ExpirationType.None)
 {
     try
     {
         var cacheItem = new CacheItem(_serializer.Serialize(Customer));
         if (expirationType.Equals(ExpirationType.Absolute))
         {
             cacheItem.Expiration = new Expiration(ExpirationType.Absolute, new TimeSpan(0, 0, 10));
         }
         _cache.Insert(Customer.CustomerID.ToUpper(), cacheItem, new WriteThruOptions(WriteMode.WriteThru, WriteThruProviderName));
         Console.WriteLine("Customer information Inserted successfuly");
     }
     catch (Exception e)
     {
         Console.WriteLine("\n" + "Error: " + e.Message);
     }
 }
Example #21
0
        internal static CacheItemPolicy CreateCacheItemPolicy(ExpirationType expirationType, int expirationValue, TimeUnit expirationTimeUnit)
        {
            CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();

            switch (expirationType)
            {
            case ExpirationType.Relative:
                TimeSpan timeSpan;
                switch (expirationTimeUnit)
                {
                case TimeUnit.Milliseconds:
                    timeSpan = new TimeSpan(0, 0, 0, 0, expirationValue);
                    cacheItemPolicy.SlidingExpiration = timeSpan;
                    break;

                case TimeUnit.Seconds:
                    timeSpan = new TimeSpan(0, 0, 0, expirationValue, 0);
                    cacheItemPolicy.SlidingExpiration = timeSpan;
                    break;

                case TimeUnit.Minutes:
                    timeSpan = new TimeSpan(0, 0, expirationValue, 0, 0);
                    cacheItemPolicy.SlidingExpiration = timeSpan;
                    break;

                case TimeUnit.Hours:
                    timeSpan = new TimeSpan(0, expirationValue, 0, 0, 0);
                    cacheItemPolicy.SlidingExpiration = timeSpan;
                    break;

                case TimeUnit.Days:
                    timeSpan = new TimeSpan(expirationValue, 0, 0, 0, 0);
                    cacheItemPolicy.SlidingExpiration = timeSpan;
                    break;

                default:
                    throw new NotImplementedException();
                }
                break;

            default:
                throw new NotImplementedException();
            }
            return(cacheItemPolicy);
        }
Example #22
0
 private static CacheItemPolicy CreateCacheItemPolicy(ExpirationType expirationType, TimeSpan expirationTime)
 {
     if (expirationType == ExpirationType.AbsoluteExpiration)
     {
         return new CacheItemPolicy
                {
                    AbsoluteExpiration = DateTime.Now.Add(expirationTime)
                }
     }
     ;
     else
     {
         return new CacheItemPolicy
                {
                    SlidingExpiration = expirationTime
                }
     };
 }
        /// <summary>
        /// MemoizerConfiguration hash code format: 5 digits with function ID + 5 digits hash of the rest.
        /// 2^31 == 2 147 483 648 == 21474 83648 => max 21474 different Funcs, and 83648 different expiration configurations...
        /// This has clearly limitations, but it's OK as a proof-of-concept, I guess - it's fixable :-)
        /// </summary>
        public override int GetHashCode()
        {
            if (FunctionId > 21474)
            {
                throw new InvalidOperationException("Memoizer.NET only supports 21474 different Func references at the moment...");
            }
            string funcId = FunctionId.ToString();

            //int expirationConfigHash = MemoizerHelper.PRIMES[15] + ExpirationType.GetHashCode();
            //expirationConfigHash = expirationConfigHash * MemoizerHelper.PRIMES[11] + ExpirationValue.GetHashCode();
            //expirationConfigHash = expirationConfigHash * MemoizerHelper.PRIMES[7] + ExpirationTimeUnit.GetHashCode();
            int expirationConfigHash = HashHelper.PRIMES[15] + ExpirationType.GetHashCode();

            expirationConfigHash = expirationConfigHash * HashHelper.PRIMES[11] + ExpirationValue.GetHashCode();
            expirationConfigHash = expirationConfigHash * HashHelper.PRIMES[7] + ExpirationTimeUnit.GetHashCode();

            expirationConfigHash = expirationConfigHash % 83648;

            return(Convert.ToInt32(funcId + expirationConfigHash));
        }
Example #24
0
        /// <summary>
        /// Set the expirate enumeration as the user selects different expiration options
        /// </summary>
        private void expirationComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (this.expirationComboBox.SelectedIndex)
            {
            case 0:
                this.expiration = ExpirationType.AbsoluteTime;
                break;

            case 1:
                this.expiration = ExpirationType.SlidingTime;
                break;

            case 2:
                this.expiration = ExpirationType.ExtendedFormat;
                break;

            case 3:
                this.expiration = ExpirationType.FileDependency;
                break;
            }
        }
 internal static Expiration DetermineCachePersistedGrantStoreExpiration(
     PersistedGrant grant,
     PersistedStoreCachingOptions options)
 {
     if (options.UsePersistedGrantExpiration &&
         grant.Expiration.HasValue)
     {
         return(new Expiration(
                    ExpirationType.Absolute,
                    grant.Expiration.Value - DateTime.UtcNow));
     }
     else
     {
         ExpirationType expirationType =
             options.Expiration ==
             CacheExpirationType.Absolute ?
             ExpirationType.Absolute :
             ExpirationType.Sliding;
         TimeSpan timeSpan = TimeSpan.FromSeconds
                                 (options.TimeSpanInSeconds);
         return(new Expiration(expirationType, timeSpan));
     }
 }
Example #26
0
        public DateTimeOffset GetExecutionDate(DateTimeOffset fromDate, ExpirationType expirationType, short expirationValue)
        {
            var executionDate = new DateTimeOffset();

            switch (expirationType)
            {
            case ExpirationType.CalendarDay:
            {
                executionDate = fromDate.AddDays(expirationValue);
                break;
            }

            case ExpirationType.WorkDay:
            {
                executionDate = fromDate.AddDays(expirationValue);
                var holidayCount = GetHolidaysCount(fromDate, executionDate);

                if (holidayCount > 0)
                {
                    executionDate = executionDate.AddDays(holidayCount);
                }
                break;
            }

            case ExpirationType.CalendarMonth:
            {
                executionDate = fromDate.AddMonths(expirationValue);
                while (GetHolidaysCount(executionDate, executionDate) > 0)
                {
                    executionDate = executionDate.AddDays(1);
                }
                break;
            }
            }

            return(executionDate);
        }
Example #27
0
        /// <summary>
        /// take customer data input from user
        /// </summary>
        public void InputDataFromUser(ExpirationType expirationType = ExpirationType.None)
        {
            Console.WriteLine("Enter the following information");

            string input;

            Console.Write("Customer ID: ");
            Customer.CustomerID = ((input = Console.ReadLine()) != "") ? input : Customer.CustomerID;
            Console.Write("Contact Name: ");
            Customer.ContactName = ((input = Console.ReadLine()) != "") ? input : Customer.ContactName;
            Console.Write("Company Name: ");
            Customer.CompanyName = ((input = Console.ReadLine()) != "") ? input : Customer.CompanyName;
            Console.Write("Address: ");
            Customer.Address = ((input = Console.ReadLine()) != "") ? input : Customer.Address;
            Console.Write("City: ");
            Customer.City = ((input = Console.ReadLine()) != "") ? input : Customer.City;
            Console.Write("Country: ");
            Customer.Country = ((input = Console.ReadLine()) != "") ? input : Customer.Country;
            Console.Write("Postal Code: ");
            Customer.PostalCode = ((input = Console.ReadLine()) != "") ? input : Customer.PostalCode;
            Console.Write("Phone Number: ");
            Customer.ContactNo = ((input = Console.ReadLine()) != "") ? input : Customer.ContactNo;
            Console.Write("Fax Number: ");
            Customer.Fax = ((input = Console.ReadLine()) != "") ? input : Customer.Fax;
            if (expirationType.Equals(ExpirationType.Absolute))
            {
                Console.Write("Enter seconds for Absolute expiration: ");
            }
            try
            {
                AbsoluteExpirationSeconds = Convert.ToInt32(Console.ReadLine());
            }
            catch
            {
                Console.WriteLine("Absolute expiration must be set in seconds in int value");
            }
        }
Example #28
0
 /// <summary>
 /// Set the expirate enumeration as the user selects different expiration options
 /// </summary>
 private void expirationComboBox_SelectedIndexChanged(object sender, EventArgs e)
 {
     switch (this.expirationComboBox.SelectedIndex)
     {
         case 0:
             this.expiration = ExpirationType.AbsoluteTime;
             break;
         case 1:
             this.expiration = ExpirationType.SlidingTime;
             break;
         case 2:
             this.expiration = ExpirationType.ExtendedFormat;
             break;
         case 3:
             this.expiration = ExpirationType.FileDependency;
             break;
     }
 }
Example #29
0
 public MemoryAdapter(string name, int minutesToExpire, ExpirationType expirationType)
 {
     _memoryCache = new MemoryCache(name);
     _expirationType = expirationType;
     _minutesToExpire = minutesToExpire;
 }
Example #30
0
 public CacheExpiration(ExpirationType type, int milliseconds)
 {
     Type         = type;
     Milliseconds = milliseconds;
 }
Example #31
0
 /// <summary>
 /// Instantiates <see cref="Expiration"/> to provide expiration values for items in cache.
 /// </summary>
 /// <param name="expirationType">Flag indicating type of expiration to be used while
 /// expiring items in cache.</param>
 /// <param name="expireAfter">Value of time in the form of <see cref="TimeSpan"/> that
 /// shows after how much time, the item in cache is to be expired.</param>
 /// <example>This example demonstrates how to create an instance of <see cref="Expiration"/> with
 /// sliding expiration of 5 minutes.
 /// <code>
 /// Expiration slidingExpiration = new Expiration(ExpirationType.Sliding, TimeSpan.FromMinutes(5));
 /// </code>
 /// </example>
 public Expiration(ExpirationType expirationType, TimeSpan expireAfter = default(TimeSpan))
 {
     Type        = expirationType;
     ExpireAfter = expireAfter;
 }
Example #32
0
 public static void Set(string key, DataTable value, ExpirationType expirationType, TimeSpan expirationTime)
 {
     MemoryCache.Default.Set(CreateKey(key), value, CreateCacheItemPolicy(expirationType, expirationTime));
 }
        private void SetSettings(XmlNode settings)
        {
            foreach (XmlNode config in settings.SelectNodes("add"))
                _settings.Add(config.Attributes["key"].Value, config.Attributes["value"].Value);

            if (_settings.ContainsKey("DefaultLanguage"))
                try { _defaultLanguage = CultureInfo.CreateSpecificCulture(_settings["DefaultLanguage"]); }
                catch (ArgumentException) { }

            if (_settings.ContainsKey("DefaultTheme"))
                _defaultTheme = _settings["DefaultTheme"];

            if (_settings.ContainsKey("DefaultStyle"))
                _defaultStyle = _settings["DefaultStyle"];

            if (_settings.ContainsKey("DefaultSkinTemplate"))
                _defaultSkinTemplate = _settings["DefaultSkinTemplate"];

            if (_settings.ContainsKey("DefaultPageHandler"))
                _defaultPageHandler = _settings["DefaultPageHandler"];

            if (_settings.ContainsKey("ExpirationType"))
                try { _expirationType = (ExpirationType)Enum.Parse(typeof(ExpirationType), _settings["ExpirationType"], true); }
                catch (ArgumentException) { }

            if (_settings.ContainsKey("CacheTime"))
                _cacheTime = XmlConvert.ToDouble(_settings["CacheTime"]);

            if (_settings.ContainsKey("DatabaseConnectionString"))
                _databaseConnectionString = _settings["DatabaseConnectionString"];

            if (_settings.ContainsKey("DatabaseCacheTime"))
                _databaseCacheTime = XmlConvert.ToDouble(_settings["DatabaseCacheTime"]);
        }
Example #34
0
 public Expiration(ExpirationType type, int duration)
 {
     ExpirationType = type;
     Duration       = duration;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="GrantPermissionRequestDurationSettings" /> class.
 /// </summary>
 /// <param name="isGrantTemporaryPermission">isGrantTemporaryPermission.</param>
 /// <param name="expirationType">expirationType.</param>
 /// <param name="durationInterval">durationInterval.</param>
 /// <param name="durationDateType">durationDateType.</param>
 /// <param name="startTime">startTime.</param>
 /// <param name="endTime">endTime.</param>
 public GrantPermissionRequestDurationSettings(bool isGrantTemporaryPermission = default(bool), ExpirationType expirationType = default(ExpirationType), int?durationInterval = default(int?), DurationDateTypeNullable durationDateType = default(DurationDateTypeNullable), DateTime?startTime = default(DateTime?), DateTime?endTime = default(DateTime?))
 {
     this.DurationInterval           = durationInterval;
     this.DurationDateType           = durationDateType;
     this.StartTime                  = startTime;
     this.EndTime                    = endTime;
     this.IsGrantTemporaryPermission = isGrantTemporaryPermission;
     this.ExpirationType             = expirationType;
     this.DurationInterval           = durationInterval;
     this.DurationDateType           = durationDateType;
     this.StartTime                  = startTime;
     this.EndTime                    = endTime;
 }
 public bool Supports(ExpirationType expirationType)
 {
     throw new NotImplementedException();
 }
 bool ICacheImplementation.Supports(ExpirationType expirationType)
 {
     return _supportedCacheExpirationTypes.Contains(expirationType);
 }
Example #38
0
        protected void ProlongateCurentStage(Domain.Entities.Request.Request request, ExpirationType type, short count)
        {
            var queue = _context.WorkflowTaskQueues.LastOrDefault(a => a.RequestId == request.Id && a.ConditionStageId == request.CurrentWorkflow.CurrentStageId);

            if (queue != null)
            {
                //Ожидаемые оплату за подачу срок этапа два месяца плюс можно один раз продлить еще на два
                if (CurrentStageContains(request, "U02.2.7") && (queue.ResolveDate - request.DateCreate).TotalDays > 65)
                {
                    return;
                }
                queue.ResolveDate = new CalendarProvider(_context).GetExecutionDate(queue.ResolveDate, type, count);
            }
        }
Example #39
0
 /// <summary>
 ///   Enables the ICacheKeyCreator to be injected into 
 ///   types (constructors cannot be constrained by interfaces).
 /// </summary>
 public Key Create(TimeSpan durationToStore, StorageStyle cacheStorageStyle, ExpirationType cacheExpirationType,
                   string friendlyName)
 {
     return new Key(durationToStore, cacheStorageStyle, cacheExpirationType, friendlyName);
 }
Example #40
0
 private AndBuilder <CacheImplementationBuilder> ExpirationType(ExpirationType expirationType)
 {
     _cacheOptions.ExpirationType = expirationType;
     return(new AndBuilder <CacheImplementationBuilder>(new CacheImplementationBuilder(_cacheOptions)));
 }
Example #41
0
        private void InitializeControls()
        {
            this.priorityComboBox.SelectedIndex = 1;

            // The form defaults to AbsoluteTime as the expiration for new items
            this.expirationComboBox.SelectedIndex = 0;
            this.expiration = ExpirationType.AbsoluteTime;
        }
Example #42
0
 public CacheAttribute(double ttlMs, ExpirationType expirationType = Caching.ExpirationType.Relative)
 {
     Ttl            = TimeSpan.FromMilliseconds(ttlMs);
     ExpirationType = expirationType;
 }
Example #43
0
 public Expiration(ExpirationType type, int duration)
 {
     ExpirationType = type;
     Duration = duration;
 }
Example #44
0
 public Cache(ExpirationType expirationPolicy)
 {
     ExpirationPolicy = expirationPolicy;
 }
Example #45
0
 public CachePolicyAttribute(int ttlSeconds, ExpirationType expirationType = ExpirationType.Relative)
 {
     Ttl            = TimeSpan.FromSeconds(ttlSeconds);
     ExpirationType = expirationType;
 }