示例#1
0
 public static void RefreshTableConfig(string key)
 {
     try
     {
         Hashtable infTableDef = new Hashtable();
         String    sql         = "select * from sys_report where seqno = '" + key + "'";
         DataTable dt          = DbHelperOra.Query(sql).Tables[0];
         string    sqlSpec     = dt.Rows[0].Field <string>("SELECTSQL");
         DataTable dataDt      = DbHelperOra.Query(sqlSpec).Tables[0];
         //foreach (DataRow dr in dt.Rows)
         //{
         //    infTableDef.Add(dr["INFKEY"].ToString(), dr["INFVALUE"].ToString());
         //}
         System.Web.Caching.Cache objCache = HttpRuntime.Cache;
         InfTableCacheCallBack = new System.Web.Caching.CacheItemRemovedCallback(RemovedCallback);
         objCache.Add(
             key,
             dataDt,
             null,
             DateTime.Now.Add(TimeSpan.FromMinutes(30)),
             TimeSpan.Zero,
             System.Web.Caching.CacheItemPriority.Default,
             InfTableCacheCallBack);
         //InfTableCacheRemoved = false;
     }
     catch (Exception ex) {
         //LogHelper.WriteLog("CacheError_"+key, ex);
         //PubFunc.OperLog("缓存管理", "00", "admin", "CacheError_" + key + "_" + ex.Message);
     }
     //两小时失效
     //CacheHelper.SetCache(INF_TABLE_CACHE_NAME, infTableDef, TimeSpan.FromHours(2));
 }
示例#2
0
        /// <summary>
        ///
        /// </summary>
        private void AddReminderTask()
        {
            OnCacheRemove = new System.Web.Caching.CacheItemRemovedCallback(CacheItemRemoved);

            // Figure out the time for next Scan...
            //  A scan happens every hour on the hour
            int      seconds         = 0;
            DateTime centralDateTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, "Central Standard Time");

            // Now calculate the next time the scan should run
            seconds = (60 - DateTime.Now.Minute) * 60;

            /* Todo: This isn't working...
             * //   Each day there will be 4 auto scans:
             * //   1.  7am
             * //   2. 12pm
             * //   3.  7pm
             * //   4. 12am
             * int seconds = 0;
             * DateTime centralDateTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, "Central Standard Time");
             *
             * // DEBUGGING
             * //centralDateTime = new DateTime(2018, 9, 21, 13, 0, 0);
             *
             * if (centralDateTime.Hour >= 0 && centralDateTime.Hour < 7)
             * {
             *  TimeSpan remind = new DateTime(centralDateTime.Year, centralDateTime.Month, centralDateTime.Day, 7, 0, 0) - centralDateTime;
             *  seconds = Convert.ToInt32(remind.TotalSeconds) + 60;
             * }
             * else if (centralDateTime.Hour >= 7 && centralDateTime.Hour < 12)
             * {
             *  TimeSpan remind = new DateTime(centralDateTime.Year, centralDateTime.Month, centralDateTime.Day, 12, 0, 0) - centralDateTime;
             *  seconds = Convert.ToInt32(remind.TotalSeconds) + 60;
             * }
             * else if (centralDateTime.Hour >= 12 && centralDateTime.Hour < 19)
             * {
             *  TimeSpan remind = new DateTime(centralDateTime.Year, centralDateTime.Month, centralDateTime.Day, 19, 0, 0) - centralDateTime;
             *  seconds = Convert.ToInt32(remind.TotalSeconds) + 60;
             * }
             * else if (centralDateTime.Hour >= 19)
             * {
             *  TimeSpan remind = new DateTime(centralDateTime.Year, centralDateTime.Month, centralDateTime.Day, 23, 59, 59) - centralDateTime;
             *  seconds = Convert.ToInt32(remind.TotalSeconds) + 60;
             * }
             * else
             * {
             *  // Do it immediately
             *  seconds = 60;
             * }
             */

            // Store it
            System.Configuration.ConfigurationManager.AppSettings["LastGuildScan"] = System.Configuration.ConfigurationManager.AppSettings["NextGuildScan"];
            System.Configuration.ConfigurationManager.AppSettings["NextGuildScan"] = centralDateTime.AddSeconds(seconds).ToString();

            // Now set the cache for the future
            HttpRuntime.Cache.Insert("RescanGuild", seconds, null, DateTime.Now.AddSeconds(seconds), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.NotRemovable, OnCacheRemove);
        }
        public ActionResult RecibirEvento(int?id)
        {
            System.Web.Caching.CacheItemRemovedCallback callback = new System.Web.Caching.CacheItemRemovedCallback(OnRemove);
            Stream req = Request.InputStream;

            req.Seek(0, System.IO.SeekOrigin.Begin);
            string json = new StreamReader(req).ReadToEnd();

            string _mensaje      = "";
            int    tiempoEnCache = 5; //Si no lo encuentra por defecto son 5 (expresado en minutos)..

            try
            {
                DtoEventos evento = Newtonsoft.Json.JsonConvert.DeserializeObject <DtoEventos>(json);
                int        tiempo = RepositorioConfiguraciones.ObtenerTiempoDelay(evento.Id_Arduino, evento.Id_Senal);
                guardarEvento(evento); //Todos los eventos se guardan
                if (tiempo != -1)
                {
                    tiempoEnCache = tiempo;
                }
                if (evento.Id_Senal == 1) //Si la señal es de luz lo manejo, sino lo guardo de una..
                {
                    if (estaEnCache("NotifacionLuz" + evento.Id_Arduino))
                    {
                        System.Web.HttpContext.Current.Cache.Remove("NotifacionLuz" + evento.Id_Arduino);
                        if (evento.Valor == 1)
                        {
                            System.Web.HttpContext.Current.Cache.Insert("NotifacionLuz" + evento.Id_Arduino, evento, null, DateTime.Now.AddMinutes(tiempoEnCache), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, callback);
                        }
                    }
                    else
                    {
                        if (evento.Valor == 1)
                        {
                            System.Web.HttpContext.Current.Cache.Insert("NotifacionLuz" + evento.Id_Arduino, evento, null, DateTime.Now.AddMinutes(tiempoEnCache), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, callback);
                        }
                        else
                        {
                            guardarNotificacion(evento);
                        }
                    }
                }
                else
                {
                    guardarNotificacion(evento);
                }

                return(new HttpStatusCodeResult(HttpStatusCode.Created));
            }
            catch (Exception ex)
            {
                _mensaje = ex.Message;
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
        }
示例#4
0
 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);
 }
        public void LoadModules()
        {
            if (HttpRuntime.Cache["MODULES"] == null)
            {
                XmlDocument applicationcatalogue = new XmlDocument();

                applicationcatalogue.Load(new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "\\applicationmodulecatalogue.xml"));
                XmlDocument         modulecache  = new XmlDocument();
                List <ModuleParams> moduleparams = new List <ModuleParams>();
                string modulepath     = string.Empty;
                string ModuleFileName = string.Empty;
                string ModuleName     = string.Empty;

                foreach (XmlNode app in applicationcatalogue.SelectNodes("ApplicationList/Application"))
                {
                    if (app.SelectSingleNode("@Enabled").Value == "true")
                    {
                        modulecache.Load(new StreamReader(AppDomain.CurrentDomain.BaseDirectory + app.SelectSingleNode("@ApplicaitonPath").Value + "\\" + app.SelectSingleNode("@ModulePath").Value + "\\Modulecatalogue.xml"));

                        foreach (XmlNode module in modulecache.SelectNodes("ModuleList/Module"))
                        {
                            if (module.SelectSingleNode("@Enabled").Value == "true")
                            {
                                ModuleFileName = module.SelectSingleNode("@FileName").Value;
                                ModuleName     = ModuleFileName.Remove(ModuleFileName.LastIndexOf('.'));
                                string css = null;
                                if (module.SelectSingleNode("@CSS") != null)
                                {
                                    css = "~/" + app.SelectSingleNode("@ApplicaitonPath").Value + "/" + module.SelectSingleNode("@ModulePath").Value + "/" + module.SelectSingleNode("@NameSpace").Value + "/" + module.SelectSingleNode("@CSS").Value;
                                }
                                modulepath = "~/" + app.SelectSingleNode("@ApplicaitonPath").Value + "/" + module.SelectSingleNode("@ModulePath").Value + "/" + module.SelectSingleNode("@NameSpace").Value + "/" + module.SelectSingleNode("@FileName").Value;
                                if (this.GetModule(module.SelectSingleNode("@NameSpace").Value) == null)
                                {
                                    _modules.Add(new Module(modulepath, ModuleName, null, "", css));
                                }
                                _modules.Add(new Module(modulepath, app.SelectSingleNode("@ApplicaitonPath").Value + "." + ModuleName, null, "", css));
                                moduleparams = new List <ModuleParams>();
                            }
                        }

                        modulecache = new XmlDocument();
                    }
                }

                System.Web.Caching.CacheItemRemovedCallback callback = new System.Web.Caching.CacheItemRemovedCallback(OnRemove);
                HttpRuntime.Cache.Insert("MODULES", _modules, null, DateTime.Now.AddHours(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, callback);
            }
        }
示例#6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            int?turnCounter;

            turnCounter = Application.Get("turnCounter") as Nullable <Int32>;
            OnRemove   += new System.Web.Caching.CacheItemRemovedCallback(myCacheItemRemovedCallback);

            if (!turnCounter.HasValue)
            {
                turnCounter = 0;
                Application.Set("turnCounter", turnCounter);
                RegisterCacheEntry(60);

                EmpiresInSpace.Server._60turns.newTurnServer();
            }
        }
示例#7
0
文件: Cache.cs 项目: Nc-light/Weixin
        public bool SetObject2Cache(string key, object value)
        {
            bool r = false;

            onRemove = new System.Web.Caching.CacheItemRemovedCallback(this.RemovedCallback);
            if (!this.IsExist(key))
            {
                try
                {
                    HttpRuntime.Cache.Insert(key, value, null, DateTime.UtcNow.Add(new TimeSpan(48, 0, 0)), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.NotRemovable, onRemove);
                    r = true;
                    //NCD.WebLog.SysWebLog.WriteCustomLog("cache", key+" adding cacheX....");
                }
                catch (Exception e)
                {
                    //NCD.WebLog.SysWebLog.WriteCustomLog("Cache", "SetObject2Cache[" + key + "] is error:" + e.ToString());
                }
            }
            return(r);
        }
示例#8
0
 /// <summary>
 /// 本地缓存写入,包括分钟,是否绝对过期及缓存过期的回调
 /// </summary>
 /// <param name="name">key</param>
 /// <param name="value">value</param>
 /// <param name="minutes"缓存分钟></param>
 /// <param name="isAbsoluteExpiration">是否绝对过期</param>
 /// <param name="onRemoveCallback">缓存过期回调</param>
 public static void Set(string name, object value, int minutes, bool isAbsoluteExpiration, System.Web.Caching.CacheItemRemovedCallback onRemoveCallback)
 {
     if (isAbsoluteExpiration)
     {
         HttpRuntime.Cache.Insert(name, value, null, DateTime.Now.AddMinutes(minutes), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, onRemoveCallback);
     }
     else
     {
         HttpRuntime.Cache.Insert(name, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(minutes), System.Web.Caching.CacheItemPriority.Normal, onRemoveCallback);
     }
 }
示例#9
0
 public object Add(string key, object value, System.Web.Caching.CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, System.Web.Caching.CacheItemPriority priority, System.Web.Caching.CacheItemRemovedCallback onRemoveCallback)
 {
     return(Cache.Add(RegionKey(key), value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback));
 }
示例#10
0
 public object Add(string key, object value, System.Web.Caching.CacheDependency dependencies, System.Web.Caching.CacheItemRemovedCallback onRemoveCallback)
 {
     return(Cache.Add(RegionKey(key), value, dependencies, onRemoveCallback));
 }
示例#11
0
 public object Add(string key, object value, TimeSpan slidingExpiration, System.Web.Caching.CacheItemRemovedCallback onRemoveCallback)
 {
     return(Cache.Add(RegionKey(key), value, slidingExpiration, onRemoveCallback));
 }
示例#12
0
 public object Add(string key, object value, DateTime absoluteExpiration, System.Web.Caching.CacheItemRemovedCallback onRemoveCallback)
 {
     return(Cache.Add(RegionKey(key), value, absoluteExpiration, onRemoveCallback));
 }
示例#13
0
 public void Insert <T>(string key, T value, System.Web.Caching.CacheDependency dependencies, System.DateTime absoluteExpiration, System.TimeSpan slidingExpiration, System.Web.Caching.CacheItemPriority priority, System.Web.Caching.CacheItemRemovedCallback onRemoveCallback) where T : class
 {
     Cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback);
 }
 public Stream Add(string key, Stream value, System.Web.Caching.CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, System.Web.Caching.CacheItemPriority priority, System.Web.Caching.CacheItemRemovedCallback onRemoveCallback)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Saves the list to the cache
        /// </summary>
        /// <typeparam name="T">The type of parameter that will be saved</typeparam>
        /// <param name="cacheKey">The unique key to save</param>
        /// <param name="cachingData">The data to cache</param>
        /// <param name="cacheTimer">The time we want to cache this data</param>
        /// <param name="isNoSlidingExpiration">Is the cacheTimer an Absolute Expiration (default) or a sliding expiration</param>
        /// <param name="useSitecoreCache">Do you want to use Sitecore cache or the HttpRuntime cache object</param>
        /// <param name="cacheSize">The size of the cache, this will fetch the size dynamically if not provided</param>
        /// <param name="globalCache">Is the data to be stored in the global cache or site specific cache</param>
        /// <param name="removeOnPublish">Remove the contents on a publish, this is defaulted as true</param>
        /// <param name="siteName">Force set the site name, if this is run from a scheduled task this should be set</param>
        /// <param name="databaseName">Force the database if this is run from a scheduled tasks, this should be set</param>
        /// <param name="cacheDep">Any caching dependencies for the cache. NOTE: Not valid for Sitecore Caching</param>
        /// <param name="priority">The priority of the cache. NOTE: Not valid for Sitecore Caching</param>
        /// <param name="callback">The call-back function of the cache. NOTE: Not valid for Sitecore Caching</param>
        public void SaveCachedItem <T>(string cacheKey, object cachingData, object cacheTimer,
                                       bool isNoSlidingExpiration = true,
                                       bool useSitecoreCache      = true,
                                       long cacheSize             = 0,
                                       bool globalCache           = false,
                                       bool removeOnPublish       = true,
                                       string siteName            = "default",
                                       string databaseName        = "master",
                                       System.Web.Caching.CacheDependency cacheDep          = null,
                                       System.Web.Caching.CacheItemPriority priority        = System.Web.Caching.CacheItemPriority.Normal,
                                       System.Web.Caching.CacheItemRemovedCallback callback = null)
        {
            // make sure we have data
            if (!string.IsNullOrEmpty(cacheKey) &&
                cachingData != null)
            {
                // set the key so we can override it
                string key = cacheKey.ToLower();

                if (!removeOnPublish)
                {
                    key = string.Format(NonPublishKey, key).ToLower();
                }

                // setup defaults for caching types
                TimeSpan slidingCache  = System.Web.Caching.Cache.NoSlidingExpiration;
                DateTime absoluteCache = System.Web.Caching.Cache.NoAbsoluteExpiration;

                // set the cache type
                if (isNoSlidingExpiration)
                {
                    // make sure it's right
                    if (cacheTimer.GetType().Equals(typeof(DateTime)))
                    {
                        absoluteCache = (DateTime)cacheTimer;
                    }
                    else
                    {
                        // we have an issue fix up
                        TimeSpan timeSpanCheck = (TimeSpan)cacheTimer;
                        absoluteCache = DateTime.UtcNow.Add(timeSpanCheck);
                    }
                }
                else
                {
                    // make sure it's right
                    if (cacheTimer.GetType().Equals(typeof(TimeSpan)))
                    {
                        slidingCache = (TimeSpan)cacheTimer;
                    }
                    else
                    {
                        // we have an issue fix up
                        DateTime dateCheck = (DateTime)cacheTimer;
                        slidingCache = dateCheck.Subtract(DateTime.UtcNow);
                    }
                }

                // what type of cache are we using
                if (useSitecoreCache)
                {
                    #region Sitecore Cache
                    Sitecore.Caching.Cache cache = SitecoreCache(globalCache, siteName, databaseName);

                    if (cache.ContainsKey(key))
                    {
                        // remove the key
                        cache.Remove(key);
                    }

                    // do we have to work out the cache size
                    if (cacheSize == 0)
                    {
                        // we need to do a binary serialization to get the objects size
                        try
                        {
                            System.IO.MemoryStream mem = new System.IO.MemoryStream();
                            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                            binFormatter.Serialize(mem, cachingData);
                            cacheSize = mem.Length + 500; // increase just in case
                        }
                        catch (System.Exception ex)
                        {
                            // log and setup defaults
                            cacheSize = 1500; // default size we have made it bigger than normal just in case

                            // do we display the serialization error
                            if (_errorLogsEnabled)
                            {
                                Sitecore.Diagnostics.Log.Warn(string.Format("Cache - Size Serialize: '{0}'", key), ex, typeof(CacheHandler));
                            }

                            // is the type an IEnumerable
                            // get the cached item type
                            Type tType = cachingData.GetType();

                            // the type is a collection
                            if (typeof(System.Collections.ICollection).IsAssignableFrom(tType) ||
                                typeof(ICollection <>).IsAssignableFrom(tType))
                            {
                                // we want to try and see if the item is a collection
                                try
                                {
                                    // set the data as ICollection so we can get the data
                                    System.Collections.ICollection iEnum = (cachingData as System.Collections.ICollection);

                                    // make sure it casts correctly
                                    if (iEnum != null)
                                    {
                                        // we need to set this as it will cause issues
                                        long fakeCacheSize = cacheSize;
                                        cacheSize = iEnum.Count * fakeCacheSize;
                                    }
                                }
                                catch (System.Exception exer)
                                {
                                    cacheSize = 5000; // at least set it bigger just in case

                                    // do we display the logs
                                    if (_errorLogsEnabled)
                                    {
                                        Sitecore.Diagnostics.Log.Warn(string.Format("Cache - Collection Count: '{0}'", key), exer, typeof(CacheHandler));
                                    }
                                }
                            }
                        }
                    }

                    // use the sitecore cache
                    cache.Add(key.ToLower(), cachingData, cacheSize, slidingCache, absoluteCache);
                    #endregion
                }
                else
                {
                    #region HttpRuntime Cache
                    // set the cache key
                    string cacheStartKey = GetBaseKey(globalCache, siteName, databaseName) + key;

                    // confirm the cache sliding
                    System.Web.HttpRuntime.Cache.Add(cacheStartKey.ToLower(), cachingData, cacheDep, absoluteCache, slidingCache, priority, callback);
                    #endregion
                }
            }
        }
        /// <inheritdoc />
        public 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)
        {
            // make sure we have data
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (cachingData == null)
            {
                throw new ArgumentNullException(nameof(cachingData));
            }

            if (!removeOnPublish)
            {
                key = KeyAgent.AddKeepAfterPublish(key);
            }

            // setup defaults for caching types
            TimeSpan slidingCache  = System.Web.Caching.Cache.NoSlidingExpiration;
            DateTime absoluteCache = System.Web.Caching.Cache.NoAbsoluteExpiration;

            // set the cache type
            if (isNoSlidingExpiration)
            {
                // make sure it's right
                if (cacheTimer is DateTime)
                {
                    absoluteCache = (DateTime)cacheTimer;
                }
                else
                {
                    // we have an issue fix up
                    var timeSpanCheck = (TimeSpan)cacheTimer;
                    absoluteCache = DateTime.Now.Add(timeSpanCheck);
                }
            }
            else
            {
                // make sure it's right
                if (cacheTimer is TimeSpan)
                {
                    slidingCache = (TimeSpan)cacheTimer;
                }
                else
                {
                    // we have an issue fix up
                    var dateCheck = (DateTime)cacheTimer;
                    slidingCache = dateCheck.Subtract(DateTime.Now);
                }
            }

            // what type of cache are we using
            if (useSitecoreCache)
            {
                ICache cache = SitecoreCacheManager.GetCache(globalCache, siteName, databaseName);

                if (cache.ContainsKey(key))
                {
                    cache.Remove(key);
                }

                cache.Add(key, cachingData, slidingCache, absoluteCache);
            }
            else
            {
                var cacheStartKey = KeyAgent.GetBaseKey(globalCache, siteName, databaseName) + key;

                System.Web.HttpRuntime.Cache.Add(cacheStartKey, cachingData, cacheDep, absoluteCache, slidingCache, priority, callback);
            }
        }
        public static void Insert(string key, object value, TimeSpan cacheDuration, CacheExpirationType ExType, System.Web.Caching.CacheItemPriority priority, System.Web.Caching.CacheItemRemovedCallback callback)
        {
            if (!EnableCaching)
            {
                context.Trace.Warn("Caching is disabled.");
            }
            else
            {
                context = System.Web.HttpContext.Current;
                switch (ExType)
                {
                case CacheExpirationType.Absolute:
                    context.Cache.Insert(key, value, null, DateTime.Now.Add(cacheDuration), System.Web.Caching.Cache.NoSlidingExpiration, priority, callback);
                    break;

                case CacheExpirationType.Sliding:
                    context.Cache.Insert(key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, cacheDuration, priority, callback);
                    break;
                }

                context.Trace.Write(key + " cached for a duration of " + cacheDuration + ".");
            }
        }
 public static void Insert(string key, object value, CacheExpirationType ExType, System.Web.Caching.CacheItemPriority priority, System.Web.Caching.CacheItemRemovedCallback callback)
 {
     Insert(key, value, GetCacheDuration(key), ExType, priority, callback);
 }
示例#19
0
        /// <summary>
        /// Override the Render() method with a do-nothing method.
        /// </summary>
        /// <param name="output"></param>
        protected override void Render( HtmlTextWriter output )
        {
            MasterPane masterPane = null;

            bool bDesignMode = ( this.Page.Site != null && this.Page.Site.DesignMode );

            if ( !bDesignMode && this.RenderMode == RenderModeType.RawImage )
            {
                //Render on the fly
                if ( this.CacheDuration > 0 )
                {
                    System.Web.HttpContext context = System.Web.HttpContext.Current;
                    System.Web.HttpCachePolicy policy = context.Response.Cache;
                    if ( policy != null )
                    {
                        policy.SetExpires( DateTime.Now.AddSeconds( this.CacheDuration ) );
                    }
                }

                Draw( true );
            }
            else
            {
                //Render as a file and an IMG tag
                try
                {
                    string tempFileName, tempFilePathName;

                    //In design, we always recreate the file. No caching is allowed.
                    if ( bDesignMode )
                    {
                        //Create temporary file if it does not exists
                        if ( DesignTimeFileStream == null )
                        {
                            tempFilePathName = Path.GetTempFileName();
                            DesignTimeFileStream = new FileStream( tempFilePathName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite );
                            tempFileName = Path.GetFileName( tempFilePathName );
                        }
                        else
                        {
                            tempFilePathName = DesignTimeFileStream.Name;
                            tempFileName = Path.GetFileName( tempFilePathName );
                            DesignTimeFileStream.SetLength( 0 );
                            DesignTimeFileStream.Seek( 0, SeekOrigin.Begin );
                        }
                    }
                    else
                    {
                        tempFileName = this.ClientID + System.Guid.NewGuid().ToString() +
                            ( this.CacheSuffix != null && this.CacheSuffix.Length > 0 ? this.CacheSuffix : "" ) +
                            "." + this.ImageFormatFileExtension;
                        tempFilePathName = Context.Server.MapPath( this.RenderedImagePath );
                        tempFilePathName = Path.Combine( tempFilePathName, tempFileName );

                        // Insert FileDestructor into cache
                        TempFileDestructor tfd = new TempFileDestructor( tempFilePathName );
                        System.Web.Caching.CacheItemRemovedCallback onRemove = new System.Web.Caching.CacheItemRemovedCallback( tfd.RemovedCallback );
                        Page.Cache.Add( tempFileName, tfd, null, DateTime.Now.AddHours( _tmpImageDuration ), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, onRemove );

                        //System.Guid.NewGuid().ToString()
                        //tempFileName = this.ClientID +
                        //	( this.CacheSuffix != null && this.CacheSuffix.Length > 0 ? this.CacheSuffix : "" ) +
                        //	"." + this.ImageFormatFileExtension;

                        //Should we use the cached image ?
                        if ( this.CacheDuration == 0 ||
                            !File.Exists( tempFilePathName ) || // IsImageMap ||
                             File.GetCreationTimeUtc( tempFilePathName ).AddSeconds( this.CacheDuration )
                                    < DateTime.Now.ToUniversalTime() )
                        {
                            //No: so recreate the image file
                            DesignTimeFileStream = new FileStream( tempFilePathName, FileMode.Create,
                                                    FileAccess.ReadWrite, FileShare.ReadWrite );
                            DesignTimeFileStream.SetLength( 0 );
                            DesignTimeFileStream.Seek( 0, SeekOrigin.Begin );
                            //Because of a bug in .NET (deleting a file and creating a file with the same
                            //        name results in the deleted file's CreationTime being returned)
                            // we need to explicitely set the creation time.
                            File.SetCreationTimeUtc( tempFilePathName, DateTime.Now.ToUniversalTime() );
                        }
                    }

                    //Recreate image if needed (caching expired or no caching)
                    if ( DesignTimeFileStream != null )
                    {
                        ImageFormat imageFormat = this.ImageFormat;
                        if ( bDesignMode )
                            imageFormat = ImageFormat.Png;

                        // Draw the graph
                        masterPane = CreateGraph( DesignTimeFileStream, imageFormat, bDesignMode );

                        DesignTimeFileStream.Flush();
                        if ( !bDesignMode ) //Production mode: close files !
                        {
                            DesignTimeFileStream.Close();
                            DesignTimeFileStream = null;
                        }
                    }

                    //The file should exist at this point
                    DateTime tempFileDate = File.GetCreationTimeUtc( tempFilePathName );

                    //Write HTML tag: <IMG width="" height="" src="" alt="">
                    string src;

                    if ( bDesignMode )
                        src = "file://" + DesignTimeFileStream.Name;
                    else
                    {
                        src = this.RenderedImagePath;

                        if ( !src.EndsWith( "/" ) )
                            src += '/';

                        src = Page.ResolveUrl( src );

                        //if ( src.StartsWith( "~/" ) )
                        //	src = src.Substring( 2 );
                        //else if ( src.StartsWith( "~" ) )
                        //	src = src.Substring( 1 );

                        //Add a querystring to defeat browsers cache when our image is recreated
                        src += tempFileName + "?" + tempFileDate.ToString( "yyyyMMddhhmmss" );
                    }

                    output.AddAttribute( HtmlTextWriterAttribute.Width, this.Width.ToString() );
                    output.AddAttribute( HtmlTextWriterAttribute.Height, this.Height.ToString() );
                    output.AddAttribute( HtmlTextWriterAttribute.Src, src );
                    output.AddAttribute( HtmlTextWriterAttribute.Alt, String.Empty );
                    output.AddAttribute( HtmlTextWriterAttribute.Border, "0" ); //CJBL

                    if ( this.IsImageMap && masterPane != null )
                        output.AddAttribute( "usemap", "#" + tempFileName + ".map" );
            //						output.AddAttribute( HtmlTextWriterAttribute.Usemap, "#" + tempFileName + ".map" );
                    output.RenderBeginTag( HtmlTextWriterTag.Img );
                    output.RenderEndTag();

                    if ( this.IsImageMap && masterPane != null )
                    {
                        output.AddAttribute( HtmlTextWriterAttribute.Name, tempFileName + ".map" );
                        output.RenderBeginTag( HtmlTextWriterTag.Map );
                        MakeImageMap( masterPane, output );
                        output.RenderEndTag();
                    }
                }
                catch ( Exception e )
                {
                    output.AddAttribute( HtmlTextWriterAttribute.Width, this.Width.ToString() );
                    output.AddAttribute( HtmlTextWriterAttribute.Height, this.Height.ToString() );
                    output.RenderBeginTag( HtmlTextWriterTag.Span );
                    output.Write( e.ToString() );
                    output.RenderEndTag();
                }

            }
        }
示例#20
0
 public void Insert(string key, object value, System.Web.Caching.CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, System.Web.Caching.CacheItemPriority priority, System.Web.Caching.CacheItemRemovedCallback onRemoveCallback)
 {
 }