Inheritance: IEnumerable
        protected string TryFindViewFromViewModel(Cache cache, object viewModel)
        {
            if (viewModel != null)
            {
                var viewModelType = viewModel.GetType();
                var cacheKey = "ViewModelViewName_" + viewModelType.FullName;
                var cachedValue = (string)cache.Get(cacheKey);
                if (cachedValue != null)
                {
                    return cachedValue != NoVirtualPathCacheValue ? cachedValue : null;
                }
                while (viewModelType != typeof(object))
                {
                    var viewModelName = viewModelType.Name;
                    var namespacePart = viewModelType.Namespace.Substring("FODT.".Length);
                    var virtualPath = "~/" + namespacePart.Replace(".", "/") + "/" + viewModelName.Replace("ViewModel", "") + ".cshtml";
                    if (Exists(virtualPath) || VirtualPathProvider.FileExists(virtualPath))
                    {
                        cache.Insert(cacheKey, virtualPath, null /* dependencies */, Cache.NoAbsoluteExpiration, _defaultCacheTimeSpan);
                        return virtualPath;
                    }
                    viewModelType = viewModelType.BaseType;
                }

                // no view found
                cache.Insert(cacheKey, NoVirtualPathCacheValue, null /* dependencies */, Cache.NoAbsoluteExpiration, _defaultCacheTimeSpan);
            }
            return null;
        }
        public async static Task<List<Dictionary<string, object>>> ReadJsonFromFileAndCache(string pathToFile, Cache cache)
        {
            string jsonString = null;
            Dictionary<string, List<Dictionary<string, object>>> jsonData = null;

            try
            {
               jsonString = await Task.Run(() => ReadJsonDataFromFile(pathToFile));
               jsonData = await Task.Run(() => JsonHelper.Parse(jsonString));               
            }
            catch
            {
                jsonString = String.Empty;
            }

            List<Dictionary<string, object>> result = new List<Dictionary<string, object>>();

            foreach(var list in jsonData.Values)
            {
                result.AddRange(list);
            }

            CacheJson(cache, "jsonData", result, pathToFile);            

            return result;
        }
Beispiel #3
0
 /// <summary>
 /// 构造函数
 /// </summary>
 public DotNetCacheManager()
 {
     if (HttpContext.Current != null)
     {
         cache = HttpContext.Current.Cache;
     }
 }
        public BritBoxingTwitterInfo(Cache cache, TwitterService service)
        {
            _cache = cache;
            _service = service;

            UpdateContent();
        }
Beispiel #5
0
 public List<Node> Dump(Cache session)
 {
     return session.Cast<DictionaryEntry>()
         .OrderBy(x => x.Key)
         .Select(x => Process("item", (string)x.Key, x.Value, 0))
         .ToList();
 }
        public static AggregationCategorizationService GetService(Cache cache, String userId)
        {

            try
            {
                if (cache["AggCatService_" + userId] == null)
                {
                    string certificateFile = System.Configuration.ConfigurationManager.AppSettings["PrivateKeyPath"];
                    string password = System.Configuration.ConfigurationManager.AppSettings["PrivateKeyPassword"];
                    X509Certificate2 certificate = new X509Certificate2(certificateFile, password);

                    string consumerKey = System.Configuration.ConfigurationManager.AppSettings["ConsumerKey"];
                    string consumerSecret = System.Configuration.ConfigurationManager.AppSettings["ConsumerSecret"];
                    string issuerId = System.Configuration.ConfigurationManager.AppSettings["SAMLIdentityProviderID"];

                    SamlRequestValidator samlValidator = new SamlRequestValidator(certificate, consumerKey, consumerSecret, issuerId, userId);

                    ServiceContext ctx = new ServiceContext(samlValidator);
                    cache.Add("AggCatService_" + userId, new AggregationCategorizationService(ctx), null, DateTime.Now.AddMinutes(50),
                              Cache.NoSlidingExpiration, CacheItemPriority.High, null);
                }
                return (AggregationCategorizationService)cache["AggCatService_" + userId];
            }
            catch (Exception ex)
            {
                throw new Exception("Unable to create AggCatService: " + ex.Message);
            }
        }
        public LessCssHttpHandler(
            Cache cache,
            IVirtualFileSystemWrapper virtualFileSystemWrapper,
            AssetHandlerSettings assetHandlerConfig)
            : base(cache, virtualFileSystemWrapper, assetHandlerConfig)
        {
		}
Beispiel #8
0
		/// <summary>
		/// Initializes this cache provider.
		/// </summary>
		public void Initialize(CacheProviderInitializationArgs args)
		{
			// This may seem odd, but using the ASP.NET cache outside of an ASP app
			// is perfectly ok, according to this MSDN article:
			// http://msdn.microsoft.com/en-us/library/ms978500.aspx
			_cache = HttpRuntime.Cache;
		}
Beispiel #9
0
        //An example of caching.
        public static IEnumerable<string> GetDummyData(Cache cache)
        {
            var action = new Func<IEnumerable<string>>(() => { return new List<string>() { "foo", "bar", "lipsum" }; });
              var things = ((IEnumerable<string>)BaseCache.GetInsertCacheItem(cache, BaseCacheNames.DummyData.ToString(), action, null));

              return things;
        }
		internal CacheEntry (Cache objManager, string strKey, object objItem,CacheDependency objDependency,
				CacheItemRemovedCallback eventRemove, DateTime dtExpires, TimeSpan tsSpan,
				long longMinHits, bool boolPublic, CacheItemPriority enumPriority )
		{
			if (boolPublic)
				_enumFlags |= Flags.Public;

			_strKey = strKey;
			_objItem = objItem;
			_objCache = objManager;
			_onRemoved += eventRemove;
			_enumPriority = enumPriority;
			_ticksExpires = dtExpires.ToUniversalTime ().Ticks;
			_ticksSlidingExpiration = tsSpan.Ticks;

			// If we have a sliding expiration it overrides the absolute expiration (MS behavior)
			// This is because sliding expiration causes the absolute expiration to be 
			// moved after each period, and the absolute expiration is the value used 
			// for all expiration calculations.
			if (tsSpan.Ticks != Cache.NoSlidingExpiration.Ticks)
				_ticksExpires = DateTime.UtcNow.AddTicks (_ticksSlidingExpiration).Ticks;
			
			_objDependency = objDependency;
			if (_objDependency != null)
				// Add the entry to the cache dependency handler (we support multiple entries per handler)
				_objDependency.Changed += new CacheDependencyChangedHandler (OnChanged); 

			_longMinHits = longMinHits;
		}
        public FieldCacheFacade()
        {
            string xmlFile = HttpContext.Current.Server.MapPath("~/schemamapping.xml");
            CacheDependency xmlDependency = new CacheDependency(xmlFile);

            Cache cache = new Cache();
            cache.Insert("", null, xmlDependency);
        }
 public HttpListenerContextAdapter(HttpListenerContext context, string virtualPath, string physicalPath)
 {
     this.request = new HttpListenerRequestAdapter(context.Request, virtualPath, MakeRelativeUriFunc(context.Request.Url, virtualPath));
     this.response = new HttpListenerResponseAdapter(context.Response);
     this.server = new ConcoctHttpServerUtility(physicalPath);
     this.cache = new Cache();
     this.session = new HttpListenerSessionState();
 }
Beispiel #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Scheduler"/> class.
 /// </summary>
 /// <param name="tasks">The tasks.</param>
 /// <param name="internalCheckInterval">The internal check interval (in seconds).</param>
 public Scheduler(SchedulerTask[] tasks, int internalCheckInterval = 120)
 {
     _tasks = tasks;
     _internalCheckInterval = internalCheckInterval;
     _cache = HttpRuntime.Cache;
     _logger = LogManager.GetLogger("SchedulerTask");
     _logger.Trace("Scheduler created.");
 }
Beispiel #14
0
 public SysCache(string region, IDictionary<string, string> properties)
 {
     this.region = region;
     this.cache = HttpRuntime.Cache;
     this.Configure(properties);
     this.rootCacheKey = this.GenerateRootCacheKey();
     this.StoreRootCacheKey();
 }
Beispiel #15
0
 static SiteCache()
 {
     DayFactor = 17280;
     HourFactor = 720;
     MinuteFactor = 12;
     Factor = 5;
     _cache = HttpRuntime.Cache;
 }
 public static void ClearCache(Cache cache)
 {
     var itms = GetAllUsers(cache);
     foreach (var itm in itms)
     {
         var email = itm.Value["email"].ReadAs<string>();
         cache.Remove(email);
     }
 }
Beispiel #17
0
 public BaseCache(string _logFolder)
     : base(_logFolder)
 {
     //
     // TODO: 在此处添加构造函数逻辑
     //
     this.cache = HttpContext.Current.Cache;
     iCacheTimeMinute = CstHalfHour;
 }
Beispiel #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceCache"/> class.
        /// </summary>
        public ServiceCache()
        {
            m_cache = HttpRuntime.Cache; // works in and out of the ASP.NET process

            if (m_cache == null)
            {
                throw new InvalidOperationException(Resources.Global.UnableToInitializeCache);
            }
        }
 private void SetCache()
 {
     lock(Lock)
     {
         if (HttpContext.Current == null || _cache != null)
             return;
         _cache = HttpContext.Current.Cache;
     }
 }
Beispiel #20
0
        public CacheService(Cache cache)
        {
            if (cache == null)
            {
                throw new ArgumentNullException("cache");
            }

            _cache = cache;
        }
 public CachingSessionSecurityTokenCookieStore(Cache cache, AbstractSessionSecurityTokenCookieStore innerStore)
     : base(null)
 {
     if (cache == null)
     {
         throw new ArgumentNullException("cache");
     }
     m_Cache = cache;
     m_InnerStore = innerStore;
 }
        /// <summary>
        /// Ctor
        /// </summary>
        public ContactRepository()
        {
            this.Cache = HttpRuntime.Cache;

            if (this.Cache == null) return;

            if (this.Cache[CacheKey] == null) {
                this.Cache[CacheKey] = this.Contacts;
            }
        }
        private string GetFromCache(string settingKey, Cache cache)
        {
            var valueFromCache = cache[settingCacheKey + settingKey] as string;
            if (null != valueFromCache)
            {
                return valueFromCache;
            }

            return null;
        }
        /// <summary>
        /// Ctor
        /// </summary>
        public UserRepository()
        {
            this.Cache = HttpRuntime.Cache;

            if (this.Cache == null) return;

            if (this.Cache[CacheKey] == null) {
                this.Cache[CacheKey] = this.Users;
            }
        }
Beispiel #25
0
		public CacheItemLRU (Cache owner, int highWaterMark, int lowWaterMark)
		{
			list = new LinkedList<CacheItem> ();
			dict = new Dictionary<string, LinkedListNode<CacheItem>> (StringComparer.Ordinal);
			revdict = new Dictionary<LinkedListNode<CacheItem>, string> ();
			
			this.highWaterMark = highWaterMark;
			this.lowWaterMark = lowWaterMark;
			this.owner = owner;
		}
 public HttpListenerContextSimulator(HttpListenerContext listenerContext, HttpSessionStateBase session)
 {
     _listenerContext = listenerContext;
     _session = session;
     _response = new HttpListenerResponseWrapper(listenerContext.Response, this);
     _request = new HttpListenerRequestWrapper(listenerContext.Request, () => this.User);
     _items = new Dictionary<object, object>();
     _cache = null;
     _applicationInstance = null;
 }
Beispiel #27
0
        public InfoController(
            ISteamGameParser gameParser,
            ISteamProfileParser profileParser,
            SteamApi.ISteamApi steamApi)
        {
            this._gameParser = gameParser;
            this._profileParser = profileParser;
            this._steamApi = steamApi;

            this._cache = System.Web.HttpContext.Current.Cache;
        }
Beispiel #28
0
 public FakeHttpContext(FakeHttpRequest request, FakeHttpResponse response)
 {
     _response = response;
     _request = request;
     _request._context = this;
     _response._context = this;
     _cache = new Cache();
     _allErrors = new Exception[0];
     _items = new Hashtable();
     User = new GenericPrincipal(new GenericIdentity(string.Empty),new string[0]);
 }
Beispiel #29
0
 /// <summary>
 /// ���췽��
 /// </summary>
 public DefaultCacheStrategy()
 {
     HttpContext context = HttpContext.Current;
     if (context != null)
     {
         _cache = context.Cache;
     }
     else
     {
         _cache = HttpRuntime.Cache;
     }
 }
Beispiel #30
0
 static HiCache()
 {
     HttpContext current = HttpContext.Current;
     if (current != null)
     {
         _cache = current.Cache;
     }
     else
     {
         _cache = HttpRuntime.Cache;
     }
 }
Beispiel #31
0
        public static BaseModuleEntity GetCache(string key)
        {
            BaseModuleEntity result = null;

            if (!string.IsNullOrWhiteSpace(key))
            {
                System.Web.Caching.Cache cache = HttpRuntime.Cache;
                if (cache != null && cache[key] == null)
                {
                    result = cache[key] as BaseModuleEntity;
                }
            }

            return(result);
        }
Beispiel #32
0
        /// <summary>
        /// 设置缓存,指定过期时间,依赖项,优先级
        /// </summary>
        /// <param name="cacheKey">键</param>
        /// <param name="cacheObject">值</param>
        /// <param name="dependency">依赖项</param>
        /// <param name="absoluteExpiration">固定的过期时间</param>
        /// <param name="slidingExpiration">设置最后一次访问多长时间过期,不能小于0,不能超过1年</param>
        /// <param name="cacheItemPriority">设置内存不足,缓存自动清除时,缓存的重要性,可不可以清除</param>
        public void SetCache(string cacheKey, object cacheObject, CacheDependency dependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority cacheItemPriority)
        {
            System.Web.Caching.Cache objCache         = HttpRuntime.Cache;
            CacheItemRemovedCallback onRemoveCallback = new CacheItemRemovedCallback(this.onRemovedCallback);

            objCache.Insert(
                cacheKey,
                cacheObject,
                dependency,
                absoluteExpiration,
                slidingExpiration,
                cacheItemPriority,
                onRemoveCallback
                );
        }
Beispiel #33
0
        /// <summary>
        /// 清除所有缓存
        /// </summary>
        public void RemoveAll()
        {
            System.Web.Caching.Cache cache     = HttpRuntime.Cache;
            IDictionaryEnumerator    CacheEnum = cache.GetEnumerator();
            ArrayList al = new ArrayList();

            while (CacheEnum.MoveNext())
            {
                al.Add(CacheEnum.Key);
            }
            foreach (string key in al)
            {
                cache.Remove(key);
            }
        }
Beispiel #34
0
        /// <summary>
        /// 以列表形式返回已存在的所有缓存
        /// </summary>
        /// <returns></returns>
        public static ArrayList ShowAllCache()
        {
            ArrayList al = new ArrayList();

            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
            if (_cache.Count > 0)
            {
                IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
                while (CacheEnum.MoveNext())
                {
                    al.Add(CacheEnum.Key);
                }
            }
            return(al);
        }
 /// <summary>
 /// Clears all cache items that starts with the key passed.
 /// </summary>
 /// <param name="KeyStartsWith">The start of the key</param>
 public static void ClearCacheByKeySearch(string KeyStartsWith)
 {
     System.Web.Caching.Cache c = System.Web.HttpRuntime.Cache;
     if (c != null)
     {
         System.Collections.IDictionaryEnumerator cacheEnumerator = c.GetEnumerator();
         while (cacheEnumerator.MoveNext())
         {
             if (cacheEnumerator.Key is string && ((string)cacheEnumerator.Key).StartsWith(KeyStartsWith))
             {
                 Cache.ClearCacheItem((string)cacheEnumerator.Key);
             }
         }
     }
 }
Beispiel #36
0
 /// <summary>
 /// 构造函数
 /// </summary>
 static DefaultCacheStrategy()
 {
     lock (syncObj)
     {
         System.Web.HttpContext context = System.Web.HttpContext.Current;
         if (context != null)
         {
             webCache = context.Cache;
         }
         else
         {
             webCache = System.Web.HttpRuntime.Cache;
         }
     }
 }
Beispiel #37
0
        public static PageInfo Init(string path)
        {
            PageInfo pi = null;

            if (Config.Main.PageCache == 0)
            {
                pi = new PageInfo(path);
            }
            else
            {
                System.Web.Caching.Cache cache = HttpContext.Current.Cache;
                string cacheKey = "CachedPageInfo['" + Sota.Web.SimpleSite.Path.Full + "']";
                if (cache[cacheKey] == null)
                {
                    pi = new PageInfo(path);
                    if (pi.Path.Length > 0)
                    {
                        if (pi.IsPagex)
                        {
                            cache.Insert(cacheKey
                                         , pi
                                         , new CacheDependency(new string[] { pi.DataFileName, HttpContext.Current.Request.MapPath(Config.ConfigFolderPath + Keys.UrlPathDelimiter + Keys.ConfigPagex) })
                                         , DateTime.Now.AddMinutes(Config.Main.PageCache)
                                         , TimeSpan.Zero);
                        }
                        else
                        {
                            cache.Insert(cacheKey
                                         , pi
                                         , new CacheDependency(pi.DataFileName)
                                         , DateTime.Now.AddMinutes(Config.Main.PageCache)
                                         , TimeSpan.Zero);
                        }
                    }
                }
                else
                {
                    pi = (PageInfo)cache[cacheKey];
                }
            }
            if (pi.Path.Length == 0)
            {
                return(null);
            }

            HttpContext.Current.Items[Keys.ContextPageInfo] = pi;
            return(pi);
        }
Beispiel #38
0
        /// <summary>
        /// Clears the specified DataSet object from the SQL Cache
        /// </summary>
        public static void ClearCache(SqlCommand cmd)
        {
            if (System.Web.HttpContext.Current == null)
            {
                throw new Exception("Caching is not available outside of web context");
            }

            System.Web.Caching.Cache GlobalCache = System.Web.HttpContext.Current.Cache;
            foreach (System.Collections.DictionaryEntry o in GlobalCache)
            {
                if (o.Key.ToString() == "SQLHelper:" + SqlHelper.GetQueryHashCode(cmd))
                {
                    GlobalCache.Remove(o.Key.ToString());
                }
            }
        }
Beispiel #39
0
        /// <summary>
        /// Clears all DataSet objects from the SQL Cache
        /// </summary>
        public static void ClearCache()
        {
            if (System.Web.HttpContext.Current == null)
            {
                throw new Exception("Caching is not available outside of web context");
            }

            System.Web.Caching.Cache GlobalCache = System.Web.HttpContext.Current.Cache;
            foreach (System.Collections.DictionaryEntry o in GlobalCache)
            {
                if (StringFunctions.StartsWith(o.Key.ToString(), "SQLHelper:"))
                {
                    GlobalCache.Remove(o.Key.ToString());
                }
            }
        }
Beispiel #40
0
 internal LocalCache()
 {
     try
     {
         theCache = H.Cache;//如果配置文件错误会引发此异常。
         ThreadBreak.AddGlobalThread(new ParameterizedThreadStart(ClearState));
         if (AppConfig.Cache.IsAutoCache)
         {
             ThreadBreak.AddGlobalThread(new ParameterizedThreadStart(AutoCache.ClearCache));
         }
     }
     catch (Exception err)
     {
         Log.WriteLogToTxt(err);
     }
 }
Beispiel #41
0
        /// <summary>
        /// Refreshes the cache if there have been updates to the database
        /// </summary>
        /// <returns>The number of exceptions that were thrown while loading the cache</returns>
        public static int Refresh()
        {
            System.Web.Caching.Cache cache = HttpRuntime.Cache;

            while (IsLoading)
            {
                Logging.Module.WriteEvent(new LoggedEvent(EventLevel.Info, "CacheLoadWait", Settings.GetString("LogFormatCacheLoadWait", new Dictionary <string, string>()
                {
                    { "Interval", Settings.GetInt("CacheLoadingSleepInterval").ToString() }
                }), true));

                System.Threading.Thread.Sleep(Settings.GetInt("CacheLoadingSleepInterval"));
            }

            if (!IsLoaded)
            {
                return(ForceRefresh());
            }
            else
            {
                DateTime lastCacheRefreshCheck = (HttpContext.Current.Application["LastComponentCacheRefreshCheck"] == null ? DateTime.MinValue : (DateTime)HttpContext.Current.Application["LastComponentCacheRefreshCheck"]);

                if (lastCacheRefreshCheck <= DateTime.Now.Subtract(new TimeSpan(0, 0, Settings.GetInt("CacheRefreshCheckInterval"))))
                {
                    using (LegionLinqDataContext db = new LegionLinqDataContext(ConfigurationManager.ConnectionStrings["LegionConnectionString"].ToString())) {
                        string ipaddress    = ServerDetails.IPv4Addresses.First().ToString();
                        bool?  refreshCache = null;

                        db.xspGetCacheStatus(ipaddress, ref refreshCache);
                        HttpContext.Current.Application["LastComponentCacheRefreshCheck"] = DateTime.Now;

                        if (refreshCache == true)
                        {
                            return(ForceRefresh());
                        }
                        else
                        {
                            return(-1);
                        }
                    }
                }
                else
                {
                    return(-1);
                }
            }
        }
Beispiel #42
0
        public static BaseStaffEntity GetObjectByCodeByCache(string code)
        {
            BaseStaffEntity result = null;

            System.Web.Caching.Cache cache = HttpRuntime.Cache;
            string cacheObject             = "StaffByCode" + code;

            if (cache != null && cache[cacheObject] == null)
            {
                BaseStaffManager staffManager = new BaseStaffManager();
                result = staffManager.GetObjectByCode(code);
                cache.Add(cacheObject, result, null, DateTime.Now.AddMinutes(10), TimeSpan.Zero, CacheItemPriority.Normal, null);
                System.Console.WriteLine(System.DateTime.Now.ToString(BaseSystemInfo.DateTimeFormat) + " cache Staff");
            }
            result = cache[cacheObject] as BaseStaffEntity;
            return(result);
        }
Beispiel #43
0
        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="entity">实体</param>
        public static void SetCache(BaseDepartmentEntity entity)
        {
            if (entity != null && entity.Id != null)
            {
                string key = string.Empty;
                System.Web.Caching.Cache cache = HttpRuntime.Cache;

                key = "Department" + entity.Id;
                cache.Add(key, entity, null, DateTime.Now.AddHours(16), TimeSpan.Zero, CacheItemPriority.Normal, null);

                key = "DepartmentByCode" + entity.Code;
                cache.Add(key, entity, null, DateTime.Now.AddHours(16), TimeSpan.Zero, CacheItemPriority.Normal, null);

                key = "DepartmentByName" + entity.FullName;
                cache.Add(key, entity, null, DateTime.Now.AddHours(16), TimeSpan.Zero, CacheItemPriority.Normal, null);
            }
        }
Beispiel #44
0
        /// <summary>
        /// 模糊移除某些缓存值
        /// </summary>
        /// <param name="likekey"> 如: housing_follow_json_11200 </param>
        public static void RemoveLike(string likekey)
        {
            System.Web.Caching.Cache _cache    = HttpRuntime.Cache;
            IDictionaryEnumerator    CacheEnum = _cache.GetEnumerator(); // 所有缓存枚举

            string key = "";

            while (CacheEnum.MoveNext())
            {
                key = CacheEnum.Key.ToString();

                if (key.Contains(likekey))
                {
                    Remove(key);
                }
            }
        }
Beispiel #45
0
        public static T Get <T>(this System.Web.Caching.Cache cache, string key, Func <T> method) where T : class
        {
            var data = cache == null ? default(T) : (T)cache[key];

            if (data == null)
            {
                data = method();

                if (1000 > 0 && data != null)
                {
                    lock (sync)
                    {
                        cache.Insert(key, data, null, DateTime.Now.AddSeconds(1000), Cache.NoSlidingExpiration);
                    }
                }
            }
            return(data);
        }
Beispiel #46
0
        /// <summary>
        /// Cache enumerator, allows iteration through the cache.
        /// </summary>
        /// <returns>The current cached item.</returns>
        public static IEnumerator <DictionaryEntry> GetCacheItem()
        {
            // Does a cache object exists.
            if (HttpRuntime.Cache != null)
            {
                // Get the cache object and the enumerator
                // from the caching object.
                System.Web.Caching.Cache dataCache = HttpRuntime.Cache;
                IDictionaryEnumerator    item      = dataCache.GetEnumerator();

                // Iterate through the dictionary entry
                // and return the key value pair.
                while (item.MoveNext())
                {
                    yield return(item.Entry);
                }
            }
        }
Beispiel #47
0
        /// <summary>
        /// Cache value enumerator, allows iteration through all values.
        /// </summary>
        /// <returns>The cache value item.</returns>
        public static IEnumerator <object> GetValue()
        {
            // Does a cache object exists.
            if (HttpRuntime.Cache != null)
            {
                // Get the cache object and the enumerator
                // from the caching object.
                System.Web.Caching.Cache dataCache = HttpRuntime.Cache;
                IDictionaryEnumerator    value     = dataCache.GetEnumerator();

                // Iterate through the dictionary entry
                // and return the value.
                while (value.MoveNext())
                {
                    yield return(value.Value);
                }
            }
        }
Beispiel #48
0
        public static T Add <T>(this System.Web.Caching.Cache cache, string cacheKey, int expirationSeconds, Func <T> method)
        {
            var data = cache == null ? default(T) : (T)cache[cacheKey];

            if (data == null)
            {
                data = method();

                if (expirationSeconds > 0 && data != null)
                {
                    lock (sync)
                    {
                        cache.Insert(cacheKey, data, null, DateTime.Now.AddSeconds(expirationSeconds), Cache.NoSlidingExpiration);
                    }
                }
            }
            return(data);
        }
Beispiel #49
0
        /// <summary>
        /// Cache key enumerator, allows iteration through all keys.
        /// </summary>
        /// <returns>The cache key item.</returns>
        public static IEnumerator <string> GetKey()
        {
            // Does a cache object exists.
            if (HttpRuntime.Cache != null)
            {
                // Get the cache object and the enumerator
                // from the caching object.
                System.Web.Caching.Cache dataCache = HttpRuntime.Cache;
                IDictionaryEnumerator    key       = dataCache.GetEnumerator();

                // Iterate through the dictionary entry
                // and return the key.
                while (key.MoveNext())
                {
                    yield return(key.Key as String);
                }
            }
        }
Beispiel #50
0
        public static void ClearCache()
        {
            System.Web.Caching.Cache cache  = HttpContext.Current.Cache;
            ArrayList             arr       = new ArrayList();
            IDictionaryEnumerator CacheEnum = cache.GetEnumerator();

            while (CacheEnum.MoveNext())
            {
                if (CacheEnum.Key.ToString().StartsWith("CachedPageInfo['"))
                {
                    arr.Add(CacheEnum.Key.ToString());
                }
            }
            foreach (string key in arr)
            {
                cache.Remove(key);
            }
        }
Beispiel #51
0
        /// <summary>
        /// 存缓存中获取数据如果数据不存在则创建数据并将其缓存
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="key">缓存键</param>
        /// <param name="createData">缓存数据不存在时 将要执行的创建数据的方法</param>
        /// <param name="timeSpan">相对过期时间</param>
        /// <returns></returns>
        static public T Get <T>(this WebCache cache, string key, Func <T> createData, TimeSpan timeSpan, CacheItemPriority priority)
        {
            var oldVal = cache.Get(key);

            if (oldVal != null)
            {
                return((T)oldVal);
            }

            T newVal = createData();

            if (newVal != null)
            {
                cache.Insert(key, newVal, null, Cache.NoAbsoluteExpiration, timeSpan, priority, null);
            }

            return((T)newVal);
        }
Beispiel #52
0
        /// <summary>
        /// 从某个角色列表中轮循获取一个用户,在线的用户优先。
        /// </summary>
        /// <param name="roleCode">角色编号</param>
        /// <param name="userId">当前用户主键</param>
        /// <param name="cacheHours">缓存小时数</param>
        /// <returns>用户主键</returns>
        public string GetRandomUserId(IDbHelper dbHelper, string roleCode, string userId, int cacheHours = 4)
        {
            string result = null;

            // 检查缓存里,是否有这个用户的对应客服的主键?若没有进行分配
            System.Web.Caching.Cache cache = HttpRuntime.Cache;
            if (!string.IsNullOrEmpty(userId))
            {
                if (cache != null && cache[userId] == null)
                {
                    var manager = new BaseUserManager(dbHelper);
                    result = manager.GetRandomUserId("Base", roleCode);
                    cache.Add(userId, result, null, DateTime.Now.AddHours(cacheHours), TimeSpan.Zero, CacheItemPriority.Normal, null);
                }
                result = cache[userId] as string;
            }
            return(result);
        }
Beispiel #53
0
        /// <summary>
        /// Clears all keys associated with the component
        /// </summary>
        /// <param name="component">the component to clear</param>
        private static void ClearComponent(string component)
        {
            System.Web.Caching.Cache cache = HttpRuntime.Cache;
            string cachemasterkey          = BuildComponentKey(component, COMPONENT_MASTER_KEY);

            lock (_componentMasterKeyLock) {
                if (cache[cachemasterkey] != null)
                {
                    string[] keys = ((List <string>)cache[cachemasterkey]).ToArray();
                    foreach (string key in keys)
                    {
                        cache.Remove(BuildComponentKey(component, key));
                    }

                    cache.Remove(cachemasterkey);
                }
            }
        }
Beispiel #54
0
        /// <summary>
        /// 按父节点获取列表
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="parentId">父节点</param>
        /// <returns>数据表</returns>
        public DataTable GetDataTableByParent(BaseUserInfo userInfo, string parentId)
        {
            DataTable result    = null;
            var       parameter = ServiceParameter.CreateWithMessage(userInfo
                                                                     , MethodBase.GetCurrentMethod()
                                                                     , this.serviceName
                                                                     , AppMessage.OrganizeService_GetProvince);

            System.Web.Caching.Cache cache = HttpRuntime.Cache;
            string cacheObject             = "Area";

            if (!string.IsNullOrEmpty(parentId))
            {
                cacheObject = "Area" + parentId;
            }
            if (cache == null || cache[cacheObject] == null)
            {
                lock (locker)
                {
                    if (cache == null || cache[cacheObject] == null)
                    {
                        ServiceUtil.ProcessUserCenterReadDb(userInfo, parameter, (dbHelper) =>
                        {
                            // 这里是条件字段
                            List <KeyValuePair <string, object> > parameters = new List <KeyValuePair <string, object> >();
                            parameters.Add(new KeyValuePair <string, object>(BaseAreaEntity.FieldParentId, parentId));
                            parameters.Add(new KeyValuePair <string, object>(BaseAreaEntity.FieldEnabled, 1));
                            parameters.Add(new KeyValuePair <string, object>(BaseAreaEntity.FieldDeletionStateCode, 0));
                            // 用静态方法获取数据,提高效率,获取列表,指定排序字段
                            result = DbLogic.GetDataTable(dbHelper, BaseAreaEntity.TableName, parameters, 0, BaseAreaEntity.FieldSortCode, null);
                            // var manager = new BaseAreaManager(dbHelper, userInfo);
                            // result = manager.GetDataTable(parameters, BaseAreaEntity.FieldSortCode);
                            result.DefaultView.Sort = BaseAreaEntity.FieldSortCode;
                            result.TableName        = BaseAreaEntity.TableName;
                            // 这里可以缓存起来,提高效率
                            cache.Add(cacheObject, result, null, DateTime.Now.AddMinutes(30), TimeSpan.Zero, CacheItemPriority.Normal, null);
                            System.Console.WriteLine(System.DateTime.Now.ToString(BaseSystemInfo.DateTimeFormat) + " cache Area " + parentId);
                        });
                    }
                }
            }
            result = cache[cacheObject] as DataTable;
            return(result);
        }
Beispiel #55
0
        /// <summary>
        /// Add the current child item to the cache.
        /// </summary>
        /// <param name="modelObjectName">The model object name dependancy.</param>
        /// <param name="cacheKey">The specific item cache key to the model dependancy.</param>
        /// <param name="value">The object the cache.</param>
        /// <param name="cacheDuration">The duration of the cache item.</param>
        public static void Add(string modelObjectName, string cacheKey, object value, double cacheDuration)
        {
            _cacheDuration = cacheDuration;

            // Does a cache object exists.
            if (HttpRuntime.Cache == null)
            {
                CreateHttpRuntime();
            }

            // Get the current application cache object.
            System.Web.Caching.Cache dataCache = HttpRuntime.Cache;

            // If the current dependancy does not exist
            // add the dependancy to the cache.
            if (dataCache[modelObjectName] == null)
            {
                dataCache[modelObjectName] = DateTime.Now;
            }

            // Create a new dependancy array
            // with the current model object
            // as the dependancy.
            string[] modelObjectNames = new string[1];
            modelObjectNames[0] = modelObjectName;

            // Add a new cache dependancy.
            System.Web.Caching.CacheDependency dependency =
                new System.Web.Caching.CacheDependency(null, modelObjectNames);

            // Indicates no expiery.
            if (cacheDuration < (double)0.0)
            {
                // Insert the current object into the cache.
                dataCache.Insert(cacheKey, value);
            }
            else
            {
                // Insert the current object into the cache.
                dataCache.Insert(cacheKey, value, dependency,
                                 DateTime.UtcNow.AddSeconds(cacheDuration), System.Web.Caching.Cache.NoSlidingExpiration);
            }
        }
Beispiel #56
0
    /// <summary>
    /// 启动更新数据缓存
    /// </summary>
    /// <param name="obj"></param>
    public void ExecUpdateCacheData(object obj)
    {
        try
        {
            System.Web.Caching.Cache currCache = HttpRuntime.Cache;
            int cacheMinute = 50;

            //加载缓存服务配置
            DataTable dtservconfig = BaseServiceUtility.GetServiceConfig(APPConfig.GetAPPConfig().GetConfigValue("ServiceConfigPath", ""));
            currCache.Insert("serviceConfig", dtservconfig, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, cacheMinute, 0));

            //缓存默认公共语言包
            string    defaultlang        = APPConfig.GetAPPConfig().GetConfigValue("currlang", "");
            string    commoni18nLangPath = string.Format(APPConfig.GetAPPConfig().GetConfigValue("Commoni18nLang", ""), defaultlang);
            DataTable i18nCommonCurrLang = BaseServiceUtility.GetI18nLang(commoni18nLangPath);
            currCache.Insert("i18nCommonCurrLang", i18nCommonCurrLang, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, cacheMinute, 0));

            //缓存默认各模块语言包,多个模块独立累加
            string    FrameNodei18nLang     = string.Format(APPConfig.GetAPPConfig().GetConfigValue("FrameNodei18nLang", ""), defaultlang);
            DataTable i18nFrameNodei18nLang = BaseServiceUtility.GetI18nLang(FrameNodei18nLang);
            currCache.Insert("i18nFrameNodei18nLang", i18nFrameNodei18nLang, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, cacheMinute, 0));


            //缓存数据节点
            DistributeDataNodeManagerParams distManagerParam = new DistributeDataNodeManagerParams(); //分布式管理参数
            FrameNodeBizCommon fnodecom = new FrameNodeBizCommon();
            distManagerParam = fnodecom.GetDistributeDataNodeManager("1");
            if (distManagerParam.DistributeDataNodes.Count > 0)
            {
                currCache.Insert("dataNodes", distManagerParam, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, cacheMinute, 0));
            }

            //缓存业务节点
            DataTable dtbiznodeaddrconfig = BaseServiceUtility.GetBizNodesConfig(APPConfig.GetAPPConfig().GetConfigValue("XmldataPath", "") + "\\SSY_BIZNODE_ADDR.xml");
            currCache.Insert("bizNodeConfig", dtbiznodeaddrconfig, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, cacheMinute, 0));

            Common.Utility.RecordLog("完成节点中心配置缓存!", this.logpathForDebug, this.isLogpathForDebug);
        }
        catch (Exception ex)
        {
            Common.Utility.RecordLog("配置节点中心缓存,发生异常!原因:" + ex.Message, this.logpathForDebug, this.isLogpathForDebug);
        }
    }
Beispiel #57
0
        /// <summary>
        /// Retrieve all cached items
        /// </summary>
        /// <returns>A hastable containing all cacheitems</returns>
        public static System.Collections.Hashtable ReturnCacheItemsOrdred()
        {
            System.Collections.Hashtable ht = new System.Collections.Hashtable();
            System.Web.Caching.Cache     c  = System.Web.HttpRuntime.Cache;
            if (c != null)
            {
                System.Collections.IDictionaryEnumerator cacheEnumerator = c.GetEnumerator();
                while (cacheEnumerator.MoveNext())
                {
                    if (ht[c[cacheEnumerator.Key.ToString()].GetType().ToString()] == null)
                    {
                        ht.Add(c[cacheEnumerator.Key.ToString()].GetType().ToString(), new System.Collections.ArrayList());
                    }

                    ((System.Collections.ArrayList)ht[c[cacheEnumerator.Key.ToString()].GetType().ToString()]).Add(cacheEnumerator.Key.ToString());
                }
            }
            return(ht);
        }
Beispiel #58
0
        public T Get <T>(string CacheKey) where T : class, new()
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            if (objCache[CacheKey] == null)
            {
                T obj = GetFileCache <T>(CacheKey);
                if (obj == null)
                {
                    return(null);
                }
                else
                {
                    Add(CacheKey, obj);
                    return(obj);
                }
            }

            return(objCache[CacheKey] as T);
        }
Beispiel #59
0
        /// <summary>
        /// 获取当前应用程序指定CacheKey的Cache值
        /// </summary>
        /// <param name="CacheKey">
        /// <returns></returns>y
        public object Get(string CacheKey)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            if (objCache[CacheKey] == null)
            {
                object obj = GetFileCache(CacheKey);
                if (obj == null)
                {
                    return(null);
                }
                else
                {
                    Add(CacheKey, obj);
                    return(obj);
                }
            }

            return(objCache[CacheKey]);
        }
Beispiel #60
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SysCacheRegion"/> class.
        /// </summary>
        /// <param name="name">The name of the region</param>
        /// <param name="settings">The configuration settings for the cache region</param>
        /// <param name="additionalProperties">additional NHibernate configuration properties</param>
        public SysCacheRegion(string name, CacheRegionElement settings, IDictionary <string, string> additionalProperties)
        {
            //validate the params
            if (String.IsNullOrEmpty(name))
            {
                log.Info("No region name specified for cache region. Using default name of 'nhibernate'");
                name = "nhibernate";
            }

            _webCache = HttpRuntime.Cache;
            _name     = name;

            //configure the cache region based on the configured settings and any relevant nhibernate settings
            Configure(settings, additionalProperties);

            //creaet the cache key that will be used for the root cache item which all other
            //cache items are dependent on
            _rootCacheKey = GenerateRootCacheKey();
        }