Example #1
0
        public void Process(System.Web.HttpContext current, IResponseArgs e)
        {
            //Use alternate cache key if provided
            string key = e.RequestKey + (e.HasModifiedDate ? e.GetModifiedDateUTC().Ticks.ToString() : "");

            //If cached, serve it.
            var c = cache.Get(key);

            if (c != null)
            {
                Serve(current, e, c);
                return;
            }
            //If not, let's cache it.
            locks.TryExecute(key, 3000, delegate() {
                c = cache.Get(key);
                if (c == null)
                {
                    using (var data = new MemoryStream()){
                        e.ResizeImageToStream(data);//Very long-running call
                        c = new MemCacheResult(StreamExtensions.CopyToBytes(data, true));
                    }
                    cache.Set(key, c);//Save to cache (may trigger cleanup)
                }
                Serve(current, e, c);
                return;
            });
        }
Example #2
0
        public void Process(System.Web.HttpContext current, IResponseArgs e)
        {
            //Use alternate cache key if provided
            string key = e.RequestKey + (e.HasModifiedDate ? e.GetModifiedDateUTC().Ticks.ToString() : "");

            //If cached, serve it.
            var c = cache.Get(key);
            if (c != null) {
                Serve(current, e, c);
                return;
            }
            //If not, let's cache it.
            locks.TryExecute(key, 3000, delegate() {
                c = cache.Get(key);
                if (c == null) {
                    using (var data = new MemoryStream()){
                        e.ResizeImageToStream(data);//Very long-running call
                        c = new MemCacheResult(StreamExtensions.CopyToBytes(data, true));
                    }
                    cache.Set(key, c);//Save to cache (may trigger cleanup)
                }
                Serve(current, e, c);
                return;
            });
        }
Example #3
0
        public CacheResult Process(IResponseArgs e)
        {
            //Query for the modified date of the source file. If the source file changes on us during the write,
            //we (may) end up saving the newer version in the cache properly, but with an older modified date.
            //This will not cause any actual problems from a behavioral standpoint - the next request for the
            //image will cause the file to be overwritten and the modified date updated.
            DateTime modDate = e.HasModifiedDate ? e.GetModifiedDateUTC() : DateTime.MinValue;

            //Verify web.config exists in the cache folder.
            writer.CheckWebConfigEvery5();

            //Cache the data to disk and return a path.
            CacheResult r = cache.GetCachedFile(e.RequestKey, e.SuggestedExtension, e.ResizeImageToStream, modDate, CacheAccessTimeout, AsyncWrites);

            //Fail
            if (r.Result == CacheQueryResult.Failed)
            {
                throw new ImageResizer.ImageProcessingException("Failed to acquire a lock on file \"" + r.PhysicalPath + "\" within " + CacheAccessTimeout + "ms. Caching failed.");
            }

            if (r.Result == CacheQueryResult.Hit && cleaner != null)
            {
                cleaner.UsedFile(r.RelativePath, r.PhysicalPath);
            }

            return(r);
        }
Example #4
0
        public void Process(System.Web.HttpContext current, IResponseArgs e)
        {
            var modDate = e.HasModifiedDate ? e.GetModifiedDateUTC() : DateTime.MinValue;
            var key     = e.RequestKey + "|" + modDate.Ticks.ToString(NumberFormatInfo.InvariantInfo);

            CacheEntry entry;

            byte[] data;

            //Ensure cache is loaded
            if (!loaded)
            {
                Load();
            }

            if (!TryGetData(key, out data, out entry))
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();
                //Cache miss - process request, outside of lock
                MemoryStream ms = new MemoryStream(4096);
                e.ResizeImageToStream(ms);
                data = StreamExtensions.CopyToBytes(ms, true);
                sw.Stop();
                //Save to cache
                entry = PutData(key, data, sw.ElapsedMilliseconds);
            }

            ((ResponseArgs)e).ResizeImageToStream = delegate(Stream s) {
                s.Write(data, 0, data.Length);
            };

            current.RemapHandler(new NoCacheHandler(e));

            if (cache.changes_since_cleanse > ChangeThreshold)
            {
                CleanseAndFlush();
            }
            else if (cache.changes_since_cleanse > 0 && DateTime.UtcNow.Subtract(lastFlush) > new TimeSpan(0, 0, 30))
            {
                Flush();
            }
        }
Example #5
0
 public static string CalcualteETag(IResponseArgs e)
 {
     return (e.RequestKey + (e.HasModifiedDate ? e.GetModifiedDateUTC().Ticks.ToString() : "")).GetHashCode().ToString("x");
 }
Example #6
0
 public static string CalcualteETag(IResponseArgs e)
 {
     return((e.RequestKey + (e.HasModifiedDate ? e.GetModifiedDateUTC().Ticks.ToString() : "")).GetHashCode().ToString("x"));
 }
Example #7
0
        public CacheResult Process(IResponseArgs e)
        {
            //Query for the modified date of the source file. If the source file changes on us during the write,
            //we (may) end up saving the newer version in the cache properly, but with an older modified date.
            //This will not cause any actual problems from a behavioral standpoint - the next request for the
            //image will cause the file to be overwritten and the modified date updated.
            DateTime modDate = e.HasModifiedDate ? e.GetModifiedDateUTC() : DateTime.MinValue;

            //Verify web.config exists in the cache folder.
            writer.CheckWebConfigEvery5();

            //Cache the data to disk and return a path.
            CacheResult r = cache.GetCachedFile(e.RequestKey, e.SuggestedExtension, e.ResizeImageToStream, modDate, CacheAccessTimeout,AsyncWrites);

            //Fail
            if (r.Result == CacheQueryResult.Failed)
                throw new ImageResizer.ImageProcessingException("Failed to acquire a lock on file \"" + r.PhysicalPath + "\" within " + CacheAccessTimeout + "ms. Caching failed.");

            if (r.Result == CacheQueryResult.Hit && cleaner != null)
                cleaner.UsedFile(r.RelativePath, r.PhysicalPath);

            return r;
        }
Example #8
0
        public void Process(HttpContext current, IResponseArgs e)
        {
            var modifiedTime = e.HasModifiedDate ? e.GetModifiedDateUTC() : DateTime.MinValue;
            var hash         = DateTime.MinValue.Equals(modifiedTime) ? this.GetHash(e.RequestKey) : this.GetHash(string.Format("{0}|={1}", e.RequestKey, modifiedTime));

            var subDir = string.Format("{0}{1}{2}", this.PhysicalCacheDir, Path.DirectorySeparatorChar, this.GetSubDir(hash));

            if (!Directory.Exists(subDir))
            {
                Directory.CreateDirectory(subDir);
            }

            var physicalPath = string.Format("{0}{1}{2}.{3}", subDir, Path.DirectorySeparatorChar, this.GetHashString(hash), e.SuggestedExtension);

            Stream stream;

            if (File.Exists(physicalPath))
            {
                var data = File.ReadAllBytes(physicalPath);
                stream = new MemoryStream(data);
                ((ResponseArgs)e).ResizeImageToStream = s => ((MemoryStream)stream).WriteTo(s);
                current.RemapHandler(new NoCacheHandler(e));
                if (logger.IsDebugEnabled)
                {
                    logger.Debug("Get image from cached file: " + physicalPath);
                }
            }
            else
            {
                var memoryStream = new MemoryStream(4096);
                e.ResizeImageToStream(memoryStream);
                memoryStream.Position = 0;

                var imageWriterKey = ImageWriterManager.GetImageWriterKey(physicalPath, modifiedTime);
                var imageWriter    = this.imageWriterManager.Get(imageWriterKey);

                if (imageWriter == null)
                {
                    imageWriter = new ImageWriter(physicalPath, memoryStream, modifiedTime);
                    this.imageWriterManager.Queue(imageWriter, delegate(ImageWriter job)
                    {
                        try
                        {
                            if (logger.IsDebugEnabled)
                            {
                                logger.Debug("Begin writing image to file: " + job.PhysicalPath);
                            }
                            using (
                                var fileStream = new FileStream(job.PhysicalPath, FileMode.Create, FileAccess.Write, FileShare.None))
                            {
                                job.GetReadonlyStream().WriteTo(fileStream);
                                fileStream.Flush();
                            }
                            if (logger.IsDebugEnabled)
                            {
                                logger.Debug("End writing image to file: " + job.PhysicalPath);
                            }
                        }
                        catch (Exception ex)
                        {
                            if (logger.IsErrorEnabled)
                            {
                                logger.Error(ex);
                            }
                        }
                        finally
                        {
                            this.imageWriterManager.Remove(imageWriterKey);
                        }
                    });
                }

                stream = imageWriter.GetReadonlyStream();
            }

            if (stream != null)
            {
                ((ResponseArgs)e).ResizeImageToStream = s => ((MemoryStream)stream).WriteTo(s);
                current.RemapHandler(new NoCacheHandler(e));
            }
        }
Example #9
0
        public void Process(System.Web.HttpContext current, IResponseArgs e)
        {
            var modDate = e.HasModifiedDate ? e.GetModifiedDateUTC() : DateTime.MinValue;
            var key = e.RequestKey +  "|" + modDate.Ticks.ToString(NumberFormatInfo.InvariantInfo);

            CacheEntry entry;
            byte[] data;

            //Ensure cache is loaded
            if (!loaded) Load();

            if (!TryGetData(key ,out data, out entry)){
                Stopwatch sw = new Stopwatch();
                sw.Start();
                //Cache miss - process request, outside of lock
                MemoryStream ms = new MemoryStream(4096);
                e.ResizeImageToStream(ms);
                data = StreamExtensions.CopyToBytes(ms,true);
                sw.Stop();
                //Save to cache
                entry = PutData(key,data, sw.ElapsedMilliseconds);
            }

            ((ResponseArgs)e).ResizeImageToStream = delegate(Stream s) {
                s.Write(data,0,data.Length);
            };

            current.RemapHandler(new NoCacheHandler(e));

            if (cache.changes_since_cleanse > ChangeThreshold) CleanseAndFlush();
            else if (cache.changes_since_cleanse > 0 && DateTime.UtcNow.Subtract(lastFlush) > new TimeSpan(0, 0, 30)) {
                Flush();
            }
        }