コード例 #1
0
ファイル: Image404.cs プロジェクト: hwebz/NTCWeb
        void Pipeline_ImageMissing(System.Web.IHttpModule sender, System.Web.HttpContext context, Configuration.IUrlEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.QueryString["404"]))
            {
                //Resolve the path to virtual or app-relative for
                string path = resolve404Path(e.QueryString["404"]);
                //Resolve to virtual path
                path = Util.PathUtils.ResolveAppRelative(path);

                //Merge commands from the 404 querystring with ones from the original image.
                ResizeSettings imageQuery = new ResizeSettings(e.QueryString);
                imageQuery.Normalize();
                imageQuery.Remove("404"); //Remove the 404 ref

                ResizeSettings i404Query = new ResizeSettings(Util.PathUtils.ParseQueryString(path));
                i404Query.Normalize();
                //Overwrite new with old
                foreach (string key in i404Query.Keys)
                {
                    if (key != null)
                    {
                        imageQuery[key] = i404Query[key];
                    }
                }

                path = PathUtils.AddQueryString(PathUtils.RemoveQueryString(path), PathUtils.BuildQueryString(imageQuery));
                //Redirect
                context.Response.Redirect(path, true);
            }
        }
コード例 #2
0
        public string CreateSignedUrlWithKey(string remoteUrl, string settings, string key)
        {
            NameValueCollection s = new ResizeSettings(settings);

            s[Base64UrlKey] = PathUtils.ToBase64U(remoteUrl);
            s[HmacKey]      = SignDataWithKey(s[Base64UrlKey], key);
            return(remotePrefix + ".jpg.ashx" + PathUtils.BuildQueryString(s));
        }
コード例 #3
0
        public void ApplyRewrittenPath()
        {
            var currentPath = context.Request.FilePath + context.Request.PathInfo;

            if (this.RewrittenVirtualPath != currentPath)
            {
                context.RewritePath(this.RewrittenVirtualPath + PathUtils.BuildQueryString(this.RewrittenQuery)); //Apply the new querystring also, or it would be lost
            }
        }
コード例 #4
0
ファイル: Default.aspx.cs プロジェクト: timgaunt/resizer
        protected void Page_Load(object sender, EventArgs e)
        {
            var psd = Config.Current.Plugins.Get <PsdComposerPlugin>();

            var request = Request;

            // generate png image link
            const string path  = "~/text.psd";
            var          query = new NameValueCollection {
                { "format", "png" }
            };

            var psdcmd = new PsdCommandBuilder(query);

            psdcmd.renderer = "psdplugin";

            foreach (string s in request.QueryString)
            {
                if (!"redraw".Equals(request.QueryString[s], StringComparison.OrdinalIgnoreCase))
                {
                    psdcmd.SetText(s, request.QueryString[s]);
                }
                psdcmd.Redraw(s);
                psdcmd.Show(s);
            }

            Encoding c = Encoding.Default;

            psdcmd.SaveToQuerystring(query);

            img.ImageUrl = ResolveUrl(path) + PathUtils.BuildQueryString(query);


            if (psd != null)
            {
                //get all layers
                var           layers = psd.GetAllLayers(path, query);
                StringBuilder sb     = new StringBuilder();
                foreach (IPsdLayer l in layers)
                {
                    sb.AppendLine(l.Name);
                    sb.AppendLine(l.Text);
                }

                lit.Text = "<pre>" + sb.ToString() + "</pre>";
            }
        }
コード例 #5
0
ファイル: Gradient.cs プロジェクト: timgaunt/resizer
 public string GetCacheKey(bool includeModifiedDate)
 {
     return(VirtualPath + PathUtils.BuildQueryString(query.Keep("width", "height", "w", "h", "maxwidth", "maxheight", "angle", "color1", "color2")));
 }
コード例 #6
0
        public string GenerateRequestCachingKey(DateTime?modifiedData)
        {
            string modified = modifiedData != null && modifiedData != DateTime.MinValue && modifiedData != DateTime.MaxValue ? modifiedData.Value.Ticks.ToString(NumberFormatInfo.InvariantInfo) : "";

            return(string.Format("{0}{1}|{2}", RewrittenVirtualPath, PathUtils.BuildQueryString(RewrittenQuery), modified));
        }
コード例 #7
0
ファイル: ResizeSettings.cs プロジェクト: hwebz/NTCWeb
 /// <summary>
 /// Returns a querystring with all the settings in this class. Querystring keys and values are URL encoded properly.
 /// </summary>
 /// <returns></returns>
 public string ToStringEncoded()
 {
     return(PathUtils.BuildQueryString(this));
 }
コード例 #8
0
ファイル: ResizeSettings.cs プロジェクト: hwebz/NTCWeb
 /// <summary>
 /// Returns a string containing all the settings in the class, in querystring form. Use ToStringEncoded() to get a URL-safe querystring.
 /// This method does not encode commas, spaces, etc.
 /// </summary>
 /// <returns></returns>
 public override string ToString()
 {
     return(PathUtils.BuildQueryString(this, false));
 }
コード例 #9
0
 /// <summary>
 /// Generates a signed domain-relative URL in the form "/app/remote.jpg.ashx?width=200&amp;urlb64=aHnSh3haSh...&amp;hmac=913f3KJGK3hj"
 /// </summary>
 /// <param name="remoteUrl"></param>
 /// <param name="settings"></param>
 /// <returns></returns>
 public string CreateSignedUrl(string remoteUrl, NameValueCollection settings)
 {
     settings[Base64UrlKey] = PathUtils.ToBase64U(remoteUrl);
     settings[HmacKey]      = SignData(settings[Base64UrlKey]);
     return(remotePrefix + ".jpg.ashx" + PathUtils.BuildQueryString(settings));
 }
コード例 #10
0
        /// <summary>
        /// Generates the resized image to disk (if needed), then rewrites the request to that location.
        /// Perform 404 checking before calling this method. Assumes file exists.
        /// Called during PostAuthorizeRequest
        /// </summary>
        /// <param name="context"></param>
        /// <param name="virtualPath"></param>
        /// <param name="queryString"></param>
        /// <param name="vf"></param>
        protected virtual void HandleRequest(HttpContext context, string virtualPath, NameValueCollection queryString, IVirtualFile vf)
        {
            Stopwatch s = new Stopwatch();

            s.Start();


            ResizeSettings settings = new ResizeSettings(queryString);

            bool isCaching    = settings.Cache == ServerCacheMode.Always;
            bool isProcessing = settings.Process == ProcessWhen.Always;

            //By default, we process it if is both (a) a recognized image extension, and (b) has a resizing directive (not just 'cache').
            if (settings.Process == ProcessWhen.Default)
            {
                //Check for resize directive by removing ('non-resizing' items from the current querystring)
                NameValueCollection copy = new NameValueCollection(queryString);
                copy.Remove("cache"); copy.Remove("process"); copy.Remove("useresizingpipeline"); copy.Remove("404");
                copy.Remove("404.filterMode"); copy.Remove("404.except");
                //If the 'copy' still has directives, and it's an image request, then let's process it.
                isProcessing = conf.IsAcceptedImageType(virtualPath) && conf.HasPipelineDirective(copy);
            }

            //By default, we only cache it if we're processing it.
            if (settings.Cache == ServerCacheMode.Default && isProcessing)
            {
                isCaching = true;
            }

            //Resolve the 'cache' setting to 'no' unless we want it cache.
            if (!isCaching)
            {
                settings.Cache = ServerCacheMode.No;
            }


            //If we are neither processing nor caching, don't do anything more with the request
            if (!isProcessing && !isCaching)
            {
                return;
            }
            context.Items[conf.ResponseArgsKey] = ""; //We are handling the requests

            //Communicate to the MVC plugin this request should not be affected by the UrlRoutingModule.
            context.Items[conf.StopRoutingKey] = true;

            //Find out if we have a modified date that we can work with
            bool     hasModifiedDate = (vf == null) || vf is IVirtualFileWithModifiedDate;
            DateTime modDate         = DateTime.MinValue;

            if (hasModifiedDate && vf != null)
            {
                modDate = ((IVirtualFileWithModifiedDate)vf).ModifiedDateUTC;
                if (modDate == DateTime.MinValue || modDate == DateTime.MaxValue)
                {
                    hasModifiedDate = false; //Skip modified date checking if the file has no modified date
                }
            }


            IEncoder guessedEncoder = null;

            //Only use an encoder to determine extension/mime-type when it's an image extension or when we've set process = always.
            if (isProcessing)
            {
                guessedEncoder = conf.GetImageBuilder().EncoderProvider.GetEncoder(settings, virtualPath);
                if (guessedEncoder == null)
                {
                    throw new ImageProcessingException("Image Resizer: No image encoder was found for the request.");
                }
            }

            //Determine the file extenson for the caching system to use if we aren't processing the image
            //Use the exsiting one if is an image extension. If not, use "unknown".
            // We don't want to suggest writing .exe or .aspx files to the cache!
            string fallbackExtension = PathUtils.GetFullExtension(virtualPath).TrimStart('.');

            if (!conf.IsAcceptedImageType(virtualPath))
            {
                fallbackExtension = "unknown";
            }

            //Determine the mime-type if we aren't processing the image.
            string fallbackContentType = "application/octet-stream";

            //Support jpeg, png, gif, bmp, tiff mime-types. Otherwise use "application/octet-stream".
            //We can't set it to null - it will default to text/html
            System.Drawing.Imaging.ImageFormat recognizedExtension = DefaultEncoder.GetImageFormatFromExtension(fallbackExtension);
            if (recognizedExtension != null)
            {
                fallbackContentType = DefaultEncoder.GetContentTypeFromImageFormat(recognizedExtension);
            }


            //Build CacheEventArgs
            ResponseArgs e = new ResponseArgs();

            e.RequestKey                  = virtualPath + PathUtils.BuildQueryString(queryString);
            e.RewrittenQuerystring        = settings;
            e.ResponseHeaders.ContentType = isProcessing ? guessedEncoder.MimeType : fallbackContentType;
            e.SuggestedExtension          = isProcessing ? guessedEncoder.Extension : fallbackExtension;
            e.HasModifiedDate             = hasModifiedDate;
            //Add delegate for retrieving the modified date of the source file.
            e.GetModifiedDateUTC = new ModifiedDateDelegate(delegate() {
                if (vf == null)
                {
                    return(System.IO.File.GetLastWriteTimeUtc(HostingEnvironment.MapPath(virtualPath)));
                }
                else if (hasModifiedDate)
                {
                    return(modDate);
                }
                else
                {
                    return(DateTime.MinValue); //Won't be called, no modified date available.
                }
            });

            //A delegate for accessing the source file
            e.GetSourceImage = new GetSourceImageDelegate(delegate() {
                return((vf != null) ? vf.Open() : File.Open(HostingEnvironment.MapPath(virtualPath), FileMode.Open, FileAccess.Read, FileShare.Read));
            });

            //Add delegate for writing the data stream
            e.ResizeImageToStream = new ResizeImageDelegate(delegate(System.IO.Stream stream) {
                //This runs on a cache miss or cache invalid. This delegate is preventing from running in more
                //than one thread at a time for the specified cache key
                try {
                    if (!isProcessing)
                    {
                        //Just duplicate the data
                        using (Stream source = e.GetSourceImage())
                            StreamExtensions.CopyToStream(source, stream); //4KiB buffer
                    }
                    else
                    {
                        //Process the image
                        if (vf != null)
                        {
                            conf.GetImageBuilder().Build(vf, stream, settings);
                        }
                        else
                        {
                            conf.GetImageBuilder().Build(HostingEnvironment.MapPath(virtualPath), stream, settings); //Use a physical path to bypass virtual file system
                        }
                    }

                    //Catch not found exceptions
                } catch (System.IO.FileNotFoundException notFound) {
                    //This will be called later, if at all.
                    FileMissing(context, virtualPath, queryString);
                    throw new ImageMissingException("The specified resource could not be located", "File not found", notFound);
                } catch (System.IO.DirectoryNotFoundException notFound) {
                    FileMissing(context, virtualPath, queryString);
                    throw new ImageMissingException("The specified resource could not be located", "File not found", notFound);
                }
            });


            context.Items[conf.ResponseArgsKey] = e; //store in context items

            //Fire events (for client-side caching plugins)
            conf.FirePreHandleImage(this, context, e);

            //Pass the rest of the work off to the caching module. It will handle rewriting/redirecting and everything.
            //We handle request headers based on what is found in context.Items
            ICache cache = conf.GetCacheProvider().GetCachingSystem(context, e);

            //Verify we have a caching system
            if (cache == null)
            {
                throw new ImageProcessingException("Image Resizer: No caching plugin was found for the request");
            }

            cache.Process(context, e);



            s.Stop();
            context.Items["ResizingTime"] = s.ElapsedMilliseconds;
        }
コード例 #11
0
ファイル: Encrypted.cs プロジェクト: zhaoyingju/resizer
 public string EncryptPathAndQuery(string virtualPath, NameValueCollection query)
 {
     return(EncryptPathAndQuery(virtualPath + PathUtils.BuildQueryString(query)));
 }
コード例 #12
0
ファイル: Gradient.cs プロジェクト: zhaoyingju/resizer
 public string GetCacheKey(bool includeModifiedDate)
 {
     return(VirtualPath + PathUtils.BuildQueryString(NameValueCollectionExtensions.Keep(query, "width", "height", "w", "h", "maxwidth", "maxheight", "angle", "color1", "color2")));
 }
コード例 #13
0
ファイル: Image404.cs プロジェクト: stukalin/ImageResizer
        void Pipeline_ImageMissing(System.Web.IHttpModule sender, System.Web.HttpContext context, Configuration.IUrlEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.QueryString["404"]))
            {
                //Resolve the path to virtual or app-relative for
                string path = resolve404Path(e.QueryString["404"]);
                //Resolve to virtual path
                path = Util.PathUtils.ResolveAppRelative(path);

                // Merge commands from the 404 querystring with ones from the
                // original image.  We start by sanitizing the querystring from
                // the image.
                ResizeSettings imageQuery = new ResizeSettings(e.QueryString);
                imageQuery.Normalize();

                // Use the configured settings by default.
                var filterMode = this.filterMode;
                var except     = this.except;

                // To support querystring-specifiable filter mode and exceptions,
                // uncomment the if block below.
                ////// If the imageQuery includes specific 404 command-filtering,
                ////// (*either* of the values), use those instead of the
                ////// configured defaults.
                ////if (!string.IsNullOrEmpty(e.QueryString["404.filterMode"]) ||
                ////    !string.IsNullOrEmpty(e.QueryString["404.except"]))
                ////{
                ////    filterMode = NameValueCollectionExtensions.Get(e.QueryString, "404.filterMode", FilterMode.ExcludeUnknownCommands);
                ////    except = MatcherCollection.Parse(e.QueryString["404.except"]);
                ////}

                // remove all of the commands we're supposed to remove... we
                // clone the list of keys so that we're not modifying the collection
                // while we enumerate it.
                var shouldRemove = CreateRemovalMatcher(filterMode, except);
                var names        = new List <string>(imageQuery.AllKeys);

                foreach (var name in names)
                {
                    if (shouldRemove(name, imageQuery[name]))
                    {
                        imageQuery.Remove(name);
                    }
                }

                // Always remove the '404', '404.filterMode', and '404.except' settings.
                imageQuery.Remove("404");
                imageQuery.Remove("404.filterMode");
                imageQuery.Remove("404.except");

                ResizeSettings i404Query = new ResizeSettings(Util.PathUtils.ParseQueryString(path));
                i404Query.Normalize();
                //Overwrite new with old
                foreach (string key in i404Query.Keys)
                {
                    if (key != null)
                    {
                        imageQuery[key] = i404Query[key];
                    }
                }

                path = PathUtils.AddQueryString(PathUtils.RemoveQueryString(path), PathUtils.BuildQueryString(imageQuery));
                //Redirect
                context.Response.Redirect(path, true);
            }
        }
コード例 #14
0
ファイル: Instructions.cs プロジェクト: timgaunt/resizer
 /// <summary>
 /// Returns a URL-safe querystring containing the instruction set
 /// </summary>
 /// <returns></returns>
 public string ToQueryString()
 {
     return(PathUtils.BuildQueryString(this, true));
 }
コード例 #15
0
ファイル: MemCachedFile.cs プロジェクト: zhaoyingju/resizer
 private static string getVirtualCacheKey(string virtualPath, NameValueCollection query)
 {
     return("MemCachedVirtualFile:" + virtualPath.ToLowerInvariant() + PathUtils.BuildQueryString(query));
 }
コード例 #16
0
ファイル: MemCachedFile.cs プロジェクト: zhaoyingju/resizer
        public static MemCachedFile GetCachedVirtualFile(string path, IVirtualImageProvider provider, NameValueCollection queryString)
        {
            string key = provider != null?getVirtualCacheKey(path, queryString) : getCacheKey(path);

            MemCachedFile file = null;

            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Cache[key] != null)
                {
                    file = (MemCachedFile)HttpContext.Current.Cache[key];
                }
                else
                {
                    IVirtualFile vfile = provider != null?provider.GetFile(path, queryString) : null;

                    if (vfile == null)
                    {
                        throw new FileNotFoundException("The specified virtual file could not be found: \"" + path + "\" Associated querystring: \"" + PathUtils.BuildQueryString(queryString) + "\".");
                    }
                    file = vfile != null ? new MemCachedFile(vfile) : new MemCachedFile(path);
                    if (provider == null)
                    {
                        HttpContext.Current.Cache.Insert(key, file, new CacheDependency(path));
                    }
                    else
                    {
                        HttpContext.Current.Cache.Insert(key, file);
                    }
                }
            }
            else
            {
                //Has no invalidation, but this is only used for benchmarks. Only runs when there is no http session.
                lock (_fallbackCache){
                    if (_fallbackCache.ContainsKey(key))
                    {
                        file = _fallbackCache[key];
                    }
                    else
                    {
                        file = provider != null ? new MemCachedFile(provider.GetFile(path, queryString)) : new MemCachedFile(path);
                        _fallbackCache[key] = file;
                    }
                }
            }
            return(file);
        }