コード例 #1
0
        /// <summary>
        ///     设置 Hash 缓存。
        /// </summary>
        /// <param name="firstKey">主键。</param>
        /// <param name="secondKey">次键。</param>
        /// <param name="value">要缓存的值。</param>
        /// <param name="options">缓存时间设置,为 NULL 表示永久。</param>
        public async Task SetHashCacheAsync(string firstKey, string secondKey, string value, KolibreCacheOptions options)
        {
            ConditionalValue <CacheWrapper> state = await StateManager.TryGetStateAsync <CacheWrapper>(firstKey);

            CacheWrapper cacheWrapper = state.HasValue ? state.Value : new CacheWrapper(CacheType.Hash);

            if (cacheWrapper.CacheType != CacheType.Hash)
            {
                throw new InvalidOperationException($"Operation against a key holding the wrong type '{cacheWrapper.CacheType}'.");
            }

            // 若设置 Hash Cache 时,值不是 Dictionary<string,string> 类型,抛出异常
            Dictionary <string, string> hashCacheWrappers;

            try
            {
                hashCacheWrappers = cacheWrapper.Cache.FromJson <Dictionary <string, string> >() ?? new Dictionary <string, string>();
            }
            catch
            {
                throw new InvalidOperationException($"Operation against a key holding the wrong type '{cacheWrapper.CacheType}'.");
            }

            hashCacheWrappers[secondKey] = value;
            CacheWrapper result = cacheWrapper.SetCache(hashCacheWrappers.ToJson(), CacheType.Hash, options);

            await StateManager.SetStateAsync(firstKey, result);
        }
コード例 #2
0
        public static List<Company> GetCompanies(int? userId, bool forceSqlLoad)
        {
            var cache = new CacheWrapper();

            var res = cache.GetList<Company>(CacheKey, userId);
            if (res == null || forceSqlLoad)
            {
                res = new List<Company>();
                using (var holder = SqlConnectionHelper.GetConnection())
                {
                    using (var cmd = holder.Connection.CreateSPCommand("companies_get"))
                    {
                        cmd.Parameters.AddWithValue("@id_user", userId);
                        try
                        {
                            using (var reader = cmd.ExecuteReader())
                            {
                                while (reader.Read())
                                    res.Add(new Company(reader));
                            }
                        }
                        catch (SqlException e)
                        {
                            cmd.AddDetailsToException(e);
                            throw;
                        }
                    }
                }
                //save to cache
                cache.SetList(CacheKey, res, userId);
            }
            return res;
        }
コード例 #3
0
        /// <summary>
        /// Ensures that the template is on the server state (cache/session)
        /// </summary>
        /// <returns></returns>
        private TemplateState LoadTemplateState(HttpContextBase context)
        {
            TemplateState template = null;
            var session = new SessionWrapper(context);
            var cache = new CacheWrapper(context);
            template = LoadPreview(context, session);
            if (template != null)
            {
                return template;
            }

            if (Config.UI.Template.UseTemplates)
            {
                if (cache.Template == null)
                {
                    //Load the current template in the cache
                    cache.Template = TemplateHelper.GetCurrentTemplateState(context, Service);
                }
                template = cache.Template;
            }
            else
            {
                cache.Template = null;
            }

            return template;
        }
コード例 #4
0
        public LinkGenerator(IPersister persister, ConnectionMonitor connection, CacheWrapper cacheWrapper, IRequestLogger logger)
        {
            _logger = logger;

            // DON'T USE DISTRIBUTED CACHE FOR N2 internal data 
            // _urlCache = cacheService.GetCache<string>(new CacheConfig("LinkGenerator_urlCache", 1800));
            _urlCache = new HttpRuntimeCacheWrapper<string>("LinkGenerator_urlCache", cacheWrapper);
            _itemCache = new HttpRuntimeCacheWrapper<object>("LinkGenerator_urlCache_item", cacheWrapper);

            // hook up to persister events
            connection.Online += delegate
            {
                persister.ItemSaved += persister_ItemSaved;
                persister.ItemMoving += persister_ItemMoving;
                persister.ItemMoved += persister_ItemMoved;
                persister.ItemCopied += persister_ItemCopied;
                persister.ItemDeleted += persister_ItemDeleted;
                persister.FlushCache += persister_ItemInvalidated;
            };
            connection.Offline += delegate
            {
                persister.ItemSaved -= persister_ItemSaved;
                persister.ItemMoving -= persister_ItemMoving;
                persister.ItemMoved -= persister_ItemMoved;
                persister.ItemCopied -= persister_ItemCopied;
                persister.ItemDeleted -= persister_ItemDeleted;
                persister.FlushCache -= persister_ItemInvalidated;
            };
        }
コード例 #5
0
        /// <summary>
        ///     向列表尾添加元素,若 key 对应无列表缓存,则自动创建并添加一个元素。
        /// </summary>
        /// <param name="key">主键。</param>
        /// <param name="value">要缓存的值。</param>
        /// <param name="options">缓存时间设置,为 NULL 表示永久。</param>
        public async Task RightPushListCacheAsync(string key, string value, KolibreCacheOptions options)
        {
            ConditionalValue <CacheWrapper> state = await StateManager.TryGetStateAsync <CacheWrapper>(key);

            CacheWrapper cacheWrapper = new CacheWrapper(CacheType.List);

            if (state.HasValue)
            {
                if (cacheWrapper.CacheType != CacheType.List)
                {
                    throw new InvalidOperationException($"Operation against a key holding the wrong type '{cacheWrapper.CacheType}'.");
                }

                if (!state.Value.IsExpired())
                {
                    cacheWrapper = state.Value;
                }
            }

            List <string> caches;

            try
            {
                caches = cacheWrapper.Cache.FromJson <List <string> >() ?? new List <string>();
            }
            catch
            {
                throw new InvalidOperationException($"Operation against a key holding the wrong type '{cacheWrapper.CacheType}'.");
            }

            caches.Insert(caches.Count, value);
            CacheWrapper result = cacheWrapper.SetCache(caches.ToJson(), CacheType.List, options);

            await StateManager.SetStateAsync(key, result);
        }
コード例 #6
0
        /// <summary>
        ///     查询缓存键对应的缓存值的数量。
        /// </summary>
        /// <param name="key">缓存键。</param>
        public async Task <int> GetTeacherCountsAsync(string key)
        {
            ConditionalValue <CacheWrapper <Teacher> > result = await StateManager.TryGetStateAsync <CacheWrapper <Teacher> >(key);

            if (!result.HasValue)
            {
                return(0);
            }

            CacheWrapper <Teacher> cacheWrapper = result.Value;

            if (cacheWrapper.IsExpired())
            {
                await StateManager.RemoveStateAsync(key);

                return(0);
            }

            // 刷新滑动过期时间。
            (bool needRestore, CacheWrapper <Teacher> cacheWrapper)refreshResult = cacheWrapper.Refresh();
            if (refreshResult.needRestore)
            {
                await StateManager.SetStateAsync(key, refreshResult.cacheWrapper);
            }

            return(refreshResult.cacheWrapper.Caches.Count);
        }
コード例 #7
0
        /// <summary>
        ///     查询缓存。
        /// </summary>
        /// <param name="key">缓存键。</param>
        /// <param name="top">返回结果数量。</param>
        public async Task <List <Teacher> > GetTeacherTopSmartCachesAsync(string key, int top)
        {
            ConditionalValue <CacheWrapper <Teacher> > result = await StateManager.TryGetStateAsync <CacheWrapper <Teacher> >(key);

            if (!result.HasValue)
            {
                return(null);
            }

            CacheWrapper <Teacher> cacheWrapper = result.Value;

            if (cacheWrapper.IsExpired())
            {
                await StateManager.RemoveStateAsync(key);

                return(null);
            }

            // 刷新滑动过期时间。
            (bool needRestore, CacheWrapper <Teacher> cacheWrapper)refreshResult = cacheWrapper.Refresh();
            if (refreshResult.needRestore)
            {
                await StateManager.SetStateAsync(key, refreshResult.cacheWrapper);
            }

            return(refreshResult.cacheWrapper.Caches.GetRange(0, top));
        }
コード例 #8
0
        /// <summary>
        ///     查询缓存。
        /// </summary>
        /// <param name="key">缓存键。</param>
        public async Task <Student> GetSmartCacheAsync(string key)
        {
            ConditionalValue <CacheWrapper <Student> > result = await StateManager.TryGetStateAsync <CacheWrapper <Student> >(key);

            if (!result.HasValue)
            {
                return(null);
            }

            CacheWrapper <Student> cacheWrapper = result.Value;

            if (cacheWrapper.IsExpired())
            {
                await StateManager.RemoveStateAsync(key);

                return(null);
            }

            // 刷新滑动过期时间。
            (bool needRestore, CacheWrapper <Student> cacheWrapper)refreshResult = cacheWrapper.Refresh();
            if (refreshResult.needRestore)
            {
                await StateManager.SetStateAsync(key, refreshResult.cacheWrapper);
            }

            return(refreshResult.cacheWrapper.Caches.FirstOrDefault());
        }
コード例 #9
0
        /// <summary>
        ///     移除缓存键中指定的缓存值。
        /// </summary>
        /// <param name="key">缓存键。</param>
        /// <param name="value">被移除的缓存值。</param>
        public async Task RemoveSmartCacheValueAsync(string key, Student value)
        {
            ConditionalValue <CacheWrapper <Student> > result = await StateManager.TryGetStateAsync <CacheWrapper <Student> >(key);

            if (!result.HasValue)
            {
                return;
            }

            CacheWrapper <Student> cacheWrapper = result.Value;

            if (cacheWrapper.IsExpired())
            {
                await StateManager.RemoveStateAsync(key);

                return;
            }

            cacheWrapper.Caches.Remove(value);
            if (cacheWrapper.Caches.Count == 0)
            {
                await StateManager.RemoveStateAsync(key);
            }

            await StateManager.SetStateAsync(key, cacheWrapper);
        }
コード例 #10
0
		public CachingLanguageGatewayDecorator(ILanguageGateway inner, CacheWrapper cacheWrapper, IPersister persister, string masterKey)
		{
			this.inner = inner;
			this.cacheWrapper = cacheWrapper;
			this.persister = persister;
			this.masterKey = masterKey;
		}
コード例 #11
0
 public CachingLanguageGatewayDecorator(ILanguageGateway inner, CacheWrapper cacheWrapper, IPersister persister, string masterKey)
 {
     this.inner        = inner;
     this.cacheWrapper = cacheWrapper;
     this.persister    = persister;
     this.masterKey    = masterKey;
 }
コード例 #12
0
        protected void ExportBySalesButton_Click(Object sender, EventArgs e)
        {
            GenericExportManager <CommerceBuilder.Reporting.ProductSummary> exportManager = GenericExportManager <CommerceBuilder.Reporting.ProductSummary> .Instance;
            GenericExportOptions <CommerceBuilder.Reporting.ProductSummary> options       = new GenericExportOptions <CommerceBuilder.Reporting.ProductSummary>();

            options.CsvFields = new string[] { "ProductId", "Name", "TotalPrice", "TotalQuantity" };

            CacheWrapper cacheWrapper = Cache[_SalesCacheKey] as CacheWrapper;
            Dictionary <string, object> salesData;
            IList <CommerceBuilder.Reporting.ProductSummary> productSales = null;
            DateTime localNow   = LocaleHelper.LocalNow;
            DateTime last60Days = (new DateTime(localNow.Year, localNow.Month, localNow.Day, 0, 0, 0)).AddDays(-60);

            if (cacheWrapper == null)
            {
                productSales = ReportDataSource.GetSalesByProduct(last60Days, DateTime.MaxValue, 8, 0, "TotalPrice DESC");

                //CACHE THE DATA
                salesData = new Dictionary <string, object>();
                salesData["DataSource"] = productSales;
                cacheWrapper            = new CacheWrapper(salesData);
                Cache.Remove(_SalesCacheKey);
                Cache.Add(_SalesCacheKey, cacheWrapper, null, DateTime.UtcNow.AddMinutes(5).AddSeconds(-1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
            }
            else
            {
                //USE CACHED VALUES
                salesData    = (Dictionary <string, object>)cacheWrapper.CacheValue;
                productSales = (List <CommerceBuilder.Reporting.ProductSummary>)salesData["DataSource"];
            }

            options.ExportData = productSales;
            options.FileTag    = string.Format("POPULAR_PRODUCTS_BY_SALES((from_{0}_to_{1})", localNow.ToShortDateString(), last60Days.ToShortDateString());
            exportManager.BeginExport(options);
        }
コード例 #13
0
 public CachingUrlParserDecorator(IUrlParser inner, IPersister persister, IWebContext webContext, CacheWrapper cache)
 {
     this.inner = inner;
     this.persister = persister;
     this.webContext = webContext;
     this.cache = cache;
 }
コード例 #14
0
        public LinkGenerator(IPersister persister, ConnectionMonitor connection, CacheWrapper cacheWrapper, IRequestLogger logger)
        {
            _logger = logger;

            // DON'T USE DISTRIBUTED CACHE FOR N2 internal data
            // _urlCache = cacheService.GetCache<string>(new CacheConfig("LinkGenerator_urlCache", 1800));
            _urlCache  = new HttpRuntimeCacheWrapper <string>("LinkGenerator_urlCache", cacheWrapper);
            _itemCache = new HttpRuntimeCacheWrapper <object>("LinkGenerator_urlCache_item", cacheWrapper);

            // hook up to persister events
            connection.Online += delegate
            {
                persister.ItemSaved   += persister_ItemSaved;
                persister.ItemMoving  += persister_ItemMoving;
                persister.ItemMoved   += persister_ItemMoved;
                persister.ItemCopied  += persister_ItemCopied;
                persister.ItemDeleted += persister_ItemDeleted;
                persister.FlushCache  += persister_ItemInvalidated;
            };
            connection.Offline += delegate
            {
                persister.ItemSaved   -= persister_ItemSaved;
                persister.ItemMoving  -= persister_ItemMoving;
                persister.ItemMoved   -= persister_ItemMoved;
                persister.ItemCopied  -= persister_ItemCopied;
                persister.ItemDeleted -= persister_ItemDeleted;
                persister.FlushCache  -= persister_ItemInvalidated;
            };
        }
コード例 #15
0
        static void Main(string[] args)
        {
            string connectionString = "localhost:6379";

            IConnector  connector  = new RedisConnector(connectionString);
            ISerializer serializer = new MySerializer();

            ICache rediCache = new RedisCache(connector, serializer);

            var cacheWrapper = new CacheWrapper(rediCache);

            var cache = new CacheTimeWrapper(cacheWrapper);

            Api api = new Api(cache);

            for (int i = 0; i < 10; i++)
            {
                var result = api.GetInformation();

                Thread.Sleep(5000);

                string value = serializer.Serializer(result);
                Console.WriteLine(value);
            }

            Console.ReadKey();
        }
コード例 #16
0
        public async Task RemoveTeacherSmartCacheValuesAsync(string key, List <Teacher> values)
        {
            ConditionalValue <CacheWrapper <Teacher> > result = await StateManager.TryGetStateAsync <CacheWrapper <Teacher> >(key);

            if (!result.HasValue)
            {
                return;
            }

            CacheWrapper <Teacher> cacheWrapper = result.Value;

            if (cacheWrapper.IsExpired())
            {
                await StateManager.RemoveStateAsync(key);

                return;
            }

            values.Select(t => cacheWrapper.Caches.Remove(t));
            if (cacheWrapper.Caches.Count == 0)
            {
                await StateManager.RemoveStateAsync(key);
            }

            await StateManager.SetStateAsync(key, cacheWrapper);
        }
コード例 #17
0
        /// <summary>
        ///     获取缓存。
        /// </summary>
        /// <param name="key">缓存的主键。</param>
        public async Task <string> GetCacheAsync(string key)
        {
            ConditionalValue <CacheWrapper> result = await StateManager.TryGetStateAsync <CacheWrapper>(key);

            if (!result.HasValue)
            {
                return(null);
            }

            CacheWrapper cacheWrapper = result.Value;

            // 如果获取缓存时,给定的 key 对应的值类型跟当前类型不一致。
            if (cacheWrapper.CacheType != CacheType.Normal)
            {
                throw new InvalidOperationException($"Operation against a key holding the wrong type '{cacheWrapper.CacheType}'.");
            }
            if (cacheWrapper.IsExpired())
            {
                await StateManager.RemoveStateAsync(key);

                return(null);
            }

            // 刷新滑动过期时间。
            (bool needRestore, CacheWrapper cacheWrapper)refreshResult = cacheWrapper.Refresh();
            if (refreshResult.needRestore)
            {
                await StateManager.SetStateAsync(key, refreshResult.cacheWrapper);
            }

            return(refreshResult.cacheWrapper.Cache);
        }
コード例 #18
0
        private void initViewChart(bool forceRefresh)
        {
            string       cacheKey     = "3C26BAC7-1D53-40ef-920B-5BDB705F363B";
            CacheWrapper cacheWrapper = Cache[cacheKey] as CacheWrapper;

            if (forceRefresh || (cacheWrapper == null))
            {
                SortableCollection <KeyValuePair <ICatalogable, int> > categoryViews = PageViewDataSource.GetViewsByCategory(_Size, 0, "ViewCount DESC");
                if (categoryViews.Count > 0)
                {
                    //BUILD BAR CHART
                    ViewsChart.Series["Views"].Points.Clear();
                    for (int i = 0; i < categoryViews.Count; i++)
                    {
                        DataPoint point = new DataPoint(ViewsChart.Series["Views"]);
                        point.SetValueXY(categoryViews[i].Key.Name, new object[] { categoryViews[i].Value });
                        ViewsChart.Series["Views"].Points.Add(point);
                    }
                    ViewsChart.DataBind();

                    //CACHE THE DATA
                    cacheWrapper = new CacheWrapper(categoryViews);
                    Cache.Remove(cacheKey);
                    Cache.Add(cacheKey, cacheWrapper, null, LocaleHelper.LocalNow.AddMinutes(5).AddSeconds(-1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
                }
                else
                {
                    //NO CATEGORIES HAVE BEEN VIEWED YET OR PAGE TRACKING IS NOT AVAIALBEL
                    this.Controls.Clear();
                    Panel noViewsPanel = new Panel();
                    noViewsPanel.CssClass = "emptyData";
                    Label noViewsMessage = new Label();
                    noViewsMessage.Text = "No categories have been viewed or page tracking is disabled.";
                    noViewsPanel.Controls.Add(noViewsMessage);
                    this.Controls.Add(noViewsPanel);
                }
            }
            else
            {
                //USE CACHED VALUES
                SortableCollection <KeyValuePair <ICatalogable, int> > categoryViews = (SortableCollection <KeyValuePair <ICatalogable, int> >)cacheWrapper.CacheValue;
                //BUILD BAR CHART
                ViewsChart.Series["Views"].Points.Clear();
                for (int i = 0; i < categoryViews.Count; i++)
                {
                    DataPoint point = new DataPoint(ViewsChart.Series["Views"]);
                    point.SetValueXY(categoryViews[i].Key.Name, new object[] { categoryViews[i].Value });
                    ViewsChart.Series["Views"].Points.Add(point);
                }
                ViewsChart.DataBind();

                ViewsGrid.DataSource = categoryViews;
                ViewsGrid.DataBind();
            }
            DateTime cacheDate = (cacheWrapper != null) ? cacheWrapper.CacheDate : LocaleHelper.LocalNow;

            CacheDate1.Text = string.Format(CacheDate1.Text, cacheDate);
            CacheDate2.Text = string.Format(CacheDate2.Text, cacheDate);
        }
コード例 #19
0
        /// <summary>
        ///     设置单个实例缓存。
        /// </summary>
        /// <param name="key">缓存键。</param>
        /// <param name="value">缓存值。</param>
        /// <param name="options">缓存有效期配置</param>
        public async Task SetTeacherSmartCacheAsync(string key, Teacher value, KolibreCacheOptions options)
        {
            CacheWrapper <Teacher> cacheWrapper = CacheWrapper <Teacher> .BuildCacheWrapper(new List <Teacher> {
                value
            }, CacheType.Object, options);

            await StateManager.SetStateAsync(key, cacheWrapper);
        }
コード例 #20
0
 public CachingUrlParserDecorator(IUrlParser inner, IPersister persister, IWebContext webContext, CacheWrapper cache, HostSection config)
 {
     this.inner = inner;
     this.persister = persister;
     this.webContext = webContext;
     this.cache = cache;
     SlidingExpiration = config.OutputCache.SlidingExpiration ?? TimeSpan.FromMinutes(15);
 }
コード例 #21
0
        public void PutInCache()
        {
            string cacheKeyName     = "PutInCache";
            string cacheContentTest = "PutInCacheContent";

            cacheWrapper.AddToMyCache(cacheKeyName, cacheContentTest, CachePriority.Default, cacheTimeSeconds);
            Assert.AreEqual(CacheWrapper.GetCachedItem(cacheKeyName), cacheContentTest);
        }
コード例 #22
0
        private void initDayChart()
        {
            string       cacheKey     = "E38012C3-C1A0-45a2-A0FF-F32D8DDE043F";
            CacheWrapper cacheWrapper = Cache[cacheKey] as CacheWrapper;

            if (cacheWrapper == null)
            {
                //LOAD VIEWS
                SortableCollection <KeyValuePair <DateTime, decimal> > salesByDay = ReportDataSource.GetSalesForPastDays(7, true);
                //BUILD BAR CHART
                SalesByDayChart.Series["Sales"].Points.Clear();
                for (int i = 0; i < salesByDay.Count; i++)
                {
                    int       roundedTotal = (int)Math.Round(salesByDay[i].Value, 0);
                    DataPoint point        = new DataPoint(SalesByDayChart.Series["Sales"]);
                    point.SetValueXY(salesByDay[i].Key.ToString("MMM d"), new object[] { roundedTotal });
                    SalesByDayChart.Series["Sales"].Points.Add(point);
                }
                SalesByDayChart.DataBind();

                //CACHE THE DATA
                cacheWrapper = new CacheWrapper(salesByDay);
                Cache.Remove(cacheKey);
                Cache.Add(cacheKey, cacheWrapper, null, LocaleHelper.LocalNow.AddMinutes(5).AddSeconds(-1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
            }
            else
            {
                //USE CACHED VALUES
                SortableCollection <KeyValuePair <DateTime, decimal> > salesByDay = (SortableCollection <KeyValuePair <DateTime, decimal> >)cacheWrapper.CacheValue;

                SalesByDayChart.Series["Sales"].Points.Clear();
                for (int i = 0; i < salesByDay.Count; i++)
                {
                    int       roundedTotal = (int)Math.Round(salesByDay[i].Value, 0);
                    DataPoint point        = new DataPoint(SalesByDayChart.Series["Sales"]);
                    point.SetValueXY(salesByDay[i].Key.ToString("MMM d"), new object[] { roundedTotal });
                    SalesByDayChart.Series["Sales"].Points.Add(point);
                }
                SalesByDayChart.DataBind();
            }

            //using (StringWriter writer = new StringWriter())
            //{
            //    SalesByDayChart.Serializer.Content = SerializationContents.Default;
            //    SalesByDayChart.Serializer.Save(writer);
            //    //Dump the contents to a string
            //    string serializedChartContent = writer.ToString();

            //    // GET THE PATH
            //    string theme = Page.Theme;
            //    if (string.IsNullOrEmpty(theme)) theme = Page.StyleSheetTheme;
            //    if (string.IsNullOrEmpty(theme)) theme = "AbleCommerceAdmin";
            //    string path = Server.MapPath("~/App_Themes/" + theme + "/chartstyles.xml");
            //    File.WriteAllText(path, serializedChartContent);
            //}
        }
コード例 #23
0
        public void CacheCallBack()
        {
            string cacheKeyName     = "CacheCallBack";
            string cacheContentTest = "CacheCallBackContent";

            cacheWrapper.AddToMyCache(cacheKeyName, cacheContentTest, CachePriority.Default, cacheTimeSeconds);
            CacheWrapper.RemoveCachedItem(cacheKeyName);

            Assert.IsNull(CacheWrapper.GetCachedItem(cacheKeyName));
        }
コード例 #24
0
        /// <summary>
        /// Checks if a external provider is trying to post a login on this website.
        /// </summary>
        public static bool TryLoginFromProviders(SessionWrapper session, CacheWrapper cache, HttpContextBase context)
        {
            bool logged = false;

            if (TryFinishMembershipLogin(context, session))
            {
                logged = true;
            }
            return(logged);
        }
コード例 #25
0
        public void RemoveCache()
        {
            string cacheKeyName     = "RemoveCache";
            string cacheContentTest = "RemoveCacheContent";

            cacheWrapper.AddToMyCache(cacheKeyName, cacheContentTest, CachePriority.Default, cacheTimeSeconds, cacheCallbackOnRemove);
            CacheWrapper.RemoveCachedItem(cacheKeyName);

            Assert.AreEqual(cacheCallbackOnRemoveAuxiliar, "TESTEOK");
        }
コード例 #26
0
        public void CacheExpiration()
        {
            string cacheKeyName     = "CacheExpiration";
            string cacheContentTest = "CacheExpirationContent";

            cacheWrapper.AddToMyCache(cacheKeyName, cacheContentTest, CachePriority.Default, cacheTimeSeconds);

            Thread.Sleep(cacheTimeSeconds * 1000);

            Assert.IsNull(CacheWrapper.GetCachedItem(cacheKeyName));
        }
コード例 #27
0
 public static List<FinanceInstitutionLinkToAccount> GetLinksToAccount(bool forceSqlLoad)
 {
     var cache = new CacheWrapper();
     var res = cache.GetList<FinanceInstitutionLinkToAccount>(CacheKeyLink);
     if (res == null || forceSqlLoad)
     {
         res = FinanceInstitutionDataAdapter.GetLinksToAccount();
         //save to cache
         cache.SetList(CacheKeyLink, res);
     }
     return res;
 }
コード例 #28
0
        public ActionResult Ingresar(LoginWrapper model)
        {
            if (ModelState.IsValid)
            {
                UserAuthenticationService usuarioService = model.Profesor ? (UserAuthenticationService) new ProfesorService() : (UserAuthenticationService) new AlumnoService();

                UsuarioWrapper usuarioWrapper = usuarioService.GetUsuarioByLogin(model);

                if (usuarioWrapper != null)
                {
                    var cacheWrapper = new CacheWrapper
                    {
                        IdUsuario = usuarioWrapper.IdUsuario,
                        Username  = usuarioWrapper.Username,
                        Nombre    = usuarioWrapper.Nombre,
                        IdPerfil  = Convert.ToInt32(usuarioWrapper.PerfilUsuario),
                    };

                    string loginJson = new JavaScriptSerializer().Serialize(cacheWrapper);

                    var ticket = new FormsAuthenticationTicket(1,
                                                               usuarioWrapper.IdUsuario.ToString(),
                                                               DateTime.Now,
                                                               DateTime.Now.AddDays(2),
                                                               true,
                                                               loginJson,
                                                               FormsAuthentication.FormsCookiePath);

                    string encTicket = FormsAuthentication.Encrypt(ticket);
                    Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

                    FormsAuthentication.SetAuthCookie(loginJson, false);
                    System.Web.HttpContext.Current.Session.Timeout = 2500;

                    UserCache.IdUsuario = usuarioWrapper.IdUsuario;
                    UserCache.Username  = usuarioWrapper.Username;
                    UserCache.IdPerfil  = Convert.ToInt32(usuarioWrapper.PerfilUsuario);

                    if (!string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }

                    return(model.Profesor
                        ? RedirectToAction("HomeProfesores", "Profesores")
                        : RedirectToAction("HomeAlumnos", "Alumnos"));
                }

                ModelState.AddModelError("", "");
            }

            return(View(model));
        }
コード例 #29
0
 public HttpRuntimeCacheWrapper(string cacheKey, CacheWrapper cache)
 {
     lock (CacheLock)
     {
         _cacheDict = cache.Get <Dictionary <string, TValue> >(cacheKey);
         if (_cacheDict == null)
         {
             _cacheDict = new Dictionary <string, TValue>();
             cache.Add(cacheKey, _cacheDict);
         }
     }
 }
コード例 #30
0
 public void Update(Item item)
 {
     CacheWrapper.Invalidate(() =>
     {
         Item found = _items.FirstOrDefault(i => i.Id.Equals(item.Id));
         if (null != found)
         {
             found.ItemName = item.ItemName;
             found.Quantity = item.Quantity;
         }
     }, cacheKey);
 }
コード例 #31
0
 public virtual IEnumerable<Transaction> GetTransactions(int? companyId, bool forceSqlLoad)
 {
     var cache = new CacheWrapper();
     var res = cache.GetList<Transaction>(CacheKey, companyId);
     if (res == null || forceSqlLoad)
     {
         //load from DB
         res = TransactionsDataAdapter.GetTransactions(companyId);
         //save to cache
         cache.SetList(CacheKey, res, companyId);
     }
     return res;
 }
コード例 #32
0
 public virtual List<Tag> GetAll(int? userId, bool forceSqlLoad)
 {
     var cache = new CacheWrapper();
     var res = cache.GetList<Tag>(CacheKey, userId);
     if (res == null || forceSqlLoad)
     {
         //load from DB
         res = TagsDataAdapter.GetTags(userId);
         //save to cache
         cache.SetList(CacheKey, res, userId);
     }
     return res;
 }
コード例 #33
0
 public static List<Account> GetAccounts(int? companyId, bool forceSqlLoad)
 {
     var cache = new CacheWrapper();
     var res = cache.GetList<Account>(CacheKey, companyId);
     if (res == null || forceSqlLoad)
     {
         //load from DB
         res = AccountsDataAdapter.GetAccounts(companyId);
         //save to cache
         cache.SetList(CacheKey, res, companyId);
     }
     return res;
 }
コード例 #34
0
        internal static CacheWrapper GetInstance()
        {
            Cache real = default(Cache);

            RealInstanceFactory(ref real);
            var instance = (CacheWrapper)CacheWrapper.GetWrapper(real);

            InstanceFactory(ref instance);
            if (instance == null)
            {
                Assert.Inconclusive("Could not Create Test Instance");
            }
            return(instance);
        }
コード例 #35
0
        public async Task TestExpiration()
        {
            CacheWrapper cacheMan = new CacheWrapper();

            cacheMan.ClearCache();

            int result = await cacheMan.GetObjectFromCacheAsync(() => testGet1(), "test", 1);

            await Task.Delay(62000);

            result = await cacheMan.GetObjectFromCacheAsync(() => testGet2(), "test", 1);

            Assert.AreEqual(2, result);
        }
コード例 #36
0
        public async Task LinearTest()
        {
            CacheWrapper cacheMan = new CacheWrapper();

            cacheMan.ClearCache();

            int result = await cacheMan.GetObjectFromCacheAsync(() => testGet1(), "test");

            await Task.Delay(2000);

            result = await cacheMan.GetObjectFromCacheAsync(() => testGet2(), "test");

            Assert.AreEqual(1, result);
        }
コード例 #37
0
        /// <summary>
        ///     清理失效 Cache。
        /// </summary>
        private async Task ClearExpiredCacheAsync(object obj)
        {
            IEnumerable <string> stateNames = await StateManager.GetStateNamesAsync();

            foreach (string stateName in stateNames)
            {
                CacheWrapper state = await StateManager.GetStateAsync <CacheWrapper>(stateName);

                if (state.IsExpired())
                {
                    await StateManager.RemoveStateAsync(stateName);
                }
            }
        }
コード例 #38
0
        /// <summary>
        ///     获取 Hash 主键+次键对应的缓存。
        /// </summary>
        /// <param name="firstKey">主键。</param>
        /// <param name="secondKey">次键,为空则返回主键对应的缓存。</param>
        public async Task <string> GetHashCacheAsync(string firstKey, string secondKey)
        {
            ConditionalValue <CacheWrapper> state = await StateManager.TryGetStateAsync <CacheWrapper>(firstKey);

            if (!state.HasValue)
            {
                return(null);
            }

            CacheWrapper cacheWrapper = state.Value;

            // 如果获取缓存时,给定的 key 对应的值类型跟当前类型不一致。
            if (cacheWrapper.CacheType != CacheType.Hash)
            {
                throw new InvalidOperationException($"Operation against a key holding the wrong type '{cacheWrapper.CacheType}'.");
            }
            // 若 first key 过期
            if (cacheWrapper.IsExpired())
            {
                await StateManager.RemoveStateAsync(firstKey);

                return(null);
            }

            // 刷新滑动过期时间。
            (bool needRestore, CacheWrapper cacheWrapper)refreshResult = cacheWrapper.Refresh();
            if (refreshResult.needRestore)
            {
                await StateManager.SetStateAsync(firstKey, refreshResult.cacheWrapper);
            }

            Dictionary <string, string> hashCacheWrappers;

            try
            {
                hashCacheWrappers = cacheWrapper.Cache.FromJson <Dictionary <string, string> >();
            }
            catch
            {
                throw new ArgumentException($"The cache value which cache key '{firstKey}' is not type of Dictionary<string,string>.");
            }

            if (!hashCacheWrappers.TryGetValue(secondKey, out string hashCache))
            {
                return(null);
            }

            return(hashCache);
        }
コード例 #39
0
 public static IServiceCollection AddCache <TCache>(this IServiceCollection services) where TCache : class, ICache
 {
     services.AddSingleton <TCache>();
     services.AddSingleton <ICache>(serviceProvider =>
     {
         return(serviceProvider.GetRequiredService <TCache>());
     });
     services.AddSingleton <ICache <TCache> >(serviceProvider =>
     {
         var cacheInstance = serviceProvider.GetRequiredService <TCache>();
         var cacheWrapper  = new CacheWrapper <TCache>(cacheInstance);
         return(cacheWrapper);
     });
     return(services);
 }
コード例 #40
0
        public async Task <T> GetOrSetAsync <T>(string key, TimeSpan?timeToLive, Func <Task <T> > createAsync)
        {
            var item = await this.GetAsync <CacheWrapper <T> >(key).ConfigureAwait(false);

            if (item != null)
            {
                return(item.Value);
            }

            var value = await createAsync().ConfigureAwait(false);

            await this.SetAsync(key, CacheWrapper <T> .For(value), timeToLive).ConfigureAwait(false);

            return(value);
        }
コード例 #41
0
ファイル: TemplateHelper.cs プロジェクト: jorgebay/nearforums
        /// <summary>
        /// Unpackages the template file and adds a new template in the db.
        /// </summary>
        /// <exception cref="ValidationException">Throws a ValidationException if the posted file is not valid or the application does not have access rights.</exception>
        public static void Add(Template template, Stream packageStream, HttpContextBase context, ITemplatesService service)
        {
            string baseDirectory = null;
            if (packageStream == null)
            {
                throw new ArgumentNullException("postedStream");
            }
            try
            {
                if (packageStream.Length > 1024 * 1024 * 3)
                {
                    throw new ValidationException(new ValidationError("postedFile", ValidationErrorType.MaxLength));
                }
                var cache = new CacheWrapper(context);

                if (cache.Template != null && template.Key != null && cache.Template.Name.ToUpper() == template.Key.ToUpper())
                {
                    throw new ValidationException(new ValidationError("postedFile", ValidationErrorType.DuplicateNotAllowed));
                }

                service.AddOrUpdate(template);

                baseDirectory = Config.General.TemplateFolderPathFull(template.Key);
                SaveFilesToDrive(baseDirectory, packageStream);
                PrepareTemplateBody(baseDirectory + "\\template.html", UrlHelper.GenerateContentUrl(Config.General.TemplateFolderPath(template.Key) + "/", context), context);
                ChopTemplateFile(baseDirectory + "\\template.html");
            }
            catch (ValidationException)
            {
                //Delete the folder
                if (baseDirectory != null)
                {
                    try
                    {
                        SafeIO.Directory_Delete(baseDirectory, true);
                    }
                    catch (UnauthorizedAccessException)
                    {

                    }
                }
                if (template.Id > 0)
                {
                    service.Delete(template.Id);
                }
                throw;
            }
        }
コード例 #42
0
 public static Account GetAccount(int? id, int? companyId, bool forceSqlLoad)
 {
     var cache = new CacheWrapper();
     var res = cache.GetFromList(CacheKey, new Account() { Id = id }, companyId);
     if (res == null || forceSqlLoad)
     {
         //load from DB
         res = AccountsDataAdapter.GetAccount(id, companyId);
         //save to cache
         //if (res == null) // not found in cache->add
         //    cache.AddToList<Account>(CacheKey, res, companyId);
         //else
         //    cache.UpdateList(CacheKey, res, companyId);
     }
     return res;
 }
コード例 #43
0
 public virtual FieldRule GetRule(int? id, int? userId, bool forceSqlLoad)
 {
     var cache = new CacheWrapper();
     var res = cache.GetFromList(CacheKey, new FieldRule() { Id = id }, userId);
     if (res == null || forceSqlLoad)
     {
         //load from DB
         res = RulesDataAdapter.GetRule(id, userId);
         //save to cache
         /*if (res == null) // not found in cache->add
             cache.AddToList<FieldRule>(CacheKey, res, userId);
         else
             cache.UpdateList(CacheKey, res, userId);*/
     }
     return res;
 }
コード例 #44
0
 public virtual int BatchInsert(List<Transaction> list, int? companyId, bool intoCache)
 {
     var cache = new CacheWrapper();
     var res = TransactionsDataAdapter.BatchInsert(list, companyId, DbActionType.Insert);
     if (res == 0)
     {
         //if ok - update cache
         if (intoCache)
         {
             foreach (var entity in list)
             {
                 cache.AddToList(CacheKey, entity, companyId);
             }
         }
     }
     return res;
 }
コード例 #45
0
 private int InsertUpdate(Tag entity, int? userId, DbActionType action, bool intoCache)
 {
     var cache = new CacheWrapper();
     var res = TagsDataAdapter.InsertUpdate(entity, userId, action);
     if (res == 0)
     {
         //if ok - update cache
         if (intoCache)
         {
             if (action == DbActionType.Insert)
                 cache.AddToList(CacheKey, entity, userId);
             if (action == DbActionType.Update)
                 cache.UpdateList(CacheKey, entity, userId);
         }
     }
     return res;
 }
コード例 #46
0
 public virtual Transaction GetTransaction(int? id, int? companyId, bool forceSqlLoad)
 {
     var cache = new CacheWrapper();
     var res = cache.GetFromList(CacheKey, new Transaction { Id = id }, companyId);
     if (res == null || forceSqlLoad)
     {
         bool inCache = res != null;
         //load from DB
         res = TransactionsDataAdapter.GetTransaction(id, companyId);
         //res = new Transaction() { Description = "Test", Category = "Dinner", Amount = 100.20M, Id = 1, Date = DateTime.Now };
         //save to cache
         //if (!inCache) // not found in cache->add
         //    cache.AddToList<Transaction>(CacheKey, res, companyId);
         //else
         //    cache.UpdateList(CacheKey, res, companyId);
     }
     return res;
 }
コード例 #47
0
        public LanguageGatewaySelector(
			IPersister persister,
			IHost host,
			StructureBoundDictionaryCache<int, LanguageInfo[]> languagesCache,
			DescendantItemFinder descendantFinder,
			ILanguageGateway languages,
			CacheWrapper cacheWrapper,
			EngineSection config)
		{
			this.persister = persister;
			this.host = host;
			this.languagesCache = languagesCache;
			this.descendantFinder = descendantFinder;
            this.languages = languages;
			this.cacheWrapper = cacheWrapper;
			Enabled = config.Globalization.Enabled;
			Cache = config.Globalization.Cache;
            LanguagesPerSite = config.Globalization.LanguagesPerSite;
		}
コード例 #48
0
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (!filterContext.Canceled)
            {
                var cache = new CacheWrapper(filterContext.HttpContext.Cache);
                var values = filterContext.RouteData.Values;
                if (!(values.ContainsKey("controller") && values.ContainsKey("action") && values.ContainsKey("id")))
                {
                    throw new ArgumentException("Necessary route values not found in controller context.");
                }
                if (Service == null)
                {
                    throw new NullReferenceException("The service is null, where an instance of ITopicsService was required.");
                }

                if (!cache.VisitedActionAlready(values["controller"].ToString(), values["action"].ToString(), values["id"].ToString(), filterContext.HttpContext.Request.UserHostAddress))
                {
                    Service.AddVisit(Convert.ToInt32(values["id"]));
                }
            }
            base.OnActionExecuted(filterContext);
        }
コード例 #49
0
 public virtual List<Category> GetAll(int? userId, bool forceSqlLoad)
 {
     var cache = new CacheWrapper();
     var res = cache.GetList<Category>(CacheKey, userId);
     if (res == null || forceSqlLoad)
     {
         //load from DB
         res = CategoriesDataAdapter.GetCategories(userId);
         //save to cache
         cache.SetList(CacheKey, res, userId);
     }
     //Localize
     var rm = new ResourceManager(typeof(Resources.Dicts));
     foreach (var item in res)
     {
         var st = rm.GetString("c_" + item.Id.ToString());
         if (!String.IsNullOrEmpty(st))
             item.Name = st;
     }
     //end Localize
     return res;
 }
コード例 #50
0
 /// <summary>
 /// Sets this ip as not beeing flooding, untill the next post
 /// </summary>
 protected virtual void ClearFlooding(ControllerContext context)
 {
     var minTime = MinTime;
     var cache = new CacheWrapper(context.HttpContext);
     cache.SetTimePassed(context.HttpContext.Request.UserHostAddress, minTime);
 }
コード例 #51
0
 public void ResetCache(int? companyId)
 {
     var cache = new CacheWrapper();
     cache.SetList<Transaction>(CacheKey, null, companyId);
 }
コード例 #52
0
ファイル: SecurityHelper.cs プロジェクト: jorgebay/nearforums
        internal static InMemoryTokenManager GetTokenManager(CacheWrapper cache, AuthenticationProvider provider, KeySecretElement providerConfiguration)
        {
            var tokenManager = (InMemoryTokenManager)cache.Cache[provider.ToString() + "TokenManager"];
            if (tokenManager == null)
            {
                tokenManager = new InMemoryTokenManager(providerConfiguration.ApiKey, providerConfiguration.SecretKey);
                cache.Cache[provider.ToString() + "TokenManager"] = tokenManager;
            }

            return tokenManager;
        }
コード例 #53
0
 public virtual Account GetAccountBySms(string cardNumber, int? id_modem, int? id_bank, bool forceSqlLoad)
 {
     var cache = new CacheWrapper();
     Account res = null;
     //load from DB
     res = SmsDataAdapter.GetAccountBySms(cardNumber, id_modem, id_bank);
     //res = cache.GetFromList(CacheKey, new Account() { Id = res.Id }, res.CompanyId);
     if (res == null)
     {
         //save to cache
         //if (res2 == null) // not found in cache->add
         //    cache.AddToList<Account>(CacheKey, res, res.CompanyId);
         //else
         //    cache.UpdateList(CacheKey, res, res.CompanyId);
     }
     return res;
 }
コード例 #54
0
 protected virtual DateTime? GetLatestPosting(ControllerContext context)
 {
     var cache = new CacheWrapper(context.HttpContext);
     return cache.GetLatestPosting(context.HttpContext.Request.UserHostAddress);
 }
コード例 #55
0
 public virtual int ChangeBalance(int? accountId, int? companyId, decimal value)
 {
     var res = AccountsDataAdapter.ChangeBalance(accountId, companyId, value);
     var cache = new CacheWrapper();
     if (res == 0)
     {
         Account account = cache.GetFromList(CacheKey, new Account() { Id = accountId }, companyId);
         if (account != null)
         {
             account.Balance = account.Balance + value;
             cache.UpdateList(CacheKey, account, companyId);
         }
     }
     return res;
 }
コード例 #56
0
 /// <summary>
 /// Stores the date of the latest posting on the state server (cache)
 /// </summary>
 /// <param name="httpContext"></param>
 protected virtual void SetLatestPosting(ControllerContext context)
 {
     var cache = new CacheWrapper(context.HttpContext);
     cache.SetLatestPosting(context.HttpContext.Request.UserHostAddress);
 }
コード例 #57
0
 public void ResetCache(int? companyId)
 {
     var cache = new CacheWrapper();
     cache.SetList<Account>(CacheKey, null, companyId);
 }
コード例 #58
0
 private static int InsertUpdate(Account entity, int? companyId, DbActionType action, bool intoCache)
 {
     var cache = new CacheWrapper();
     var res = AccountsDataAdapter.InsertUpdate(entity, companyId, action);
     if (res == 0)
     {
         //if ok - update cache
         if (intoCache)
         {
             if (action == DbActionType.Insert)
                 cache.AddToList(CacheKey, entity, companyId);
             if (action == DbActionType.Update)
                 cache.UpdateList(CacheKey, entity, companyId);
         }
     }
     return res;
 }
コード例 #59
0
		public DraftRepository(ContentVersionRepository repository, CacheWrapper cache)
		{
			this.Versions = repository;
			this.cache = cache;
		}
コード例 #60
0
 public List<string> GetRolesForUser(string username, bool forceSqlLoad)
 {
     if (username.Length < 1)
     {
         return null;
     }
     var cache = new CacheWrapper();
     var res = cache.GetList<string>("user_roles_" + username);
     if (res == null || forceSqlLoad)
     {
         //load from DB
         res = RoleDataAdapter.GetRolesForUser(username);
         //save to cache
         cache.SetList("user_roles_" + username, res);
     }
     return res;
 }