Exemple #1
0
 public void Insert(string key, object value, System.Web.Caching.CacheDependency cacheDependency, DateTime absoluteExpiration, TimeSpan slidingExpiration)
 {
     if (HttpContext.Current != null)
     {
         HttpContext.Current.Cache.Add(key, value, cacheDependency, absoluteExpiration, slidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);
     }
 }
 public static void AddWithDependency(string key, object value, string name, DateTime absoluteExpiration)
 {
     var dependency = new System.Web.Caching.CacheDependency(GetOptionPath());
     var slidingExpiration = ExpiredTime(name);
     HttpRuntime.Cache.Insert(key, value, dependency, absoluteExpiration,
         TimeSpan.FromMinutes(slidingExpiration), System.Web.Caching.CacheItemPriority.Low, null);
 }
Exemple #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpRuntime.Cache["Time"] == null)
            {
                //设置文件依赖缓存
                object obj = DateTime.Now;

                //设置文件依赖项
                System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency(Server.MapPath("/数据缓存/1.txt"));

                HttpRuntime.Cache.Add(
                    "Time",                                        //键
                    obj,                                           //值
                    dep,                                           //依赖项
                    System.Web.Caching.Cache.NoAbsoluteExpiration, //绝对过期时间
                    System.Web.Caching.Cache.NoSlidingExpiration,  //相对过期时间
                    System.Web.Caching.CacheItemPriority.Normal,   //优先级
                    null                                           //回调函数
                    );
                Response.Write("缓存设置成功,当前缓存的时间为:" + obj.ToString());
            }
            else
            {
                Response.Write("从缓存得到时间,时间为:" + HttpRuntime.Cache["Time"].ToString());
            }
        }
 /// <summary>
 /// 创建缓存项的文件依赖
 /// </summary>
 /// <param name="key">缓存Key</param>
 /// <param name="obj">object对象</param>
 /// <param name="fileName">文件绝对路径</param>
 public static void Insert(string key, object obj, string fileName)
 {
     //创建缓存依赖项
     System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency(fileName);
     //创建缓存
     HttpContext.Current.Cache.Insert(key, obj, dep);
 }
Exemple #5
0
        private bool LoadMessagesIntoCache(string langtag)
        {
            lock (Sync)
            {
                // It is possible for multiple threads to race to this method. The first to
                // enter the above lock will insert the messages into the cache.
                // If we lost the race...no need to duplicate the work of the winning thread.
                if (System.Web.HttpRuntime.Cache[GetCacheKey(langtag)] != null)
                {
                    return(true);
                }

                Translation t = _translationRepository.GetTranslation(langtag);

                // Cache messages.
                // · In order to facilitate dynamic refreshing of translations during runtime
                //   (without restarting the server instance) we first establish something upon
                //   which the cache entry will be dependent: that is a 'cache dependency' object
                //   which essentially triggers an event if/when the entry is to be considered
                //   as 'dirty' and whihc is listened to by the cache.
                //   In our case, we want this 'dirty' event to be triggered if/when the
                //   translation's source PO file is updated.
                //   NB: it is possible for GetCacheDependencyForSingleLanguage to return null in the
                //   case of the default language where it is added to AppLanguages yet there
                //   doesn't actually exist an underlying PO file. This is perfectly valid when
                //   LocalizedApplication.MessageKeyIsValueInDefaultLanguage == true (default setting).
                //   In this case the cache entry is associated with the null CacheDependency instance
                //   which means the cache entry is effectively permanent for this server instance.
                System.Web.Caching.CacheDependency cd = _translationRepository.GetCacheDependencyForSingleLanguage(langtag);
                // · Insert translation into cache associating it with any CacheDependency.
                System.Web.HttpRuntime.Cache.Insert(GetCacheKey(langtag), t.Items, cd);
            }
            return(true);
        }
        /// <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[context.Request.Path] != null)
                {
                    context.Cache.Remove(context.Request.Path);
                }
            }
            else
            {
                if (context.Cache[context.Request.Path] != null)
                {
                    context.Cache[context.Request.Path] = 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(context.Request.Path, this._config, dependency, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, this._config.CacheDuration, 0), System.Web.Caching.CacheItemPriority.Normal, null);
                    }
                    else
                    {
                        context.Cache.Add(context.Request.Path, this._config, dependency, DateTime.Now.AddMinutes(this._config.CacheDuration), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
                    }
                }
            }
        }
 ///<summary>
 ///设置以缓存依赖的方式缓存数据
 ///</summary>
 ///<param name="CacheKey">索引键值</param>
 ///<param name="objObject">缓存对象</param>
 ///<param name="cacheDepen">依赖对象</param>
 public static void SetCache(string CacheKey, object objObject, System.Web.Caching.CacheDependency dep)
 {
     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);
 }
 public static void Set(string key, object value, System.Web.Caching.CacheDependency dependencies)
 {
     try
     {
         HttpContext.Current.Cache.Insert(key, value, dependencies);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
 /// <summary>
 /// 依赖缓存
 /// </summary>
 /// <param name="Name"></param>
 /// <param name="Data"></param>
 /// <param name="dep"></param>
 /// <returns></returns>
 public bool Set(string name, object data, System.Web.Caching.CacheDependency dep)
 {
     System.Web.Caching.Cache objCache = HttpRuntime.Cache;
     objCache.Insert(
         GetKey(name),
         data,
         dep,
         System.Web.Caching.Cache.NoAbsoluteExpiration, //从不过期
         System.Web.Caching.Cache.NoSlidingExpiration,  //禁用可调过期
         System.Web.Caching.CacheItemPriority.Default,
         null);
     return(true);
 }
 private void Page_Load(object sender, System.EventArgs e)
 {
     if (!this.IsPostBack)
     {
         lblInfo.Text += "Creating dependent item...<br>";
         Cache.Remove("Dependent");
         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("Dependent", item, dependency);
     }
 }
 public static void Add(string key, object cachingData, object cacheTimer,
                        bool isNoSlidingExpiration = true,
                        bool useSitecoreCache      = true,
                        bool globalCache           = false,
                        bool removeOnPublish       = true,
                        string siteName            = "",
                        string databaseName        = "",
                        System.Web.Caching.CacheDependency cacheDep          = null,
                        System.Web.Caching.CacheItemPriority priority        = System.Web.Caching.CacheItemPriority.Normal,
                        System.Web.Caching.CacheItemRemovedCallback callback = null)
 {
     CachingContext.Current.Add(key, cachingData, cacheTimer, isNoSlidingExpiration, useSitecoreCache, globalCache, removeOnPublish, siteName, databaseName, cacheDep, priority, callback);
 }
Exemple #12
0
        private static XmlDocument LoadDataAccessConfig()
        {
            XmlDocument xmlDoc = (XmlDocument)HttpRuntime.Cache["DataAccess.config"];

            if (xmlDoc == null)
            {
                string strFile = string.Format(@"{0}Configurations\DataAccess.config", WebRootPath.Instance.ToString());
                xmlDoc = new XmlDocument();
                xmlDoc.Load(strFile);
                System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency(strFile);
                HttpRuntime.Cache.Insert("DataAccess.config", xmlDoc, dep, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, null);
            }
            return(xmlDoc);
        }
Exemple #13
0
        /// <summary>
        /// Adds the cache item.
        /// </summary>
        /// <param name="rawKey">The raw key.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static T AddCacheItem(string rawKey, object value)
        {
            System.Web.Caching.Cache DataCache = HttpRuntime.Cache;

            if (DataCache[MasterCacheKeyArray()[0]] == null)
            {
                DataCache[MasterCacheKeyArray()[0]] = DateTime.Now;
            }

            System.Web.Caching.CacheDependency dependency = new System.Web.Caching.CacheDependency(null, MasterCacheKeyArray());
            DataCache.Insert(GetCacheKey(rawKey), value, dependency, DateTime.Now.AddMinutes(60), System.Web.Caching.Cache.NoSlidingExpiration);

            return((T)value);
        }
Exemple #14
0
        public static void AddCacheItem(string rawKey, object value)
        {
            System.Web.Caching.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.Now;
            }

            // Add a CacheDependency
            System.Web.Caching.CacheDependency dependency = new System.Web.Caching.CacheDependency(null, MasterCacheKeyArray);
            DataCache.Insert(GetCacheKey(rawKey), value, dependency, DateTime.Now.AddMinutes(CacheDuration), System.Web.Caching.Cache.NoSlidingExpiration);
        }
Exemple #15
0
        /// <summary>
        /// 读取可配置文件
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetSiteConfig(string key)
        {
            string     msg           = "";
            SiteConfig configSection = null;

            if (HttpRuntime.Cache["OrgCompanyMvc_SiteConfig"] == null)
            {
                var ConfigFile = AppDomain.CurrentDomain.BaseDirectory + "Config\\Site.config";

                if (!string.IsNullOrEmpty(ConfigFile))
                //这里的ConfigFile是你要读取的Xml文件的路径,如果为空,则使用默认的app.config文件
                {
                    try
                    {
                        var fileMap = new ExeConfigurationFileMap()
                        {
                            ExeConfigFilename = ConfigFile
                        };
                        var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
                        configSection = (SiteConfig)config.GetSection("SiteConfig");
                        msg           = configSection.KeyValues[key].Value;
                        //添加缓存依赖
                        System.Web.Caching.CacheDependency cdy = new System.Web.Caching.CacheDependency(ConfigFile);
                        //添加缓存项
                        HttpRuntime.Cache.Insert(
                            "OrgCompanyMvc_SiteConfig",
                            configSection,
                            cdy,
                            DateTime.MaxValue,
                            System.Web.Caching.Cache.NoSlidingExpiration
                            );
                    }
                    catch (Exception ex)
                    {
                        msg = "配置有误";
                    }
                }
            }
            else
            {
                configSection = (SiteConfig)HttpRuntime.Cache["OrgCompanyMvc_SiteConfig"];
                msg           = configSection.KeyValues[key].Value;
            }

            if (configSection == null)
            {
                msg = "配置有误";
            }
            return(msg);
        }
Exemple #16
0
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            string key        = "LWSVG" + StringUtils.ToURL(_src);
            string svgContent = "";

            try
            {
                _lock.AcquireReaderLock(-1);

                object obj = WebContext.Cache[key];

                if (obj != null)
                {
                    svgContent = obj.ToString();
                }
                else
                {
                    _lock.ReleaseReaderLock();
                    _lock.AcquireWriterLock(-1);

                    System.Web.Caching.CacheDependency dep = null;

                    if (_src.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || _src.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
                    {
                        svgContent = WebUtils.GetURLContent(_src);
                    }
                    else
                    {
                        _src = WebContext.Server.MapPath(_src);

                        StreamReader sr = new StreamReader(_src);
                        svgContent = sr.ReadToEnd();
                        sr.Close();

                        dep = new System.Web.Caching.CacheDependency(_src);
                    }

                    WebContext.Cache.Insert(key, svgContent, dep);
                }
            }
            finally
            {
                _lock.ReleaseLock();
            }

            writer.Write(svgContent);

            //base.Render(writer);
        }
Exemple #17
0
        const double CacheDuration = 1; //days
        protected void AddCacheItem(string rawKey, object value)
        {
            System.Web.Caching.Cache DataCache = HttpContext.Current.Cache;
            // Make sure cache dependency key is in the cache - if not , add it
            if (DataCache[MasterCacheKeyArray[0]] == null)
            {
                DataCache[MasterCacheKeyArray[0]] = DateTime.Now;
            }

            // Add Dependency
            System.Web.Caching.CacheDependency dependency =
                new System.Web.Caching.CacheDependency(null, MasterCacheKeyArray);

            DataCache.Insert(GetCacheKey(rawKey), value, dependency,
                             DateTime.Now.AddDays(CacheDuration), System.Web.Caching.Cache.NoSlidingExpiration);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string filePath = Request.MapPath("/20180528/File.txt");

            if (Cache["fileContent"] == null)
            {
                string fileContent = File.ReadAllText(filePath);
                System.Web.Caching.CacheDependency cDep = new System.Web.Caching.CacheDependency(filePath);
                Cache.Insert("fileContent", fileContent, cDep);
                Response.Write("data from file|" + fileContent);
            }
            else
            {
                Response.Write("data from Cache|" + Cache["fileContent"].ToString());
            }
        }
Exemple #19
0
        protected void Use(object sender, EventArgs e)
        {
            string CacheKey = "cachetest";
            object objModel = GetCache(CacheKey); //从缓存中获取

            if (objModel == null)                 //缓存里没有
            {
                objModel = DateTime.Now;          //把当前时间进行缓存
                if (objModel != null)
                {
                    //依赖 C:\\test.txt 文件的变化来更新缓存
                    System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency("C:\\test.txt");
                    SetCache(CacheKey, objModel, dep);//写入缓存
                }
            }
        }
        //Load thestatic Field
        private static void LoadinterestTopicsFromXML(string VRoot, string LangCode)
        {
            XmlDocument xmlConfig = new XmlDocument();

            HttpRuntime.Cache.Remove("ProfileinterestTopic");
            string configFile = HttpContext.Current.Server.MapPath(string.Format("{0}/configurations/ProfileData.config", VRoot));

            xmlConfig.Load(configFile);
            XmlNodeList xmlinterestTopics = xmlConfig.SelectNodes("/Root/InterestTopic");
            int         i = 0;

            foreach (XmlNode xmlInterestTopic in xmlinterestTopics)
            {
                if (i < 10) //Only 10 DB Fields are available... throw exception if more that 10 are found in the DB
                {
                    InterestTopic InterestTopic = new InterestTopic();
                    InterestTopic.ID      = xmlInterestTopic.Attributes["ID"].Value;
                    InterestTopic.DBField = xmlInterestTopic.Attributes["DBField"].Value;
                    if (InterestTopic.DBField.ToLower().IndexOf("interesttopic") == -1)
                    {
                        throw new SiemeException("ProfileInterestTopic", "LoadinterestTopicsFromXML()", "DBField in ProfileinterestTopics.config must  be InterestTopicx where x goes from 1 to 10");
                    }
                    InterestTopic.DisplayName      = xmlInterestTopic.SelectSingleNode(string.Format("./FriendlyName[@Lang = '{0}']", LangCode.ToLower())).InnerText;
                    InterestTopic.NameSingular     = xmlInterestTopic.SelectSingleNode(string.Format("./NameSingular[@Lang = '{0}']", LangCode.ToLower())).InnerText;
                    InterestTopic.NamePlural       = xmlInterestTopic.SelectSingleNode(string.Format("./NamePlural[@Lang = '{0}']", LangCode.ToLower())).InnerText;
                    InterestTopic.InterestSubTopic = new List <InterestSubTopic>();
                    XmlNodeList xmlInterestSubTopics = xmlInterestTopic.SelectNodes("./InterestSubTopics/InterestSubTopic");
                    foreach (XmlNode xmlInterestSubTopic in xmlInterestSubTopics)
                    {
                        InterestSubTopic InterestSubTopic = new InterestSubTopic();
                        InterestSubTopic.ID          = xmlInterestSubTopic.Attributes["ID"].Value;
                        InterestSubTopic.Value       = xmlInterestSubTopic.SelectSingleNode("./Value").InnerText;
                        InterestSubTopic.DisplayName = xmlInterestSubTopic.SelectSingleNode(string.Format("./FriendlyName[@Lang = '{0}']", LangCode.ToLower())).InnerText;
                        InterestTopic.InterestSubTopic.Add(InterestSubTopic);
                    }
                    interestTopics.Add(InterestTopic);
                }
                else
                {
                    throw new SiemeException("ProfileInterestTopic", "LoadinterestTopicsFromXML()", "Too Many interestTopics defined in ProfileinterestTopics.config");
                }
                i++;
            }
            //The Cache is only set for the static field to get reloaded in case that the config file got changed
            System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency(configFile);
            HttpRuntime.Cache.Insert("ProfileinterestTopic", string.Empty, dep);
        }
Exemple #21
0
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="Type">对象类型</param>
        /// <param name="fileName">文件路径</param>
        /// <param name="root">根元素</param>
        /// <returns></returns>
        public static object load(Type type, string fileName, string root)
        {
            FileStream fs = null;
            //System.Collections.Specialized.StringDictionary dictionary = new System.Collections.Specialized.StringDictionary();
            string cacheKey = Utils.MD5("bitcms_Xml_" + root + "_" + fileName);
            object obj      = DataCache.get(cacheKey);

            if (obj == null)
            {
                try
                {
                    // 打开 FileStream
                    using (fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        XmlSerializer serializer;
                        if (root != null)
                        {
                            XmlRootAttribute xmlRoot = new XmlRootAttribute();
                            xmlRoot.ElementName = root;
                            serializer          = new XmlSerializer(type, xmlRoot);
                        }
                        else
                        {
                            serializer = new XmlSerializer(type);
                        }
                        obj = serializer.Deserialize(fs);
                        //建立缓存依赖项
                        System.Web.Caching.CacheDependency cdd = new System.Web.Caching.CacheDependency(fileName);
                        DataCache.set(cacheKey, obj, cdd, DateTime.Now.AddDays(1));
                    }
                }
                catch (Exception e)
                {
                    Logs.error("SerializationHelper 反序列化", fileName + " " + e.Message);
                    obj = null;
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                }
            }

            return(obj);
        }
Exemple #22
0
        public object Add(string key, object value, System.Web.Caching.CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, System.Web.Caching.CacheItemPriority priority, HostCacheItemRemovedCallback onRemoveCallback)
        {
            if (!IsHostKey(key))
            {
                key = GetHostKey(key);
            }

            if (onRemoveCallback != null)
            {
                Callbacks[key] = onRemoveCallback;
                return(System.Web.HttpRuntime.Cache.Add(key, value, dependencies, absoluteExpiration, slidingExpiration, priority, new System.Web.Caching.CacheItemRemovedCallback(CacheItemRemoved)));
            }
            else
            {
                return(System.Web.HttpRuntime.Cache.Add(key, value, dependencies, absoluteExpiration, slidingExpiration, priority, null));
            }
        }
Exemple #23
0
        /// <summary>
        /// Adds an object into cache based on the parameters provided.
        /// </summary>
        /// <param name="tag">The tag.</param>
        /// <param name="name">The name.</param>
        /// <param name="itemPolicy">The itemPolicy object.</param>
        /// <param name="value">The value to store in cache.</param>
        /// <param name="dispatch">The dispatch.</param>
        /// <returns></returns>
        public object Set(object tag, string name, CacheItemPolicy itemPolicy, object value, ServiceCacheByDispatcher dispatch)
        {
            if (itemPolicy == null)
            {
                throw new ArgumentNullException("itemPolicy");
            }
            var updateCallback = itemPolicy.UpdateCallback;

            if (updateCallback != null)
            {
                updateCallback(name, value);
            }
            // item priority
            WebCacheItemPriority cacheItemPriority;

            switch (itemPolicy.Priority)
            {
            case CacheItemPriority.AboveNormal: cacheItemPriority = WebCacheItemPriority.AboveNormal; break;

            case CacheItemPriority.BelowNormal: cacheItemPriority = WebCacheItemPriority.BelowNormal; break;

            case CacheItemPriority.High: cacheItemPriority = WebCacheItemPriority.High; break;

            case CacheItemPriority.Low: cacheItemPriority = WebCacheItemPriority.Low; break;

            case CacheItemPriority.Normal: cacheItemPriority = WebCacheItemPriority.Normal; break;

            case CacheItemPriority.NotRemovable: cacheItemPriority = WebCacheItemPriority.NotRemovable; break;

            default: cacheItemPriority = WebCacheItemPriority.Default; break;
            }
            //
            var removedCallback = (itemPolicy.RemovedCallback == null ? null : new WebCacheItemRemovedCallback((n, v, c) => { itemPolicy.RemovedCallback(n, v); }));

            Cache.Insert(name, value, GetCacheDependency(tag, itemPolicy.Dependency, dispatch), itemPolicy.AbsoluteExpiration, itemPolicy.SlidingExpiration, cacheItemPriority, removedCallback);
            var registration = dispatch.Registration;

            if (registration != null && registration.UseHeaders)
            {
                var headerPolicy = new WebCacheDependency(null, new[] { name });
                var header       = dispatch.Header;
                header.Item = name;
                Cache.Insert(name + "#", header, headerPolicy, itemPolicy.AbsoluteExpiration, itemPolicy.SlidingExpiration, cacheItemPriority, null);
            }
            return(value);
        }
Exemple #24
0
        // load the cache object for NotTrackObjectEvents
        private static Dictionary <string, string> LoadCacheNotTrackObjectEvents(bool forceLoad)
        {
            if (forceLoad && HttpRuntime.Cache["NotTrackObjectEvents"] != null)
            {
                HttpRuntime.Cache.Remove("NotTrackObjectEvents");
            }

            // load tracking rules from config file
            Dictionary <string, string> collRules = new Dictionary <string, string>();
            XmlReaderSettings           xmlSet    = new XmlReaderSettings();

            xmlSet.IgnoreWhitespace = true;

            string    strFile = string.Format(@"{0}Configurations\NotTrackObjectEvents.rule", HttpContext.Current.Request.PhysicalApplicationPath);
            XmlReader xmlr    = null;

            try
            {
                xmlr = XmlReader.Create(strFile, xmlSet);
                while (xmlr.Read())
                {
                    if (xmlr.Depth == 1 && xmlr.NodeType == XmlNodeType.Element)
                    {
                        try
                        {
                            collRules.Add(xmlr.GetAttribute("rule").ToLower(), xmlr.GetAttribute("roles").ToLower());
                        }
                        catch
                        {
                            //ignore... if the Xml has 2 times the same entry
                        }
                    }
                }
                System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency(strFile);
                HttpRuntime.Cache.Insert("NotTrackObjectEvents", collRules, dep);
                return(collRules);
            }
            finally
            {
                if (xmlr != null)
                {
                    xmlr.Close();
                }
            }
        }
Exemple #25
0
        // load the cache object for NotTrackPageEvents
        private static Dictionary <string, string> LoadCacheNotTrackPageEvents(bool forceLoad)
        {
            if (forceLoad && HttpRuntime.Cache["NotTrackPageEvents"] != null)
            {
                HttpRuntime.Cache.Remove("NotTrackPageEvents");
            }

            Dictionary <string, string> collRules = new Dictionary <string, string>();
            // load tracking rules from config file
            XmlReaderSettings xmlSet = new XmlReaderSettings();

            xmlSet.IgnoreWhitespace = true;

            string    strFile = PageTrackingFile;
            XmlReader xmlr    = null;

            try
            {
                xmlr = XmlReader.Create(strFile, xmlSet);
                while (xmlr.Read())
                {
                    if (xmlr.Depth == 1 && xmlr.NodeType == XmlNodeType.Element)
                    {
                        try
                        {
                            collRules.Add(String.Concat(xmlr.GetAttribute("url").ToLower(), "|", xmlr.GetAttribute("event").ToLower()), xmlr.GetAttribute("roles").ToLower());
                        }
                        catch
                        {
                            //ignore... if the Xml has 2 times the same entry
                        }
                    }
                }
                System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency(strFile);
                HttpRuntime.Cache.Insert("NotTrackPageEvents", collRules, dep);
                return(collRules);
            }
            finally
            {
                if (xmlr != null)
                {
                    xmlr.Close();
                }
            }
        }
Exemple #26
0
 protected virtual void Dispose(bool disposing)
 {
     if ((disposing))
     {
         if (_cacheDependency != null)
         {
             _cacheDependency.Dispose(disposing);
         }
         if (_systemCacheDependency != null)
         {
             _systemCacheDependency.Dispose();
         }
         _fileNames             = null;
         _cacheKeys             = null;
         _cacheDependency       = null;
         _systemCacheDependency = null;
     }
 }
Exemple #27
0
        private void SetContextMenu()
        {
            string XSLPath     = Server.MapPath(Page.ResolveUrl("~/xsl/contextmenu.xsl"));
            string contextMenu = string.Empty;

            if (Cache[m_XMLPath] == null)
            {
                System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency(m_XMLPath);
                contextMenu = TransformXML(m_XMLPath, XSLPath);
                Cache.Insert(m_XMLPath, contextMenu, dep);
            }
            else
            {
                contextMenu = (string)Cache[m_XMLPath];
            }
            ContextMenu.Controls.Add(new System.Web.UI.LiteralControl(contextMenu));
            ContextMenu.Visible = true;
        }
Exemple #28
0
        private static List <LogSession> LoadChacheNotTrackSessions(bool forceLoad)
        {
            if (forceLoad && HttpRuntime.Cache["NotTrackSessions"] != null)
            {
                HttpRuntime.Cache.Remove("NotTrackSessions");
            }

            // load tracking rules from config file
            List <LogSession> collRules = new List <LogSession>();
            XmlReaderSettings xmlSet    = new XmlReaderSettings();

            xmlSet.IgnoreWhitespace = true;

            string strFile = string.Format(@"{0}Configurations\NotTrackSessions.rule", HttpContext.Current.Request.PhysicalApplicationPath);

            if (File.Exists(strFile))
            {
                XmlReader xmlr = null;
                try
                {
                    xmlr = XmlReader.Create(strFile, xmlSet);
                    while (xmlr.Read())
                    {
                        if (xmlr.Depth == 1 && xmlr.NodeType == XmlNodeType.Element)
                        {
                            collRules.Add(new LogSession {
                                IP = xmlr.GetAttribute("ip"), System = xmlr.GetAttribute("system")
                            });
                        }
                    }
                    System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency(strFile);
                    HttpRuntime.Cache.Insert("NotTrackSessions", collRules, dep);
                    return(collRules);
                }
                finally
                {
                    if (xmlr != null)
                    {
                        xmlr.Close();
                    }
                }
            }
            return(collRules);
        }
Exemple #29
0
        /// <summary>
        /// 设置缓存,并建立依赖关系
        /// </summary>
        /// <param name="cacheName">缓存的名称</param>
        /// <param name="val">要缓存的对象</param>
        /// <param name="cacheDepKeys">缓存的依赖关系</param>
        public static void SetCache(string cacheName, object val, string[] cacheDepKeys)
        {
            if (cacheDepKeys.Length == 0)
            {
                return;
            }
            System.Web.Caching.CacheDependency dependency = new System.Web.Caching.CacheDependency(cacheDepKeys);

            HttpRuntime.Cache.Insert(cacheName, val, dependency);
            //  HttpRuntime.Cache.Insert(cacheName, val);
            //TimeSpan ts = new TimeSpan(1, 0, 0);
            //HttpRuntime.Cache.Insert(cacheName, val, dependency, DateTime.UtcNow.AddMinutes(30), TimeSpan.Zero);
            // , DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.High, null);
            //DateTime absoluteexpiration = DateTime.maxvalue;
            //TimeSpan slidingexpiration = TimeSpan.FromMinutes(10);//.fromminutes(10);
            //HttpRuntime.Cache.Insert("txt", "a", null,
            //absoluteexpiration, slidingexpiration,
            //System.Web.Caching.CacheItemPriority.High, null);
        }
Exemple #30
0
        /// <summary>
        /// 单点登录实现,可以放在05-Infrastructure中,进行中…………………………………………………………
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        private bool IsLogin(string userId, string userName)
        {
            string existUser = Convert.ToString(HttpRuntime.Cache[userId]);

            if (string.IsNullOrEmpty(existUser))
            {
                #region 缓存依赖项
                string loginUserId = "loginUserId";
                Session[userId] = userId;
                HttpRuntime.Cache.Insert(loginUserId, Session[userId]);
                System.Web.Caching.CacheDependency dep = new System.Web.Caching
                                                         .CacheDependency(null, new string[] { loginUserId });
                #endregion

                HttpRuntime.Cache.Insert(userId, userName, dep);
                return(false);
            }
            return(true);
        }
        /// <summary>
        /// Salva os dados para o cache.
        /// </summary>
        /// <param name="startRowIndex"></param>
        /// <param name="maximumRows"></param>
        /// <param name="data"></param>
        internal void SaveDataToCache(int startRowIndex, int maximumRows, object data)
        {
            string key  = this.CreateCacheKey(startRowIndex, maximumRows);
            string str2 = this.CreateMasterCacheKey();

            if (this.Cache.LoadDataFromCache(str2) == null)
            {
                this.Cache.SaveDataToCache(str2, -1);
            }
            var constructor = typeof(System.Web.Caching.CacheDependency).GetConstructor(new Type[] {
                typeof(int),
                typeof(string[]),
                typeof(string[])
            });

            System.Web.Caching.CacheDependency dependency = null;
            if (constructor == null)
            {
                dependency = new System.Web.Caching.CacheDependency(new string[0], new string[] {
                    str2
                });
            }
            else
            {
                try
                {
                    dependency = (System.Web.Caching.CacheDependency)constructor.Invoke(new object[] {
                        0,
                        new string[0],
                        new string[] {
                            str2
                        }
                    });
                }
                catch (System.Reflection.TargetInvocationException ex)
                {
                    throw ex.InnerException;
                }
            }
            this.Cache.SaveDataToCache(key, data, dependency);
        }
Exemple #32
0
 private void FileWatchInit(string filePath)
 {
     if (!string.IsNullOrEmpty(filePath))
     {
         string cacheKey = GenerateCacheKey();
         var dep = new System.Web.Caching.CacheDependency(filePath);
         HttpRuntime.Cache.Insert(cacheKey, filePath, dep,
             System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration,
             System.Web.Caching.CacheItemPriority.NotRemovable, CacheItemRemovedCallback);
     }
 }
Exemple #33
0
 public static Query GetQuery(string queryName)
 {
     if (HttpRuntime.Cache["Query" + queryName] == null)
     {
         string filename = Path.Combine(HttpRuntime.AppDomainAppPath, "app_data\\query\\" + queryName + ".txt");
         Query q = GetQueryByFile(filename);
         q.Name = queryName;//���ļ�����query������,�����ļ����������ʵ������
         if (q != null)
         {
             System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency(filename);
             HttpRuntime.Cache.Add("Query" + queryName, q, dep, new DateTime(2100, 1, 1), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);
         }
     }
     return (Query)HttpRuntime.Cache["Query" + queryName];
 }
        /// <summary>
        /// 单点登录实现,可以放在05-Infrastructure中,进行中…………………………………………………………
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        private bool IsLogin(string userId, string userName)
        {
            string existUser = Convert.ToString(HttpRuntime.Cache[userId]);
            if (string.IsNullOrEmpty(existUser))
            {
                #region 缓存依赖项
                string loginUserId = "loginUserId";
                Session[userId] = userId;
                HttpRuntime.Cache.Insert(loginUserId, Session[userId]);
                System.Web.Caching.CacheDependency dep = new System.Web.Caching
                    .CacheDependency(null, new string[] { loginUserId });
                #endregion

                HttpRuntime.Cache.Insert(userId, userName, dep);
                return false;
            }
            return true;
        }
 protected virtual void Dispose(bool disposing)
 {
     if ((disposing))
     {
         if (_cacheDependency != null)
             _cacheDependency.Dispose(disposing);
         if (_systemCacheDependency != null)
             _systemCacheDependency.Dispose();
         _fileNames = null;
         _cacheKeys = null;
         _cacheDependency = null;
         _systemCacheDependency = null;
     }
 }
 public CacheDependency(System.Web.Caching.CacheDependency systemCacheDependency)
 {
     _systemCacheDependency = systemCacheDependency;
 }
 /// <summary>
 /// Adds an object into cache based on the parameters provided.
 /// </summary>
 /// <param name="tag">The tag.</param>
 /// <param name="name">The name.</param>
 /// <param name="itemPolicy">The itemPolicy object.</param>
 /// <param name="value">The value to store in cache.</param>
 /// <param name="dispatch">The dispatch.</param>
 /// <returns></returns>
 public object Set(object tag, string name, CacheItemPolicy itemPolicy, object value, ServiceCacheByDispatcher dispatch)
 {
     if (itemPolicy == null)
         throw new ArgumentNullException("itemPolicy");
     var updateCallback = itemPolicy.UpdateCallback;
     if (updateCallback != null)
         updateCallback(name, value);
     // item priority
     WebCacheItemPriority cacheItemPriority;
     switch (itemPolicy.Priority)
     {
         case CacheItemPriority.AboveNormal: cacheItemPriority = WebCacheItemPriority.AboveNormal; break;
         case CacheItemPriority.BelowNormal: cacheItemPriority = WebCacheItemPriority.BelowNormal; break;
         case CacheItemPriority.High: cacheItemPriority = WebCacheItemPriority.High; break;
         case CacheItemPriority.Low: cacheItemPriority = WebCacheItemPriority.Low; break;
         case CacheItemPriority.Normal: cacheItemPriority = WebCacheItemPriority.Normal; break;
         case CacheItemPriority.NotRemovable: cacheItemPriority = WebCacheItemPriority.NotRemovable; break;
         default: cacheItemPriority = WebCacheItemPriority.Default; break;
     }
     //
     var removedCallback = (itemPolicy.RemovedCallback == null ? null : new WebCacheItemRemovedCallback((n, v, c) => { itemPolicy.RemovedCallback(n, v); }));
     Cache.Insert(name, value, GetCacheDependency(tag, itemPolicy.Dependency, dispatch), itemPolicy.AbsoluteExpiration, itemPolicy.SlidingExpiration, cacheItemPriority, removedCallback);
     var registration = dispatch.Registration;
     if (registration != null && registration.UseHeaders)
     {
         var headerPolicy = new WebCacheDependency(null, new[] { name });
         var header = dispatch.Header;
         header.Item = name;
         Cache.Insert(name + "#", header, headerPolicy, itemPolicy.AbsoluteExpiration, itemPolicy.SlidingExpiration, cacheItemPriority, null);
     }
     return value;
 }
        private void CreateCacheDependency(string version, bool isCompressed, HttpContext context, byte[]responseBytes)
        {
            try
            {
                string CacheName = GetCacheKey(version, isCompressed);
                System.Web.Caching.AggregateCacheDependency __agg = new System.Web.Caching.AggregateCacheDependency();
                System.Web.Caching.CacheDependency[] __c1 = new System.Web.Caching.CacheDependency[2];
                int i = 0;
                foreach (string fileName in _files)
                {

                    string physicalPath = context.Server.MapPath(fileName);
                    __c1[i] = new System.Web.Caching.CacheDependency(physicalPath);
                }
                __agg.Add(__c1);
                context.Cache.Insert(CacheName, responseBytes, __agg, System.Web.Caching.Cache.NoAbsoluteExpiration, CACHE_DURATION);
            }
            catch (Exception ex)
            {
            }

        }
Exemple #39
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);
        }
        public static void Insert(string key, object keyValue, CacheDependency dep)
        {
            // Create the array of cache keys for the CacheDependency ctor
            string storageKey = GetHelperKeyName(key);
            string[] rgDepKeys = new string[1];
            rgDepKeys[0] = storageKey;

            // Create a helper cache key
            HttpContext.Current.Cache.Insert(storageKey, dep);

            // Create a standard CacheDependency object
            System.Web.Caching.CacheDependency keyDep;
            keyDep = new System.Web.Caching.CacheDependency(null, rgDepKeys);

            // Create a new entry in the cache and make it dependent on a helper key
            HttpContext.Current.Cache.Insert(key, keyValue, keyDep);
        }
 public static void AddWithDependency(string key, object value)
 {
     var dependency = new System.Web.Caching.CacheDependency(GetOptionPath());
     HttpRuntime.Cache.Insert(key, value, dependency);
 }