protected void Page_Load(object sender, EventArgs e)
        {
            var filePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\file.txt";
            if (!File.Exists(filePath))
            {
                File.WriteAllText(filePath, "content");
            }

            if (this.Cache["file"] == null)
            {
                var dependency = new CacheDependency(filePath);
                var content = string.Format("{0} [{1}]", File.ReadAllText(filePath), DateTime.Now);
                Cache.Insert(
                    "file",                    // key
                    content,                   // object
                    dependency,                // dependencies
                    DateTime.Now.AddHours(1),  // absolute exp.
                    TimeSpan.Zero,             // sliding exp.
                    CacheItemPriority.Default, // priority
                    null);                     // callback delegate
            }

            this.filePathSpan.InnerText = filePath;
            this.currentTimeSpan.InnerText = this.Cache["file"] as string;
        }
Пример #2
0
        /// <summary>
        /// Versions the specified relative path.
        /// </summary>
        /// <param name="relativePath">The relative path.</param>
        /// <returns>The versioned relative path.</returns>
        public static string Version(string relativePath)
        {
            if (relativePath == null) return null;

            if (HttpRuntime.Cache[relativePath] == null)
            {
                var absolutePath = HostingEnvironment.MapPath(relativePath);
                if (!File.Exists(absolutePath) && relativePath.StartsWith("/", StringComparison.OrdinalIgnoreCase))
                {
                  absolutePath = HostingEnvironment.MapPath("~" + relativePath);
                }

                if (absolutePath != null && File.Exists(absolutePath))
                {
                    using (var stream = File.OpenRead(absolutePath))
                    using (var sha = new SHA1Managed())
                    {
                        var hash = sha.ComputeHash(stream);
                        var hashString = BitConverter.ToString(hash).Replace("-", string.Empty);

                        if (relativePath.StartsWith("~", StringComparison.OrdinalIgnoreCase))
                        {
                          relativePath = VirtualPathUtility.ToAbsolute(relativePath);
                        }

                        var versionedUrl = relativePath + "?v=" + hashString;

                        using (var cacheDependency = new CacheDependency(absolutePath)) HttpRuntime.Cache.Insert(relativePath, versionedUrl, cacheDependency);
                    }
                }
            }

            return HttpRuntime.Cache[relativePath] as string;
        }
Пример #3
0
 /// <summary>
 /// 添加缓存
 /// </summary>
 /// <param name="value">缓存值</param>
 /// <param name="cacheKey">缓存键</param>
 /// <param name="dependency">缓存依赖项(sql表依赖 请使用 SqlCacheDependency )</param>
 public static void InsertCache(object value, string cacheKey, CacheDependency dependency)
 {
     if (GetCache(cacheKey) == null)
     {
         HttpRuntime.Cache.Insert(cacheKey, value);
     }
 }
 internal override void CacheBuildResult(string cacheKey, BuildResult result, long hashCode, DateTime utcStart)
 {
     if (!BuildResultCompiledType.UsesDelayLoadType(result))
     {
         ICollection virtualPathDependencies = result.VirtualPathDependencies;
         CacheDependency dependencies = null;
         if (virtualPathDependencies != null)
         {
             dependencies = result.VirtualPath.GetCacheDependency(virtualPathDependencies, utcStart);
             if (dependencies != null)
             {
                 result.UsesCacheDependency = true;
             }
         }
         if (result.CacheToMemory)
         {
             CacheItemPriority normal;
             BuildResultCompiledAssemblyBase base2 = result as BuildResultCompiledAssemblyBase;
             if (((base2 != null) && (base2.ResultAssembly != null)) && !base2.UsesExistingAssembly)
             {
                 string assemblyCacheKey = BuildResultCache.GetAssemblyCacheKey(base2.ResultAssembly);
                 Assembly assembly = (Assembly) this._cache.Get(assemblyCacheKey);
                 if (assembly == null)
                 {
                     this._cache.UtcInsert(assemblyCacheKey, base2.ResultAssembly, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
                 }
                 CacheDependency dependency2 = new CacheDependency(0, null, new string[] { assemblyCacheKey });
                 if (dependencies != null)
                 {
                     AggregateCacheDependency dependency3 = new AggregateCacheDependency();
                     dependency3.Add(new CacheDependency[] { dependencies, dependency2 });
                     dependencies = dependency3;
                 }
                 else
                 {
                     dependencies = dependency2;
                 }
             }
             string memoryCacheKey = GetMemoryCacheKey(cacheKey);
             if (result.IsUnloadable)
             {
                 normal = CacheItemPriority.Normal;
             }
             else
             {
                 normal = CacheItemPriority.NotRemovable;
             }
             CacheItemRemovedCallback onRemoveCallback = null;
             if (result.ShutdownAppDomainOnChange || (result is BuildResultCompiledAssemblyBase))
             {
                 if (this._onRemoveCallback == null)
                 {
                     this._onRemoveCallback = new CacheItemRemovedCallback(this.OnCacheItemRemoved);
                 }
                 onRemoveCallback = this._onRemoveCallback;
             }
             this._cache.UtcInsert(memoryCacheKey, result, dependencies, result.MemoryCacheExpiration, result.MemoryCacheSlidingExpiration, normal, onRemoveCallback);
         }
     }
 }
Пример #5
0
 public static void Insert(string key, object obj, CacheDependency dep, int seconds, CacheItemPriority priority)
 {
     if (obj != null)
     {
         _cache.Insert(key, obj, dep, DateTime.Now.AddSeconds((double) (Factor * seconds)), TimeSpan.Zero, priority, null);
     }
 }
Пример #6
0
 /// <summary>
 /// 添加缓存
 /// </summary>
 /// <param name="value">缓存值</param>
 /// <param name="cacheKey">缓存键</param>
 /// <param name="dependency">缓存依赖项(sql表依赖 请使用 SqlCacheDependency )</param>
 /// <param name="expriationTime">缓存滑动(连续访问时间)过期时间</param>
 public static void InsertCache(object value, string cacheKey, CacheDependency dependency, TimeSpan expriationTime)
 {
     if (GetCache(cacheKey) == null)
     {
         HttpRuntime.Cache.Insert(cacheKey, value, dependency, System.Web.Caching.Cache.NoAbsoluteExpiration, expriationTime);
     }
 }
Пример #7
0
 /// <summary>/// 按小时缓存数据// </summary>
 /// <param name="CacheKey">索引键值</param>
 /// <param name="objObject">缓存对象</param>
 /// <param name="cacheDepen">依赖对象</param>
 /// <param name="Hours">缓存小时)</param>
 public static void InsertCacheHours(string CacheKey, object objObject, System.Web.Caching.CacheDependency dep, int Hours)
 {
     if (objObject != null)
     {
         objCache.Insert(CacheKey, objObject, dep, DateTime.Now.AddHours(Hours), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
     }
 }
Пример #8
0
 /// <summary>
 /// 本地缓存写入(默认缓存20min),依赖项
 /// </summary>
 /// <param name="name">key</param>
 /// <param name="value">value</param>
 /// <param name="cacheDependency">依赖项</param>
 public static void Set(string name, object value, CacheDependency cacheDependency)
 {
     if (value != null)
     {
         HttpRuntime.Cache.Insert(name, value, cacheDependency, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(10), CacheItemPriority.Normal, null);
     }
 }
Пример #9
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string rootPath = MapPath("~/");

            DirectoryInfo rootDirectory = new DirectoryInfo(rootPath);

            var files = rootDirectory.GetFiles();
            int filesCount = files.Length;

            this.ListViewFiles.DataSource = files;
            this.ListViewFiles.DataBind();

            if (Cache["FilesCount"] == null)
            {
                var dependency = new CacheDependency(rootPath);
                Cache.Insert(
                    "FilesCount", // key
                    filesCount, // object
                    dependency, // dependencies
                    DateTime.Now.AddHours(1), // absolute expiration
                    TimeSpan.Zero, // sliding expiration
                    CacheItemPriority.Default, // priority
                    null); // callback delegate
            }

            this.LiteralRootDirectory.Text = string.Format(
                "Root directory: {0} ({1} files)",
                rootPath,
                Cache["FilesCount"]);
        }
Пример #10
0
        /// <summary>
        /// 获取缓存对象
        /// </summary>
        /// <param name="context">当前执行上下文</param>
        /// <param name="cacheKey">缓存名称</param>
        /// <param name="cacheDependencies">缓存依赖类型</param>
        /// <param name="absoluteExpiration">过期时间</param>
        /// <param name="slidingExpiration">用于设置可调过期时间,它表示当离最后访问超过某个时间段后就过期</param>
        /// <param name="func">要执行的委托方法</param>
        /// <returns>缓存对象</returns>
        public static object Cache(
            HttpContext context,
            string cacheKey,
            CacheDependency cacheDependencies,
            DateTime absoluteExpiration,
            TimeSpan slidingExpiration,
            Func<object> func)
        {
            var cache = context.Cache;
            var content = cache.Get(cacheKey);

            if (content == null)
            {
                lock (lockObject) //线程安全的添加缓存
                {
                    content = cache.Get(cacheKey);
                    if (content == null)
                    {
                        content = func();
                        cache.Insert(cacheKey, content, cacheDependencies, absoluteExpiration, slidingExpiration);
                    }
                }
            }
            return content;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var directoryName = Server.MapPath("\\Common");

            DirectoryInfo dirInfo = new DirectoryInfo(directoryName);
            string[] filenames = dirInfo.GetFiles().Select(i => i.Name).ToArray();
            string[] fullNames = dirInfo.GetFiles().Select(i => i.FullName).ToArray();

            if (this.Cache["files"] == null)
            {
                var dependency = new CacheDependency(fullNames);
                var content = string.Join(", ", filenames) + DateTime.Now;
                Cache.Insert(
                    "files",                    // key
                    content,                   // object
                    dependency,                // dependencies
                    DateTime.Now.AddHours(1),  // absolute exp.
                    TimeSpan.Zero,             // sliding exp.
                    CacheItemPriority.Default, // priority
                    null);                     // callback delegate
            }

            this.filePathSpan.InnerText = string.Join(", ", filenames) + DateTime.Now;
            this.currentTimeSpan.InnerText = this.Cache["files"] as string;
        }
        public void SaveDataCache(string request, int expiredSecond, int expiredMinute, int expiredHour, object objet, string dependancyKey = ""
            , bool lowPriority = false, bool autoReload = false)
        {
            if (IsActive && HttpRuntime.Cache.EffectivePercentagePhysicalMemoryLimit > 5)
            {
                if (objet != null)
                {
                    if (HttpRuntime.Cache[request] != null)
                        HttpRuntime.Cache[request] = objet;
                    else
                    {
                        CacheDependency dependance = null;
                        if (!String.IsNullOrEmpty(dependancyKey))
                        {
                            dependance = new CacheDependency(null, new string[] { dependancyKey });
                        }

                        CacheItemPriority priorite = (lowPriority ? CacheItemPriority.Low : CacheItemPriority.Normal);

                        if (autoReload)
                            HttpRuntime.Cache.Insert(request, objet, dependance, DateTime.Now.Add(new TimeSpan(expiredHour, expiredMinute, expiredSecond)), TimeSpan.Zero, priorite, RemovedCallback);
                        else
                            HttpRuntime.Cache.Insert(request, objet, dependance, DateTime.Now.Add(new TimeSpan(expiredHour, expiredMinute, expiredSecond)), TimeSpan.Zero, priorite, null);

                        if (!_keys.Contains(request))
                            _keys.Add(request);
                    }
                }
            }
        }
        protected virtual void SaveDataToCacheInternal(string key, object data, CacheDependency dependency)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException("key");
            }
            if (!this.Enabled)
            {
                throw new InvalidOperationException(System.Web.SR.GetString("DataSourceCache_CacheMustBeEnabled"));
            }
            DateTime noAbsoluteExpiration = Cache.NoAbsoluteExpiration;
            TimeSpan noSlidingExpiration = Cache.NoSlidingExpiration;
            switch (this.ExpirationPolicy)
            {
                case DataSourceCacheExpiry.Absolute:
                    noAbsoluteExpiration = DateTime.UtcNow.AddSeconds((this.Duration == 0) ? ((double) 0x7fffffff) : ((double) this.Duration));
                    break;

                case DataSourceCacheExpiry.Sliding:
                    noSlidingExpiration = TimeSpan.FromSeconds((double) this.Duration);
                    break;
            }
            AggregateCacheDependency dependencies = new AggregateCacheDependency();
            string[] cachekeys = null;
            if (this.KeyDependency.Length > 0)
            {
                cachekeys = new string[] { this.KeyDependency };
                dependencies.Add(new CacheDependency[] { new CacheDependency(null, cachekeys) });
            }
            if (dependency != null)
            {
                dependencies.Add(new CacheDependency[] { dependency });
            }
            HttpRuntime.CacheInternal.UtcInsert(key, data, dependencies, noAbsoluteExpiration, noSlidingExpiration);
        }
        static IHtmlString RenderFileWithVersion(HtmlHelper html, string fileName,string fileWrap)
        {
            //if (fileName.StartsWith("~"))
            //{
            //    var area =(string) html.ViewContext.RouteData.DataTokens["area"];
            //    if (area.IsNotNull())
            //        fileName = fileName.Replace("~", "/Areas/" + area);

            //}

            string mcvscript = string.Empty;
            if (fileName.IndexOf('?') > 0)
            {
                mcvscript = string.Format(JsFileWrap, fileName);
            }
            else
            {
                var filewithverison = HttpRuntime.Cache[fileName];
                if (filewithverison == null)
                {
                    var filePath = PathHelper.MapPath(fileName);
                    var version = new FileInfo(filePath).LastWriteTime.ToString("yyyyMMddHHmmss");
                    filewithverison = fileName + "?" + version;
                    CacheDependency cdy = new CacheDependency(filePath);
                    HttpRuntime.Cache.Insert(fileName, filewithverison, cdy);

                }
                mcvscript = string.Format(fileWrap, filewithverison);
            }

            return html.Raw(mcvscript);
        }
		public static void Insert(string key, object value, CacheDependency dependency, TimeSpan timeframe, CacheItemPriority priority)
		{
			if (value != null)
			{
				_cache.Insert(key, value, dependency, DateTime.Now.Add(timeframe), Cache.NoSlidingExpiration, priority, null);
			}
		}
 public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemUpdateCallback onUpdateCallback)
 {
     if (((dependencies == null) && (absoluteExpiration == NoAbsoluteExpiration)) && (slidingExpiration == NoSlidingExpiration))
     {
         throw new ArgumentException(System.Web.SR.GetString("Invalid_Parameters_To_Insert"));
     }
     if (onUpdateCallback == null)
     {
         throw new ArgumentNullException("onUpdateCallback");
     }
     DateTime utcAbsoluteExpiration = DateTimeUtil.ConvertToUniversalTime(absoluteExpiration);
     this._cacheInternal.DoInsert(true, key, value, null, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.NotRemovable, null, true);
     string[] cachekeys = new string[] { key };
     CacheDependency expensiveObjectDependency = new CacheDependency(null, cachekeys);
     if (dependencies == null)
     {
         dependencies = expensiveObjectDependency;
     }
     else
     {
         AggregateCacheDependency dependency2 = new AggregateCacheDependency();
         dependency2.Add(new CacheDependency[] { dependencies, expensiveObjectDependency });
         dependencies = dependency2;
     }
     this._cacheInternal.DoInsert(false, "w" + key, new SentinelEntry(key, expensiveObjectDependency, onUpdateCallback), dependencies, utcAbsoluteExpiration, slidingExpiration, CacheItemPriority.NotRemovable, s_sentinelRemovedCallback, true);
 }
Пример #17
0
		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;
		}
Пример #18
0
        public List<CombinerModel> ReadData(string fileName)
        {
            List<CombinerModel> list = new List<CombinerModel>();
            object obj = CacheHelper.ReadData(ConstMember.CONFIG_CACHE_ID);

            if (obj == null)
            {
                string strFilePath = GetAbsolutPath(fileName);

                try
                {
                    obj = XMLHelper.LoadFromXml(strFilePath, list.GetType());
                    CacheDependency dep = new CacheDependency(strFilePath);
                    CacheHelper.WriteData(ConstMember.CONFIG_CACHE_ID, dep, obj);
                }
                catch
                {
                }
            }

            if (obj != null && obj is List<CombinerModel>)
            {
                list = obj as List<CombinerModel>;
            }

            return list;
        }
Пример #19
0
 public void Insert(string key, object value, CacheDependency dependencies,
     DateTime absoluteExpiration, TimeSpan slidingExpiration,
     CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
 {
     _cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration,
         priority, onRemoveCallback);
 }
Пример #20
0
        private const long CACHE_EXPIRED = 31104000; // tính theo giây

        public HandlerMapping()
        {
            if (null != HttpContext.Current.Cache[CACHE_NAME])
            {
                try
                {
                    this.Domains = (DomainCollection)HttpContext.Current.Cache[CACHE_NAME];
                    return;
                }
                catch
                {
                }
            }

            string configFilePath = System.Web.HttpContext.Current.Server.MapPath("/HandlerMapping/HandlerMapping.config");

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(configFilePath);

            this.Domains = new DomainCollection();

            if (xmlDoc != null && xmlDoc.DocumentElement.ChildNodes.Count > 0)
            {
                XmlNodeList nodeDomains = xmlDoc.DocumentElement.SelectNodes("//AllowDomains/AllowDomain");

                for (int domainIndex = 0; domainIndex < nodeDomains.Count; domainIndex++)
                {
                    string domainName = nodeDomains[domainIndex].Attributes["domain"].Value;
                    //string idenity = nodeDomains[domainIndex].Attributes["idenity"].Value;
                    Domain newDomain = new Domain(domainName, "");

                    XmlNodeList nodeHandlers = nodeDomains[domainIndex].SelectNodes("handler");

                    for (int handlerIndex = 0; handlerIndex < nodeHandlers.Count; handlerIndex++)
                    {
                        string key = nodeHandlers[handlerIndex].Attributes["key"].Value;
                        string assembly = nodeHandlers[handlerIndex].Attributes["assembly"].Value;
                        string method = nodeHandlers[handlerIndex].Attributes["method"].Value;
                        string parameters = nodeHandlers[handlerIndex].Attributes["params"].Value;
                        int cacheExpiration = Lib.Object2Integer(nodeHandlers[handlerIndex].Attributes["cache"].Value);
                        string allowRequestKey = nodeHandlers[handlerIndex].Attributes["AllowRequestKey"].Value;
                        
                        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
                        List<string> listOfParams = new List<string>();
                        if (parameters != "")
                        {
                            listOfParams = jsSerializer.Deserialize<List<string>>("[" + parameters + "]");
                        }

                        newDomain.Handlers.Add(new Handler(key, assembly, method, cacheExpiration, allowRequestKey, listOfParams.ToArray()));
                    }

                    this.Domains.Add(newDomain);
                }

                CacheDependency fileDependency = new CacheDependency(configFilePath);
                HttpContext.Current.Cache.Insert(CACHE_NAME, this.Domains, fileDependency, DateTime.Now.AddSeconds(CACHE_EXPIRED), TimeSpan.Zero, CacheItemPriority.Normal, null);

            }
        }
Пример #21
0
 public static object GetFileFromCache(string FilePath)
 {
     try
     {
         if (FilePath != null)
         {
             object objCache = System.Web.HttpRuntime.Cache.Get(FilePath);
             if (objCache == null)
             {
                 CacheDependency dependancy = new System.Web.Caching.CacheDependency(FilePath);
                 XDocument       document   = XDocument.Load(FilePath);
                 System.Web.HttpRuntime.Cache.Insert(FilePath, document, dependancy, DateTime.Now.AddDays(1), System.Web.Caching.Cache.NoSlidingExpiration);
                 return(document);
             }
             else
             {
                 return(objCache);
             }
         }
         else
         {
             return(null);
         }
     }
     catch (Exception ex)
     {
         return(null);
     }
 }
Пример #22
0
        public static Dictionary<string, string> GetResources()
        {
            string key = "_CVV_RESOURCES_";

            Dictionary<string, string> resources = HttpRuntime.Cache.Get(key) as Dictionary<string, string>;

            if (resources == null)
            {
                string fp = WebAppContext.Server.MapPath(string.Format("~/Languages/{0}/Resources.xml", WebAppContext.Session.LanguageCode));
                CacheDependency dp = new CacheDependency(fp);
                resources = new Dictionary<string, string>(StringComparer.InvariantCulture);

                XmlDocument d = new XmlDocument();
                d.Load(fp);

                foreach (XmlNode n in d.SelectSingleNode("root").ChildNodes)
                {
                    if (n.NodeType != XmlNodeType.Comment)
                    {
                        if (n.Attributes["name"] == null || n.Attributes["name"].Value == null)
                            continue;

                        if (!resources.ContainsKey(n.Attributes["name"].Value))
                        {
                            resources.Add(n.Attributes["name"].Value, n.InnerText);
                        }
                    }
                }

                HttpRuntime.Cache.Add(key, resources, dp, DateTime.Now.AddHours(_hours), Cache.NoSlidingExpiration, CacheItemPriority.High, null);

            }

            return resources;
        }
Пример #23
0
 /// <summary>
 /// 永久加入缓存项(缓存的失效依赖时间以外的因素)
 /// </summary>
 /// <param name="key">缓存项标识</param>
 /// <param name="obj">缓存项</param>
 /// <param name="dep">缓存依赖</param>
 public static void Max(string key, object obj, System.Web.Caching.CacheDependency dep)
 {
     if (obj != null)
     {
         _cache.Add(key, obj, dep, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.AboveNormal, null);
     }
 }
        /// <summary>
        /// Updates the Handler Configuration
        /// </summary>
        /// <param name="context">HTTP Context</param>
        protected override void UpdateConfig(HttpContext context)
        {
            if (this._config.CacheDuration == 0)
            {
                if (context.Cache[this._basePath] != null)
                {
                    context.Cache.Remove(this._basePath);
                }
            }
            else
            {
                if (context.Cache[this._basePath] != null)
                {
                    context.Cache[this._basePath] = this._config;
                }
                else
                {
                    String configFile = context.Server.MapPath(ConfigurationManager.AppSettings["dotNetRDFConfig"]);
                    System.Web.Caching.CacheDependency dependency = (configFile != null) ? new System.Web.Caching.CacheDependency(configFile) : null;

                    if (this._config.CacheSliding)
                    {
                        context.Cache.Add(this._basePath, this._config, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, this._config.CacheDuration, 0), System.Web.Caching.CacheItemPriority.Normal, null);
                    }
                    else
                    {
                        context.Cache.Add(this._basePath, this._config, null, DateTime.Now.AddMinutes(this._config.CacheDuration), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
                    }
                }
            }
        }
Пример #25
0
        private static void AddHostSettingsToCache(string host, NameValueCollection Obj)
        {
            if (System.Web.HttpRuntime.Cache == null)
            {
                _objHostSettings = Obj;
            }
            else
            {
                if (Obj != null)
                {
                    System.Web.Caching.Cache GlobalCache = System.Web.HttpRuntime.Cache;

                    System.Web.Caching.CacheDependency objDepend = null;
                    if (System.IO.File.Exists(General.Environment.Current.GetBinDirectory() + "General.config"))
                    {
                        objDepend = new System.Web.Caching.CacheDependency(General.Environment.Current.GetBinDirectory() + "General.config");
                    }
                    else if (System.IO.File.Exists(General.Environment.Current.GetAppDirectory() + "General.config"))
                    {
                        objDepend = new System.Web.Caching.CacheDependency(General.Environment.Current.GetAppDirectory() + "General.config");
                    }

                    if (objDepend != null)
                    {
                        GlobalCache.Add("General.Configuration.HostSettings." + host, Obj, objDepend, DateTime.Now.AddMinutes(10), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
                    }
                    else
                    {
                        _objHostSettings = Obj;
                    }
                }
            }
        }
Пример #26
0
        public void AddCacheItem(string rawKey, object value)
        {
            if (value == null)
            {
                return;
            }

            Cache dataCache = HttpRuntime.Cache;

            // Make sure MasterCacheKeyArray[0] is in the cache - if not, add it.
            if (dataCache[_masterCacheKeyArray[0]] == null)
            {
                dataCache[_masterCacheKeyArray[0]] = DateTime.UtcNow;
            }

            // TODO: Test what happens if I dispose this cache dependency after inserting in cache.
            // Adding a cache dependency:
            var dependency =
                new CacheDependency(null, _masterCacheKeyArray);
            dataCache.Insert(
                GetCacheKey(rawKey),
                value,
                dependency,
                DateTime.UtcNow.AddSeconds(CacheDuration),
                Cache.NoSlidingExpiration);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Cache["Data"] != null)
            {
                Label1.Text = "From Cache";
                GridView1.DataSource = Cache["Data"];
                GridView1.DataBind();
            }
            else
            {
                Label1.Text = "From List";
                Employee emp = new Employee();
                GridView1.DataSource = emp.GetEmployees();
                GridView1.DataBind();
                Cache["Data"] = emp.GetEmployees();
                Cache.Insert("Data", emp.GetEmployees());
   CacheDependency cd = new CacheDependency(Server.MapPath("myfile.txt"));
   Cache.Insert("Data", emp.GetEmployees(), cd, DateTime.Now.AddSeconds(20), Cache.NoSlidingExpiration);

            }


            ////       throw new InvalidOperationException("An InvalidOperationException " +
            ////"occurred in the Page_Load handler .");
        }
Пример #28
0
 public static void WriteData(string cacheID, CacheDependency cacheDependency, object data)
 {
     HttpRuntime.Cache.Insert(
                    cacheID, data, cacheDependency, Cache.NoAbsoluteExpiration,
                    Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null
                    );
 }
Пример #29
0
        public static void LoadConfig(string xmlFilePath)
        {
            Dictionary<string, OutputCacheSetting> dict = null;

            try
            {
                OutputCacheConfig config = XmlHelper.XmlDeserializeFromFile<OutputCacheConfig>(xmlFilePath, Encoding.UTF8);
                dict = config.Settings.ToDictionary(x => x.FilePath, StringComparer.OrdinalIgnoreCase);
            }
            catch (Exception ex)
            {
                s_loadConfigException = new System.Configuration.ConfigurationErrorsException(
                    "初始化SetOutputCacheModule时发生异常,请检查" + xmlFilePath + "文件是否配置正确。", ex);
            }


            if (dict != null)
            {
                // 注册缓存移除通知,以便在用户修改了配置文件后自动重新加载。

                // 参考:细说 ASP.NET Cache 及其高级用法
                //	      http://www.cnblogs.com/fish-li/archive/2011/12/27/2304063.html
                CacheDependency dep = new CacheDependency(xmlFilePath);
                HttpRuntime.Cache.Insert(CacheKey, xmlFilePath, dep,
                    Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, CacheRemovedCallback);
            }

            s_settings = dict;
        }
Пример #30
0
		/// <summary>
		/// Load assets from <c>~/App_Data/AssetPackager.xml</c> XML file.
		/// </summary>
		/// <returns>List of <see cref="AssetList" /> objects.</returns>
		public static ICollection<AssetList> LoadAssets()
		{
			string configFile = HttpContext.Current.Server.MapPath("~/App_Data/AssetPackager.xml");
			CacheDependency dependency = new CacheDependency(configFile);
			return (List<AssetList>) CacheHelper.GetData(Settings.CacheKey, dependency, DateTime.Now.AddDays(30),
			                                             CacheItemPriority.NotRemovable,
			                                             delegate { return LoadAssetLists(configFile); });
		}
Пример #31
0
 void AddCacheDependency()
 {
     var obj = System.IO.File.ReadAllText(@"E:\log.log");
     var cacheDependency = new CacheDependency(@"E:\log.log");
     HttpRuntime.Cache.Add("global_config", obj, cacheDependency,
         Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
         CacheItemPriority.Default, null);
 }
 //缓存DataSet,并建立DataSet缓存与文件的依赖项
 private void CacheDataSet1()
 {
     dsEmployee = new DataSet();
     dsEmployee.ReadXml(Server.MapPath("~/App_Data/Employees.xml"));
     filedep = null;//建立DataSet缓存与文件依赖项
     filedep = new CacheDependency(Server.MapPath("~/App_Data/Employees.xml"));
     Cache.Insert("Employee", dsEmployee, filedep);
 }
Пример #33
0
        /// <summary>
        /// 加入当前对象到缓存中,并使用依赖键
        /// </summary>
        /// <param name="objId">key for the object</param>
        /// <param name="o">object</param>
        /// <param name="dependKey">监视的路径文件</param>
        public void AddObjectWithDepend(string objId, object o, string[] dependKey)
        {
            if (objId == null || objId.Length == 0 || o == null)
                return;

            CacheDependency dep = new CacheDependency(null, dependKey, DateTime.Now);
            webCacheforfocus.Insert(objId, o, dep, System.DateTime.Now.AddMinutes(TimeOut), System.Web.Caching.Cache.NoSlidingExpiration);
        }
Пример #34
0
		/// <summary>
		/// 加入当前对象到缓存中,并对相关文件建立依赖
		/// </summary>
		/// <param name="objId">key for the object</param>
		/// <param name="o">object</param>
		/// <param name="files">监视的路径文件</param>
		public void AddObjectWithFileChange(string objId, object o, string[] files)
		{
			if (objId == null || objId.Length == 0 || o == null)
			    return;
		
			CacheDependency dep = new CacheDependency(files, DateTime.Now);
            webCacheforfocus.Insert(objId, o, dep, System.DateTime.Now.AddSeconds(TimeOut), System.Web.Caching.Cache.NoSlidingExpiration);
		}
Пример #35
0
        public FieldCacheFacade()
        {
            string xmlFile = HttpContext.Current.Server.MapPath("~/schemamapping.xml");
            CacheDependency xmlDependency = new CacheDependency(xmlFile);

            Cache cache = new Cache();
            cache.Insert("", null, xmlDependency);
        }
Пример #36
0
 /// <summary>
 /// 设置数据缓存-CacheDependency
 /// </summary>
 /// <param name="CacheKey"></param>
 /// <param name="cacheDependency"></param>
 public static void SetCacheDependency(string CacheKey, object objc, string FilePath)
 {
     System.Web.Caching.Cache objCache = HttpRuntime.Cache;
     if (objCache[CacheKey] == null)
     {
         System.Web.Caching.CacheDependency cacheDependency = new System.Web.Caching.CacheDependency(FilePath, DateTime.Now);
         objCache.Insert(CacheKey, objc, cacheDependency);
     }
 }
Пример #37
0
        public static List <object> GetFilesFromCache(string DirectoryPath)
        {
            try
            {
                if (DirectoryPath != null)
                {
                    DirectoryInfo dir   = new DirectoryInfo(DirectoryPath);
                    List <object> files = new List <object>();
                    object        objCache;
                    foreach (DirectoryInfo directory in dir.GetDirectories())
                    {
                        GetFilesFromCache(directory.FullName);
                        foreach (FileInfo fi in directory.GetFiles())
                        {
                            objCache = System.Web.HttpRuntime.Cache.Get(fi.FullName);
                            if (objCache == null)
                            {
                                CacheDependency dependancy = new System.Web.Caching.CacheDependency(fi.FullName);
                                XDocument       document   = XDocument.Load(fi.FullName);
                                System.Web.HttpRuntime.Cache.Insert(fi.FullName, document, dependancy, DateTime.Now.AddDays(1), System.Web.Caching.Cache.NoSlidingExpiration);
                                files.Add(document);
                            }
                            else
                            {
                                files.Add(objCache);
                            }
                        }
                    }
                    foreach (FileInfo fi in dir.GetFiles())
                    {
                        objCache = System.Web.HttpRuntime.Cache.Get(fi.FullName);
                        if (objCache == null)
                        {
                            CacheDependency dependancy = new System.Web.Caching.CacheDependency(fi.FullName);
                            XDocument       document   = XDocument.Load(fi.FullName);
                            System.Web.HttpRuntime.Cache.Insert(fi.FullName, document, dependancy, DateTime.Now.AddDays(1), System.Web.Caching.Cache.NoSlidingExpiration);
                            files.Add(document);
                        }
                        else
                        {
                            files.Add(objCache);
                        }
                    }


                    return(files);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Пример #38
0
 /// <summary>
 /// 设置数据缓存-CacheDependency
 /// </summary>
 /// <param name="CacheKey"></param>
 /// <param name="cacheDependency"></param>
 public static void SetCacheDependency(string CacheKey, string FilePath)
 {
     System.Web.Caching.Cache objCache = HttpRuntime.Cache;
     if (objCache[CacheKey] == null)
     {
         FileFSO fso = new FileFSO();
         string  txt = fso.ReadFileText(FilePath);
         System.Web.Caching.CacheDependency cacheDependency = new System.Web.Caching.CacheDependency(FilePath, DateTime.Now);
         objCache.Insert(CacheKey, txt, cacheDependency);
     }
 }
Пример #39
0
 /// <summary>
 /// 设置以缓存依赖的方式缓存数据
 /// </summary>
 /// <param name="CacheKey">索引键值</param>
 /// <param name="objObject">缓存对象</param>
 /// <param name="dep">依赖对象</param>
 public static void SetCache(string CacheKey, object objObject, System.Web.Caching.CacheDependency dep)
 {
     // System.Web.Caching.Cache objCache = HttpRuntime.Cache;
     _cache.Insert(
         CacheKey,
         objObject,
         dep,
         System.Web.Caching.Cache.NoAbsoluteExpiration, //从不过期
         System.Web.Caching.Cache.NoSlidingExpiration,  //禁用可调过期
         System.Web.Caching.CacheItemPriority.Default,
         null);
 }
Пример #40
0
        private static Dictionary <string, SqlContent> GetSqlDocuments()
        {
            Dictionary <string, SqlContent> dic = System.Web.HttpContext.Current.Cache.Get(typeof(Dictionary <string, SqlContent>).FullName) as Dictionary <string, SqlContent>;

            if (dic != null && dic.Count > 0)
            {
                return(dic);
            }

            string parentPath = AppDomain.CurrentDomain.BaseDirectory;

            dic = new Dictionary <string, SqlContent>();

            XmlSerializer _sqlDocSerializer = new XmlSerializer(typeof(SqlDocument));

            string[] files = System.IO.Directory.GetFiles(parentPath, @"*.xml", SearchOption.AllDirectories);

            files = files.Where(a => a.IndexOf("\\XmlConfig\\", StringComparison.OrdinalIgnoreCase) != -1).ToArray();

            System.Web.Caching.CacheDependency dependency = new System.Web.Caching.CacheDependency(files);

            foreach (var file in files)
            {
                using (var stream = File.OpenRead(file))
                {
                    try
                    {
                        var doc = (SqlDocument)_sqlDocSerializer.Deserialize(stream);

                        if (doc != null && doc.Entities != null)
                        {
                            foreach (var model in doc.Entities)
                            {
                                if (!dic.ContainsKey(model.Name))
                                {
                                    dic.Add(model.Name, new SqlContent()
                                    {
                                        Content = model.Content, Parameter = model.Parameter
                                    });
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Esmart.Framework.Logging.LogManager.CreateTpoLog().Error("sqlxml基础信息读取失败", ex);
                    }
                }
            }
            HttpContext.Current.Cache.Add(typeof(Dictionary <string, SqlContent>).FullName, dic, dependency, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null);

            return(dic);
        }
Пример #41
0
        /// <summary>
        /// Adds the item to the web cache, along with general dependency support
        /// </summary>
        /// <param name="rawKey"></param>
        /// <param name="value"></param>
        private static void AddCacheItem(string rawKey, object value)
        {
            System.Web.Caching.Cache DataCache = HttpRuntime.Cache;

            // Make sure MasterCacheKeyArray[0] is in the cache and create a depedency
            DataCache[MasterCacheKeyArray[0]] = DateTime.Now;
            System.Web.Caching.CacheDependency masterCacheKeyDependency = new System.Web.Caching.CacheDependency(null, MasterCacheKeyArray);

            //we are putting the cache without any expiration policy,
            //we are expiring the cache programatically once when a new or existing instance of the current entity are being updated.
            DataCache.Insert(GetCacheKey(rawKey), value, masterCacheKeyDependency, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration);
        }
Пример #42
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!this.IsPostBack)
     {
         lblInfo.Text += "Creating dependent item...<br />";
         Cache.Remove("File");
         System.Web.Caching.CacheDependency dependency =
             new System.Web.Caching.CacheDependency(Server.MapPath("dependency.txt"));
         string item = "Dependent cached item";
         lblInfo.Text += "Adding dependent item<br />";
         Cache.Insert("File", item, dependency);
     }
 }
Пример #43
0
 /// <summary>/// 设置从不过期以缓存依赖的方式缓存数据/// </summary>
 /// <param name="CacheKey">索引键值</param>
 /// <param name="objObject">缓存对象</param>
 /// <param name="cacheDepen">依赖对象</param>
 public static void InsertCache(string CacheKey, object objObject, System.Web.Caching.CacheDependency dep)
 {
     if (objObject != null)
     {
         objCache.Insert(CacheKey,
                         objObject,
                         dep,
                         System.Web.Caching.Cache.NoAbsoluteExpiration, //从不过期
                         System.Web.Caching.Cache.NoSlidingExpiration,  //禁用可调过期
                         System.Web.Caching.CacheItemPriority.Default,
                         null);
     }
 }
Пример #44
0
 /// <summary>
 /// 依赖文件的缓存,文件没改不会过期
 /// </summary>
 /// <param name="CacheKey">键</param>
 /// <param name="objObject">数据</param>
 /// <param name="depfilename">依赖文件,可调用 DataCache 里的变量</param>
 public static void SetCacheDepFile(string CacheKey, object objObject, string depfilename)
 {
     //缓存依赖对象
     System.Web.Caching.CacheDependency dep      = new System.Web.Caching.CacheDependency(depfilename);
     System.Web.Caching.Cache           objCache = HttpRuntime.Cache;
     objCache.Insert(
         CacheKey,
         objObject,
         dep,
         System.Web.Caching.Cache.NoAbsoluteExpiration, //从不过期
         System.Web.Caching.Cache.NoSlidingExpiration,  //禁用可调过期
         System.Web.Caching.CacheItemPriority.Default,
         null);
 }
Пример #45
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);
            }
        }
Пример #46
0
        public ActionResult Index()
        {
            sqllitehelper _sh = new sqllitehelper();

            try
            {
                if (HttpRuntime.Cache["ftoken"] == null)
                {
                    //缓存要依赖的文件的路径(我这里写的是绝对路径,也可以写虚拟路径,到时候给它转成物理路径就可以了)
                    string filePath = Server.MapPath("~/App_Data/cacketrigger.txt");

                    //这段代码无缓存依赖没有关系,这里仅仅是将上面那个路径的文件读出来而已(到时候用作缓存的值,当然你也可以设置别的值,这里仅仅是做是案例而已)
                    DataTable dt  = _sh.GetToken();
                    string    msg = (dt != null && dt.Rows.Count > 0) ? dt.Rows[0][0].ToString() : "";
                    //创建一个缓存依赖对象(并用缓存依赖文件的服务器端的物理路径给它初始化。只要文件的内容改变,它就会通知framework清空缓存
                    System.Web.Caching.CacheDependency cDep = new System.Web.Caching.CacheDependency(filePath);
                    //第一个参数:缓存的键
                    //第二个参数:缓存的值
                    //第三个参数:缓存依赖的对象
                    //第四个参数:缓存的绝对过期时间,从用户第一次请求开始计时(因为这里我们是使用的缓存依赖,所以这里使用NoAbsoluteExpiration,表示没有到期时间,即永不过期)
                    //第五个参数:缓存的可调过期时间,从用户最后一次请求开始计时(因为这里我们是使用缓存依赖,所以这里使用NoSlidingExpiration,表示没有可调过期时间)
                    //第六个参数:指定 System.Web.Caching.Cache 对象中存储的项的相对优先级。(它是一个枚举) Normal是默认值
                    //第七个参数:缓存依赖的回调函数(缓存被清除或修改的时候调用此方法)
                    //【其实第七个参数它是一个委托,既然它是一个委托,所以我们使用它的时候需要传递一个方法签名和这个委托签名一样的方法给它】
                    //Cache.Insert()方法也可以用Cache.Add()方法替代,只是Cache.Add()方法的参数个数比较多,有时候我们不需要那么多参数的时候就使用Cache.Insert(),比较方便
                    HttpRuntime.Cache.Insert("ftoken", msg, cDep, System.Web.Caching.Cache.NoAbsoluteExpiration,
                                             System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, CacheCallBack);
                    ViewBag.bdyctoken = msg;
                }
                else
                {
                    //如果key为“fmsg”的缓存存在数据,就将它赋值给ViewData["msg"]
                    ViewBag.bdyctoken = HttpRuntime.Cache["ftoken"].ToString();
                }
                int db = _sh.InsertData("");
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(View());
        }
Пример #47
0
        /// <summary>
        /// 获取缓存的对象。当没有缓存的时候,自动创建对象并进行缓存。只支持引用类型的缓存。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="dependency"></param>
        /// <param name="timeOutSeconds">单位:秒</param>
        /// <param name="onCreateInstance"></param>
        /// <returns></returns>
        public static T GetCachedObject <T>(string key, System.Web.Caching.CacheDependency dependency, int timeOutSeconds, Func <T> onCreateInstance)
        {
            if (timeOutSeconds > 0 || dependency != null)
            {
                //当前Cache对象
                System.Web.Caching.Cache webCache = System.Web.HttpRuntime.Cache;
                if (webCache == null)
                {
                    return(onCreateInstance());
                }

                //获取缓存的对象
                T cachedObject = (T)webCache.Get(key);

                if (cachedObject == null)
                {
                    //加锁确保多线程安全
                    lock (CacheLocker)
                    {
                        cachedObject = (T)webCache.Get(key);
                        if (cachedObject == null)
                        {
                            //创建新的对象
                            cachedObject = onCreateInstance();
                            //将创建的对象进行缓存
                            if (cachedObject != null)
                            {
                                webCache.Insert(key, cachedObject, dependency, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 0, timeOutSeconds));
                            }
                        }
                    }
                }
                return(cachedObject);
            }
            else
            {
                //不设置缓存,则创建新的对象
                return(onCreateInstance());
            }
        }
Пример #48
0
        public T GetCachedObject <T>(string key, System.Web.Caching.CacheDependency dependency, int timeOutMinutes, Func <T> onCreateInstance)
        {
            if (timeOutMinutes > 0)
            {
                string   file = string.Format("{0}\\{1}.cache", _CacheConst, key);
                FileInfo fi   = new FileInfo(file);
                if (!fi.Exists)
                {
                    return(onCreateInstance());
                }

                //获取缓存的对象
                T cachedObject = Get <T>(key);

                if (cachedObject == null)
                {
                    //加锁确保多线程安全
                    lock (CacheLocker)
                    {
                        cachedObject = Get <T>(key);
                        if (cachedObject == null)
                        {
                            //创建新的对象
                            cachedObject = onCreateInstance();
                            //将创建的对象进行缓存
                            if (cachedObject != null)
                            {
                                Insert(key, cachedObject, timeOutMinutes);
                            }
                        }
                    }
                }
                return(cachedObject);
            }
            else
            {
                //不设置缓存,则创建新的对象
                return(onCreateInstance());
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            lblInfo.Text += "Creating dependent item...<br>";
            Cache.Remove("Dependent");
            System.Web.Caching.CacheDependency dep1 =
                new System.Web.Caching.CacheDependency(Server.MapPath("dependency.txt"));
            System.Web.Caching.CacheDependency dep2 =
                new System.Web.Caching.CacheDependency(Server.MapPath("dependency2.txt"));


            // Create the aggregate.
            CacheDependency[]        dependencies = new CacheDependency[] { dep1, dep2 };
            AggregateCacheDependency aggregateDep = new AggregateCacheDependency();
            aggregateDep.Add(dependencies);

            string item = "Dependent cached item";
            lblInfo.Text += "Adding dependent item<br>";
            Cache.Insert("Dependent", item, aggregateDep);
        }
    }
Пример #50
0
        /// <summary>
        /// 依赖文件的缓存,文件没改不会过期
        /// </summary>
        /// <param name="CacheKey">键</param>
        /// <param name="objObject">数据</param>
        /// <param name="depfilename">依赖文件,可调用 DataCache 里的变量</param>
        public static void SetCacheDepFile(string CacheKey, object objObject, string depfilename)
        {
            //缓存依赖对象
            System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency(depfilename);
            DateTime absoluteExpiration            = System.Web.Caching.Cache.NoAbsoluteExpiration;
            TimeSpan slidingExpiration             = System.Web.Caching.Cache.NoSlidingExpiration;

            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(
                CacheKey,
                objObject,
                dep,
                System.Web.Caching.Cache.NoAbsoluteExpiration, //从不过期
                slidingExpiration,                             //禁用可调过期
                System.Web.Caching.CacheItemPriority.Default,
                null);
            if (File.Exists(depfilename))
            {
                FileInfo fi            = new FileInfo(depfilename);
                DateTime lastWriteTime = fi.LastWriteTime;
                HttpRuntime.Cache.Insert(CacheKey + "_time", lastWriteTime, null, absoluteExpiration, slidingExpiration);//存储文件最后修改时间
            }
        }
Пример #51
0
        public ActionResult gsk()
        {
            if (HttpRuntime.Cache["fmsg"] == null)
            {
                //缓存要依赖的文件的路径(我这里写的是绝对路径,也可以写虚拟路径,到时候给它转成物理路径就可以了)
                string filePath = Server.MapPath("~/App_Data/cacketrigger.txt");

                //这段代码无缓存依赖没有关系,这里仅仅是将上面那个路径的文件读出来而已(到时候用作缓存的值,当然你也可以设置别的值,这里仅仅是做是案例而已)
                string msg = System.IO.File.ReadAllText(filePath, System.Text.Encoding.Default);

                //创建一个缓存依赖对象(并用缓存依赖文件的服务器端的物理路径给它初始化。只要文件的内容改变,它就会通知framework清空缓存
                System.Web.Caching.CacheDependency cDep = new System.Web.Caching.CacheDependency(filePath);
                //第一个参数:缓存的键
                //第二个参数:缓存的值
                //第三个参数:缓存依赖的对象
                //第四个参数:缓存的绝对过期时间,从用户第一次请求开始计时(因为这里我们是使用的缓存依赖,所以这里使用NoAbsoluteExpiration,表示没有到期时间,即永不过期)
                //第五个参数:缓存的可调过期时间,从用户最后一次请求开始计时(因为这里我们是使用缓存依赖,所以这里使用NoSlidingExpiration,表示没有可调过期时间)
                //第六个参数:指定 System.Web.Caching.Cache 对象中存储的项的相对优先级。(它是一个枚举) Normal是默认值
                //第七个参数:缓存依赖的回调函数(缓存被清除或修改的时候调用此方法)
                //【其实第七个参数它是一个委托,既然它是一个委托,所以我们使用它的时候需要传递一个方法签名和这个委托签名一样的方法给它】
                //Cache.Insert()方法也可以用Cache.Add()方法替代,只是Cache.Add()方法的参数个数比较多,有时候我们不需要那么多参数的时候就使用Cache.Insert(),比较方便
                HttpRuntime.Cache.Insert("fmsg", msg, cDep, System.Web.Caching.Cache.NoAbsoluteExpiration,
                                         System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, CacheCallBack);
                ViewBag.msg = msg;
            }
            else
            {
                //如果key为“fmsg”的缓存存在数据,就将它赋值给ViewData["msg"]
                ViewBag.msg = HttpRuntime.Cache["fmsg"].ToString();
            }
            sqllitehelper _sh = new sqllitehelper();
            DataTable     dt  = _sh.GetData();

            ViewBag.alldata = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
            return(View());
        }
Пример #52
0
        void InitForMemoryCache(bool isPublic, string[] filenamesArg, string[] cachekeysArg, CacheDependency dependency, DateTime utcStart)
        {
            bool dispose = true;

            try {
                MemCache memCache = HttpRuntime.CacheInternal as MemCache;
                _bits            = new SafeBitVector32(0);
                _utcLastModified = DateTime.MinValue;
                IList <String> files = filenamesArg;
                IList <String> keys  = cachekeysArg;
                if (dependency != null)
                {
                    ReadOnlyCollection <string> filePaths = (dependency._fileChangeMonitor != null) ? dependency._fileChangeMonitor.FilePaths : null;
                    ReadOnlyCollection <string> cacheKeys = (dependency._entryChangeMonitor != null) ? dependency._entryChangeMonitor.CacheKeys : null;
                    if (filePaths != null || filenamesArg != null)
                    {
                        if (filePaths == null)
                        {
                            files = filenamesArg;
                        }
                        else if (filenamesArg == null)
                        {
                            files = filePaths;
                        }
                        else
                        {
                            files = new List <String>(filenamesArg.Length + filePaths.Count);
                            foreach (string f in filenamesArg)
                            {
                                files.Add(f);
                            }
                            foreach (string f in filePaths)
                            {
                                files.Add(f);
                            }
                        }
                    }
                    if (cacheKeys != null || cachekeysArg != null)
                    {
                        if (cacheKeys == null)
                        {
                            keys = cachekeysArg;
                        }
                        else if (cachekeysArg == null)
                        {
                            keys = cacheKeys;
                        }
                        else
                        {
                            keys = new List <String>(cachekeysArg.Length + cacheKeys.Count);
                            foreach (string f in cachekeysArg)
                            {
                                keys.Add(f);
                            }
                            foreach (string f in cacheKeys)
                            {
                                keys.Add(f);
                            }
                        }
                    }
                }

                _fileChangeMonitor  = (files != null) ? new HostFileChangeMonitor(files) : null;
                _entryChangeMonitor = (keys != null) ? memCache.CreateCacheEntryChangeMonitor(keys, isPublic) : null;

                string uniqueId = null;

                if (_fileChangeMonitor != null)
                {
                    _utcLastModified = _fileChangeMonitor.LastModified.UtcDateTime;
                    uniqueId         = _fileChangeMonitor.UniqueId;
                    _fileChangeMonitor.NotifyOnChanged(new OnChangedCallback(OnChangedCallback));
                }
                if (_entryChangeMonitor != null)
                {
                    DateTime utcLastModified = _entryChangeMonitor.LastModified.UtcDateTime;
                    if (utcLastModified > _utcLastModified)
                    {
                        _utcLastModified = utcLastModified;
                    }
                    uniqueId += _entryChangeMonitor.UniqueId;
                    _entryChangeMonitor.NotifyOnChanged(new OnChangedCallback(OnChangedCallback));
                }

                _uniqueID = uniqueId;
#if DBG
                _isUniqueIDInitialized = true;
#endif
                // check if file has changed since the start time
                if (utcStart < DateTime.MaxValue)
                {
                    if (_utcLastModified > utcStart &&
                        !(_utcLastModified - DateTime.UtcNow > FUTURE_FILETIME_BUFFER))        // See VSWhidbey 400917
                    {
                        _bits[CHANGED] = true;
                    }
                }

                _bits[BASE_INIT] = true;
                if (dependency != null && dependency._bits[CHANGED])
                {
                    _bits[CHANGED] = true;
                }
                if (_bits[WANTS_DISPOSE] || _bits[CHANGED])
                {
                    Debug.Trace("CacheDependencyInit", "WANTS_DISPOSE or CHANGED.  InitForMemoryCache calling DisposeInternal");
                    DisposeInternal();
                }
                dispose = false;
            }
            finally {
                if (dispose)
                {
                    _bits[BASE_INIT] = true;
                    Debug.Trace("CacheDependencyInit", "\n\nERROR in CacheDependency.InitForMemoryCache, calling DisposeInternal");
                    DisposeInternal();
                }
            }
        }
Пример #53
0
        public static void SetCacheByFileDependency(string CacheKey, object objObject, System.Web.Caching.CacheDependency cd, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            CacheItemRemovedCallback onRemove = new CacheItemRemovedCallback(RemovedCallback);

            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject, cd, absoluteExpiration, slidingExpiration, CacheItemPriority.High, onRemove);
        }
Пример #54
0
 /// <summary>
 /// ��ӻ����ļ��Ļ�����������
 /// </summary>
 /// <param name="CacheKey"></param>
 /// <param name="objObject"></param>
 /// <param name="cd"></param>
 /// <param name="absoluteExpiration"></param>
 /// <param name="slidingExpiration"></param>
 public static void SetCache(string CacheKey, object objObject, System.Web.Caching.CacheDependency cd, DateTime absoluteExpiration, TimeSpan slidingExpiration)
 {
     System.Web.Caching.Cache objCache = HttpRuntime.Cache;
     objCache.Insert(CacheKey, objObject, cd, absoluteExpiration, slidingExpiration);
 }
Пример #55
0
        void Init(bool isPublic, string[] filenamesArg, string[] cachekeysArg, CacheDependency dependency, DateTime utcStart)
        {
#if USE_MEMORY_CACHE
            if (CacheInternal.UseMemoryCache)
            {
                InitForMemoryCache(isPublic, filenamesArg, cachekeysArg, dependency, utcStart);
                return;
            }
#endif
            DepFileInfo[] depFileInfos = s_depFileInfosEmpty;
            CacheEntry[]  depEntries   = s_entriesEmpty;
            string []     filenames, cachekeys;
            CacheInternal cacheInternal;

            _bits = new SafeBitVector32(0);

            // copy array argument contents so they can't be changed beneath us
            if (filenamesArg != null)
            {
                filenames = (string [])filenamesArg.Clone();
            }
            else
            {
                filenames = null;
            }

            if (cachekeysArg != null)
            {
                cachekeys = (string [])cachekeysArg.Clone();
            }
            else
            {
                cachekeys = null;
            }

            _utcLastModified = DateTime.MinValue;

            try {
                // validate filenames array
                if (filenames == null)
                {
                    filenames = s_stringsEmpty;
                }
                else
                {
                    foreach (string f in filenames)
                    {
                        if (f == null)
                        {
                            throw new ArgumentNullException("filenamesArg");
                        }

                        // demand PathDiscovery if public
                        if (isPublic)
                        {
                            InternalSecurityPermissions.PathDiscovery(f).Demand();
                        }
                    }
                }

                if (cachekeys == null)
                {
                    cachekeys = s_stringsEmpty;
                }
                else
                {
                    // validate cachekeys array
                    foreach (string k in cachekeys)
                    {
                        if (k == null)
                        {
                            throw new ArgumentNullException("cachekeysArg");
                        }
                    }
                }

                // copy all parts of another dependency if provided
                if (dependency == null)
                {
                    dependency = s_dependencyEmpty;
                }
                else
                {
                    if (dependency.GetType() != s_dependencyEmpty.GetType())
                    {
                        throw new ArgumentException(SR.GetString(SR.Invalid_Dependency_Type));
                    }

                    // Copy the parts of the dependency we need before
                    // we reference them, as the dependency can change
                    // underneath us.
                    object   d_depFileInfos = dependency._depFileInfos;
                    object   d_entries      = dependency._entries;
                    DateTime d_lastModified = dependency._utcLastModified;

                    // if the dependency we're copying has changed, we're done
                    if (dependency._bits[CHANGED])
                    {
                        _bits[CHANGED] = true;
                        // There is nothing to dispose because we haven't started
                        // monitoring anything yet.  But we call DisposeInternal in
                        // order to set the WANTS_DISPOSE bit.
                        DisposeInternal();
                        return;
                    }

                    // copy depFileInfos
                    if (d_depFileInfos != null)
                    {
                        if (d_depFileInfos is DepFileInfo)
                        {
                            depFileInfos = new DepFileInfo[1] {
                                (DepFileInfo)d_depFileInfos
                            };
                        }
                        else
                        {
                            depFileInfos = (DepFileInfo[])(d_depFileInfos);
                        }

                        // verify that the object was fully constructed
                        // and that we have permission to discover the file
                        foreach (DepFileInfo depFileInfo in depFileInfos)
                        {
                            string f = depFileInfo._filename;

                            if (f == null)
                            {
                                _bits[CHANGED] = true;
                                // There is nothing to dispose because we haven't started
                                // monitoring anything yet.  But we call DisposeInternal in
                                // order to set the WANTS_DISPOSE bit.
                                DisposeInternal();
                                return;
                            }

                            // demand PathDiscovery if public
                            if (isPublic)
                            {
                                InternalSecurityPermissions.PathDiscovery(f).Demand();
                            }
                        }
                    }

                    // copy cache entries
                    if (d_entries != null)
                    {
                        if (d_entries is CacheEntry)
                        {
                            depEntries = new CacheEntry[1] {
                                (CacheEntry)(d_entries)
                            };
                        }
                        else
                        {
                            depEntries = (CacheEntry[])(d_entries);
                            // verify that the object was fully constructed
                            foreach (CacheEntry entry in depEntries)
                            {
                                if (entry == null)
                                {
                                    _bits[CHANGED] = true;
                                    // There is nothing to dispose because we haven't started
                                    // monitoring anything yet.  But we call DisposeInternal in
                                    // order to set the WANTS_DISPOSE bit.
                                    DisposeInternal();
                                    return;
                                }
                            }
                        }
                    }

                    _utcLastModified = d_lastModified;
                }

                // Monitor files for changes
                int lenMyDepFileInfos = depFileInfos.Length + filenames.Length;
                if (lenMyDepFileInfos > 0)
                {
                    DepFileInfo[]          myDepFileInfos = new DepFileInfo[lenMyDepFileInfos];
                    FileChangeEventHandler handler        = new FileChangeEventHandler(this.FileChange);
                    FileChangesMonitor     fmon           = HttpRuntime.FileChangesMonitor;

                    int i;
                    for (i = 0; i < lenMyDepFileInfos; i++)
                    {
                        myDepFileInfos[i] = new DepFileInfo();
                    }

                    // monitor files from the existing dependency
                    // note that we don't check for start times in the existing dependency
                    i = 0;
                    foreach (DepFileInfo depFileInfo in depFileInfos)
                    {
                        string f = depFileInfo._filename;
                        fmon.StartMonitoringPath(f, handler, out myDepFileInfos[i]._fad);
                        myDepFileInfos[i]._filename = f;
                        i++;
                    }

                    // monitor new files
                    DateTime utcNow = DateTime.MinValue;
                    foreach (string f in filenames)
                    {
                        DateTime utcLastWrite = fmon.StartMonitoringPath(f, handler, out myDepFileInfos[i]._fad);
                        myDepFileInfos[i]._filename = f;
                        i++;

                        if (utcLastWrite > _utcLastModified)
                        {
                            _utcLastModified = utcLastWrite;
                        }

                        // check if file has changed since the start time
                        if (utcStart < DateTime.MaxValue)
                        {
                            if (utcNow == DateTime.MinValue)
                            {
                                utcNow = DateTime.UtcNow;
                            }

                            Debug.Trace("CacheDependencyInit", "file=" + f + "; utcStart=" + utcStart + "; utcLastWrite=" + utcLastWrite);
                            if (utcLastWrite >= utcStart &&
                                !(utcLastWrite - utcNow > FUTURE_FILETIME_BUFFER))     // See VSWhidbey 400917
                            {
                                Debug.Trace("CacheDependencyInit", "changes occurred since start time for file " + f);
                                _bits[CHANGED] = true;
                                break;
                            }
                        }
                    }

                    if (myDepFileInfos.Length == 1)
                    {
                        _depFileInfos = myDepFileInfos[0];
                    }
                    else
                    {
                        _depFileInfos = myDepFileInfos;
                    }
                }

                // Monitor other cache entries for changes
                int lenMyEntries = depEntries.Length + cachekeys.Length;
                if (lenMyEntries > 0 && !_bits[CHANGED])
                {
                    CacheEntry[] myEntries = new CacheEntry[lenMyEntries];

                    // Monitor entries from the existing cache dependency
                    int i = 0;
                    foreach (CacheEntry entry in depEntries)
                    {
                        entry.AddCacheDependencyNotify(this);
                        myEntries[i++] = entry;
                    }

                    // Monitor new entries specified for this depenedency
                    // Entries must be added to cache, and created before the startTime
                    cacheInternal = HttpRuntime.CacheInternal;
                    foreach (string k in cachekeys)
                    {
                        CacheEntry entry = (CacheEntry)cacheInternal.DoGet(isPublic, k, CacheGetOptions.ReturnCacheEntry);
                        if (entry != null)
                        {
                            entry.AddCacheDependencyNotify(this);
                            myEntries[i++] = entry;

                            if (entry.UtcCreated > _utcLastModified)
                            {
                                _utcLastModified = entry.UtcCreated;
                            }

                            if (entry.State != CacheEntry.EntryState.AddedToCache ||
                                entry.UtcCreated > utcStart)
                            {
#if DBG
                                if (entry.State != CacheEntry.EntryState.AddedToCache)
                                {
                                    Debug.Trace("CacheDependencyInit", "Entry is not in cache, considered changed:" + k);
                                }
                                else
                                {
                                    Debug.Trace("CacheDependencyInit", "Changes occurred to entry since start time:" + k);
                                }
#endif

                                _bits[CHANGED] = true;
                                break;
                            }
                        }
                        else
                        {
                            Debug.Trace("CacheDependencyInit", "Cache item not found to create dependency on:" + k);
                            _bits[CHANGED] = true;
                            break;
                        }
                    }

                    if (myEntries.Length == 1)
                    {
                        _entries = myEntries[0];
                    }
                    else
                    {
                        _entries = myEntries;
                    }
                }

                _bits[BASE_INIT] = true;
                if (dependency._bits[CHANGED])
                {
                    _bits[CHANGED] = true;
                }

                if (_bits[WANTS_DISPOSE] || _bits[CHANGED])
                {
                    DisposeInternal();
                }

                Debug.Assert(_objNotify == null, "_objNotify == null");
            }
            catch {
                // derived constructor will not execute due to the throw,
                // so we just force a dispose on ourselves
                _bits[BASE_INIT] = true;
                DisposeInternal();
                throw;
            }
            finally {
                InitUniqueID();
            }
        }
Пример #56
0
 public void Insert(string key, object value, CacheDependency dependencies)
 {
     Insert(key, value, dependencies, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.Normal, null, null, true);
 }
Пример #57
0
 public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration,
                    CacheItemUpdateCallback onUpdateCallback)
 {
     Insert(key, value, dependencies, absoluteExpiration, slidingExpiration, CacheItemPriority.Normal, null, onUpdateCallback, true);
 }
Пример #58
0
 public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration,
                    CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
 {
     Insert(key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback, null, true);
 }
Пример #59
0
 public static void Insert(string key, object value, System.Web.Caching.CacheDependency dep)
 {
     s_Cache.Insert(key, value, dep, DateTime.Now.AddSeconds((double)(Factor * 0x21c0)), TimeSpan.Zero, CacheItemPriority.NotRemovable, null);
 }//此方法是新加的
Пример #60
0
 /// <summary>
 /// 设定滑动过期缓存(过期时间为15分钟)
 /// (当缓存最后一次使用后经过所指定的时间后则清除缓存)
 /// </summary>
 /// <param name="CacheKey">缓存键名</param>
 /// <param name="objObject">缓存对象</param>
 /// <param name="dep">缓存依赖项</param>
 public static void InsertCacheExpired(string CacheKey, object objObject, System.Web.Caching.CacheDependency dep)
 {
     objCache.Insert(CacheKey, objObject, dep, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(DataCacheKey.CacheExpiredTime));
 }