/// <summary>
        /// Sets the output cache parameters and also the client side caching parameters
        /// </summary>
        /// <param name="context"></param>
        private void SetCaching(HttpContext context, string fileName)
        {
            //This ensures OutputCaching is set for this handler and also controls
            //client side caching on the browser side. Default is 10 days.
            TimeSpan        duration = TimeSpan.FromDays(10);
            HttpCachePolicy cache    = context.Response.Cache;

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetExpires(DateTime.Now.Add(duration));
            cache.SetMaxAge(duration);
            cache.SetValidUntilExpires(true);
            cache.SetLastModified(DateTime.Now);
            cache.SetETag(Guid.NewGuid().ToString());
            //set server OutputCache to vary by our params
            cache.VaryByParams["t"] = true;
            cache.VaryByParams["s"] = true;
            //don't allow varying by wildcard
            cache.SetOmitVaryStar(true);
            //ensure client browser maintains strict caching rules
            cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
            //This is the only way to set the max-age cachability header in ASP.Net!
            FieldInfo maxAgeField = cache.GetType().GetField("_maxAge", BindingFlags.Instance | BindingFlags.NonPublic);

            maxAgeField.SetValue(cache, duration);

            //make this output cache dependent on the file if there is one.
            if (!string.IsNullOrEmpty(fileName))
            {
                context.Response.AddFileDependency(fileName);
            }
        }
示例#2
0
        private static void SetCache(string path)
        {
            HttpCachePolicy cache   = HttpContext.Current.Response.Cache;
            TimeSpan        expires = TimeSpan.FromDays(14);

            cache.SetExpires(DateTime.Now.Add(expires));
            cache.SetMaxAge(expires);
            cache.SetLastModified(File.GetLastWriteTime(path));
        }
示例#3
0
 private static void SetCache(HttpCachePolicy cache)
 {
     cache.SetCacheability(HttpCacheability.Public);
     cache.VaryByParams[_paramV]    = true;
     cache.VaryByParams[_paramFile] = true;
     cache.SetOmitVaryStar(true);
     cache.SetValidUntilExpires(true);
     cache.SetExpires(DateTime.Now.AddYears(2));
     cache.SetLastModified(DateTime.ParseExact(AppConstants.BuildDate,
                                               _dateFormat, CultureInfo.GetCultureInfo(_usCulture).DateTimeFormat));
 }
示例#4
0
        private static void OutputCacheResponse(HttpContext context, DateTime lastModified)
        {
            HttpCachePolicy cachePolicy = context.Response.Cache;

            cachePolicy.SetCacheability(HttpCacheability.Public);
            cachePolicy.VaryByParams["*"] = true;
            cachePolicy.SetOmitVaryStar(true);
            cachePolicy.SetExpires(DateTime.Now + TimeSpan.FromDays(365));
            cachePolicy.SetValidUntilExpires(true);
            cachePolicy.SetLastModified(lastModified);
        }
示例#5
0
        private void SetCache(HttpCachePolicy cache, DateTime lastModified)
        {
            // Use ASP.Net output cache.

            cache.SetExpires(DateTime.UtcNow.Add(_imageProviderPath.Expiration));
            cache.SetValidUntilExpires(true);
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            cache.SetCacheability(HttpCacheability.Public);
            cache.SetMaxAge(_imageProviderPath.Expiration);
            cache.SetLastModified(lastModified.ToUniversalTime());
            cache.SetETagFromFileDependencies();
        }
示例#6
0
        private void SetResponseCache(HttpContext context)
        {
            HttpCachePolicy cache = context.Response.Cache;

            cache.SetLastModified(new DateTime(ResourceManager.GetAssemblyTime(typeof(ResourceManager).Assembly)));
            cache.SetOmitVaryStar(true);
            cache.SetVaryByCustom("v");
            cache.SetExpires(DateTime.UtcNow.AddYears(1));
            cache.SetMaxAge(TimeSpan.FromDays(365));
            cache.SetValidUntilExpires(true);
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            cache.SetCacheability(HttpCacheability.Public);
        }
示例#7
0
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request      = context.Request;
            string      physicalPath = request.PhysicalPath;

            if (File.Exists(physicalPath))
            {
                string       subfix        = Path.GetExtension(physicalPath);
                bool         isOutputCache = false;
                HttpResponse response      = context.Response;
                if (".png".Equals(subfix, StringComparison.CurrentCultureIgnoreCase))
                {
                    isOutputCache        = true;
                    response.ContentType = "image/x-png";
                }
                else if (".jpg".Equals(subfix, StringComparison.CurrentCultureIgnoreCase))
                {
                    isOutputCache        = true;
                    response.ContentType = "image/pjpeg";
                }
                if (isOutputCache)
                {
                    const int DAYS            = 30;
                    string    ifModifiedSince = request.Headers["If-Modified-Since"];
                    if (!string.IsNullOrEmpty(ifModifiedSince) &&
                        TimeSpan.FromTicks(DateTime.Now.Ticks - DateTime.Parse(ifModifiedSince).Ticks).Days < DAYS)
                    {
                        response.StatusCode        = (int)System.Net.HttpStatusCode.NotModified;
                        response.StatusDescription = "Not Modified";
                        response.End();
                        return;
                    }
                    else
                    {
                        HttpCachePolicy cache = response.Cache;
                        cache.SetLastModifiedFromFileDependencies();
                        cache.SetETagFromFileDependencies();
                        cache.SetCacheability(HttpCacheability.Public);
                        cache.SetExpires(DateTime.Now.AddDays(DAYS));
                        TimeSpan timeSpan = TimeSpan.FromDays(DAYS);
                        cache.SetMaxAge(timeSpan);
                        cache.SetProxyMaxAge(timeSpan);
                        cache.SetLastModified(context.Timestamp);
                        cache.SetValidUntilExpires(true);
                        cache.SetSlidingExpiration(true);
                    }
                }
                response.WriteFile(physicalPath);
                response.End();
            }
        }
示例#8
0
        private void SetResponseCache(HttpContext context)
        {
            HttpCachePolicy cache = context.Response.Cache;

            cache.SetLastModified(DateTime.Now.ToUniversalTime().AddSeconds(-1.0));
            cache.SetOmitVaryStar(true);
            cache.SetVaryByCustom("v");
            cache.SetExpires(DateTime.UtcNow.AddDays(365.0));
            cache.SetMaxAge(TimeSpan.FromDays(365.0));
            cache.SetValidUntilExpires(true);
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            cache.SetCacheability(HttpCacheability.Public);
            cache.SetLastModifiedFromFileDependencies();
        }
        /// <summary>
        /// 缓存
        /// </summary>
        /// <param name="instance">HttpContext扩展</param>
        /// <param name="duration">时间差</param>
        public static void Cache(this HttpContext instance, TimeSpan duration)
        {
            instance.CheckOnNull("instance");
            HttpCachePolicy cache = instance.Response.Cache;

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetOmitVaryStar(true);
            cache.SetExpires(instance.Timestamp.Add(duration));
            cache.SetMaxAge(duration);
            cache.SetValidUntilExpires(true);
            cache.SetLastModified(instance.Timestamp);
            cache.SetLastModifiedFromFileDependencies();
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        }
示例#10
0
 internal static void SetCacheLastModified(HttpContext context, DateTime lastModifiedTime, bool neverExpires)
 {
     if (lastModifiedTime.ToUniversalTime() < DateTime.UtcNow)
     {
         HttpCachePolicy cache = context.Response.Cache;
         cache.SetCacheability(HttpCacheability.Public);
         cache.SetLastModified(lastModifiedTime);
         if (neverExpires)
         {
             cache.SetExpires(DateTime.Now.AddYears(1));
             cache.SetValidUntilExpires(true);
         }
     }
 }
示例#11
0
        private static void SetCache(bool suppressLastModified = false)
        {
            HttpContext.Current.Response.AddHeader("Age", ((int)(PortalContext.Current.LastModified - DateTime.Now).TotalSeconds).ToString(CultureInfo.InvariantCulture));
            HttpCachePolicy cache   = HttpContext.Current.Response.Cache;
            TimeSpan        expires = TimeSpan.FromDays(14);

            cache.SetExpires(DateTime.UtcNow.Add(expires));
            cache.SetMaxAge(expires);
            DateTime dt       = PortalContext.Current.LastModified;
            string   eTagDate = "\"" + dt.ToString("s", DateTimeFormatInfo.InvariantInfo) + "\"";

            HttpContext.Current.Response.AddHeader("ETag", eTagDate);

            if (!suppressLastModified)
            {
                cache.SetLastModified(PortalContext.Current.LastModified);
            }
        }
示例#12
0
        internal static string GetClientProxyScript(HttpContext context)
        {
            WebServiceData webServiceData   = WebServiceData.GetWebServiceData(context, context.Request.FilePath);
            DateTime       lastModifiedDate = GetAssemblyModifiedTime(webServiceData.TypeData.Type.Assembly);

            // If the browser sent this header, we can check if we need to resend
            string modifiedSince = context.Request.Headers["If-Modified-Since"];

            if (modifiedSince != null)
            {
                DateTime header;
                if (DateTime.TryParse(modifiedSince, out header))
                {
                    // We are done if the assembly hasn't been modified
                    if (header >= lastModifiedDate)
                    {
                        context.Response.StatusCode = 304;
                        return(null);
                    }
                }
            }
            bool debug = RestHandlerFactory.IsClientProxyDebugRequest(context.Request.PathInfo);

            // Only cache for release proxy script (/js)
            if (!debug)
            {
                // Only cache if we get a reasonable last modified date
                if (lastModifiedDate.ToUniversalTime() < DateTime.UtcNow)
                {
                    // Cache the resource so we don't keep processing the same requests
                    HttpCachePolicy cachePolicy = context.Response.Cache;
                    cachePolicy.SetCacheability(HttpCacheability.Public);
                    cachePolicy.SetLastModified(lastModifiedDate);
                    // expires is necessary so that the browser at least does an If-Modified-Since request on every request.
                    // without that, the browser wouldn't request a new proxy until the user hits refresh.
                    // Use one year ago to reasonably ensure "past" interpretation
                    cachePolicy.SetExpires(lastModifiedDate.AddYears(-1));
                }
            }

            WebServiceClientProxyGenerator proxyGenerator = new WebServiceClientProxyGenerator(context.Request.FilePath, debug);

            return(proxyGenerator.GetClientProxyScript(webServiceData));
        }
示例#13
0
        /// <summary>
        /// 设置浏览器缓存
        /// </summary>
        public void SetResponseCache()
        {
            HttpCachePolicy cache        = HttpCurrentContext.Response.Cache;
            DateTime        modifiedDate = new DateTime(AssemblyManager.GetAssemblyTime(typeof(ResourceManager).Assembly).Ticks).ToUniversalTime();
            DateTime        nowDate      = DateTime.Now.ToUniversalTime().AddSeconds(-1);

            if (modifiedDate > nowDate)
            {
                modifiedDate = nowDate;
            }
            cache.SetLastModified(modifiedDate);
            cache.SetOmitVaryStar(true);
            cache.SetVaryByCustom("v");
            cache.SetExpires(DateTime.UtcNow.AddDays(365));
            cache.SetMaxAge(TimeSpan.FromDays(365));
            cache.SetValidUntilExpires(true);
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            cache.SetCacheability(HttpCacheability.Public);
            cache.SetLastModifiedFromFileDependencies();
        }
示例#14
0
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            context.Response.Clear();
            Stream manifestResourceStream = null;

            try
            {
                string str = context.Request.QueryString["d"];
                if (string.IsNullOrEmpty(str))
                {
                    throw new HttpException(0x194, System.Web.SR.GetString("AssemblyResourceLoader_InvalidRequest"));
                }
                string str2  = Page.DecryptString(str);
                int    index = str2.IndexOf('|');
                string str3  = str2.Substring(0, index);
                if (string.IsNullOrEmpty(str3))
                {
                    throw new HttpException(0x194, System.Web.SR.GetString("AssemblyResourceLoader_AssemblyNotFound", new object[] { str3 }));
                }
                string webResource = str2.Substring(index + 1);
                if (string.IsNullOrEmpty(webResource))
                {
                    throw new HttpException(0x194, System.Web.SR.GetString("AssemblyResourceLoader_ResourceNotFound", new object[] { webResource }));
                }
                char ch = str3[0];
                str3 = str3.Substring(1);
                Assembly assembly = null;
                switch (ch)
                {
                case 's':
                    assembly = typeof(AssemblyResourceLoader).Assembly;
                    break;

                case 'p':
                    assembly = Assembly.Load(str3);
                    break;

                case 'f':
                {
                    string[] strArray = str3.Split(new char[] { ',' });
                    if (strArray.Length != 4)
                    {
                        throw new HttpException(0x194, System.Web.SR.GetString("AssemblyResourceLoader_InvalidRequest"));
                    }
                    AssemblyName assemblyRef = new AssemblyName {
                        Name    = strArray[0],
                        Version = new Version(strArray[1])
                    };
                    string name = strArray[2];
                    if (name.Length > 0)
                    {
                        assemblyRef.CultureInfo = new CultureInfo(name);
                    }
                    else
                    {
                        assemblyRef.CultureInfo = CultureInfo.InvariantCulture;
                    }
                    string str6           = strArray[3];
                    byte[] publicKeyToken = new byte[str6.Length / 2];
                    for (int i = 0; i < publicKeyToken.Length; i++)
                    {
                        publicKeyToken[i] = byte.Parse(str6.Substring(i * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
                    }
                    assemblyRef.SetPublicKeyToken(publicKeyToken);
                    assembly = Assembly.Load(assemblyRef);
                    break;
                }

                default:
                    throw new HttpException(0x194, System.Web.SR.GetString("AssemblyResourceLoader_InvalidRequest"));
                }
                if (assembly == null)
                {
                    throw new HttpException(0x194, System.Web.SR.GetString("AssemblyResourceLoader_InvalidRequest"));
                }
                bool    third   = false;
                bool    first   = false;
                string  second  = string.Empty;
                int     num3    = HashCodeCombiner.CombineHashCodes(assembly.GetHashCode(), webResource.GetHashCode());
                Triplet triplet = (Triplet)_webResourceCache[num3];
                if (triplet != null)
                {
                    first  = (bool)triplet.First;
                    second = (string)triplet.Second;
                    third  = (bool)triplet.Third;
                }
                else
                {
                    WebResourceAttribute attribute = FindWebResourceAttribute(assembly, webResource);
                    if (attribute != null)
                    {
                        webResource = attribute.WebResource;
                        first       = true;
                        second      = attribute.ContentType;
                        third       = attribute.PerformSubstitution;
                    }
                    try
                    {
                        if (first)
                        {
                            first = false;
                            manifestResourceStream = assembly.GetManifestResourceStream(webResource);
                            first = manifestResourceStream != null;
                        }
                    }
                    finally
                    {
                        Triplet triplet2 = new Triplet {
                            First  = first,
                            Second = second,
                            Third  = third
                        };
                        _webResourceCache[num3] = triplet2;
                    }
                }
                if (first)
                {
                    HttpCachePolicy cache = context.Response.Cache;
                    cache.SetCacheability(HttpCacheability.Public);
                    cache.VaryByParams["d"] = true;
                    cache.SetOmitVaryStar(true);
                    cache.SetExpires(DateTime.Now + TimeSpan.FromDays(365.0));
                    cache.SetValidUntilExpires(true);
                    Pair assemblyInfo = GetAssemblyInfo(assembly);
                    cache.SetLastModified(new DateTime((long)assemblyInfo.Second));
                    StreamReader reader = null;
                    try
                    {
                        if (manifestResourceStream == null)
                        {
                            manifestResourceStream = assembly.GetManifestResourceStream(webResource);
                        }
                        if (manifestResourceStream != null)
                        {
                            context.Response.ContentType = second;
                            if (third)
                            {
                                reader = new StreamReader(manifestResourceStream, true);
                                string          input      = reader.ReadToEnd();
                                MatchCollection matchs     = webResourceRegex.Matches(input);
                                int             startIndex = 0;
                                StringBuilder   builder    = new StringBuilder();
                                foreach (Match match in matchs)
                                {
                                    builder.Append(input.Substring(startIndex, match.Index - startIndex));
                                    Group group = match.Groups["resourceName"];
                                    if (group != null)
                                    {
                                        string a = group.ToString();
                                        if (a.Length > 0)
                                        {
                                            if (string.Equals(a, webResource, StringComparison.Ordinal))
                                            {
                                                throw new HttpException(0x194, System.Web.SR.GetString("AssemblyResourceLoader_NoCircularReferences", new object[] { webResource }));
                                            }
                                            builder.Append(GetWebResourceUrlInternal(assembly, a, false, true, null));
                                        }
                                    }
                                    startIndex = match.Index + match.Length;
                                }
                                builder.Append(input.Substring(startIndex, input.Length - startIndex));
                                StreamWriter writer = new StreamWriter(context.Response.OutputStream, reader.CurrentEncoding);
                                writer.Write(builder.ToString());
                                writer.Flush();
                            }
                            else
                            {
                                byte[] buffer       = new byte[0x400];
                                Stream outputStream = context.Response.OutputStream;
                                int    count        = 1;
                                while (count > 0)
                                {
                                    count = manifestResourceStream.Read(buffer, 0, 0x400);
                                    outputStream.Write(buffer, 0, count);
                                }
                                outputStream.Flush();
                            }
                        }
                    }
                    finally
                    {
                        if (reader != null)
                        {
                            reader.Close();
                        }
                        if (manifestResourceStream != null)
                        {
                            manifestResourceStream.Close();
                        }
                    }
                }
            }
            catch
            {
                manifestResourceStream = null;
            }
            if (manifestResourceStream == null)
            {
                throw new HttpException(0x194, System.Web.SR.GetString("AssemblyResourceLoader_InvalidRequest"));
            }
            context.Response.IgnoreFurtherWrites();
        }
        internal static void ProcessRequestInternal(HttpContext context, string pathOverride)
        {
            HttpRequest  request  = context.Request;
            HttpResponse response = context.Response;
            string       virtualPathWithPathInfo;
            string       physicalPath;
            FileInfo     fileInfo;
            long         fileLength;
            DateTime     lastModifiedInUtc;
            string       etag;
            string       rangeHeader;

            // custom virtual path providers that don't yeild a MapPathBasedVirtualFile
            // are a special case, and do not support TransmitFile, WriteFile, Range requests,
            // or the cache policy that we apply below

            /*
             * if (ProcessRequestForNonMapPathBasedVirtualFile(request, response, overrideVirtualPath)) {
             *  return;
             * }
             *
             * if (overrideVirtualPath == null)
             * {
             *  virtualPathWithPathInfo = request.Path;
             *  physicalPath = request.PhysicalPath;
             * }
             * else {
             *  virtualPathWithPathInfo = overrideVirtualPath;
             *  physicalPath = request.MapPath(overrideVirtualPath);
             * }
             */

            if (pathOverride != null)
            {
                physicalPath = pathOverride;
            }
            else
            {
                physicalPath = context.Request.PhysicalPath;
            }

            // Debug.Trace("StaticFileHandler", "Path= " + virtualPathWithPathInfo + ", PhysicalPath= " + physicalPath);

            try
            {
                fileInfo = GetFileInfo(physicalPath);
            }
            catch (HttpException hex)
            {
                int    httpCode  = hex.GetHttpCode();
                string httpError = String.Format("{0} ({1})", hex.Message, physicalPath);
                throw new HttpException(httpCode, httpError, hex);
            }

            // Determine Last Modified Time.  We might need it soon
            // if we encounter a Range: and If-Range header
            // Using UTC time to avoid daylight savings time bug 83230
            lastModifiedInUtc = new DateTime(fileInfo.LastWriteTimeUtc.Year,
                                             fileInfo.LastWriteTimeUtc.Month,
                                             fileInfo.LastWriteTimeUtc.Day,
                                             fileInfo.LastWriteTimeUtc.Hour,
                                             fileInfo.LastWriteTimeUtc.Minute,
                                             fileInfo.LastWriteTimeUtc.Second,
                                             0,
                                             DateTimeKind.Utc);

            // Because we can't set a "Last-Modified" header to any time
            // in the future, check the last modified time and set it to
            // DateTime.Now if it's in the future.
            // This is to fix VSWhidbey #402323
            DateTime utcNow = DateTime.UtcNow;

            if (lastModifiedInUtc > utcNow)
            {
                // use 1 second resolution
                lastModifiedInUtc = new DateTime(utcNow.Ticks - (utcNow.Ticks % TimeSpan.TicksPerSecond), DateTimeKind.Utc);
            }

            etag       = GenerateETag(lastModifiedInUtc, utcNow);
            fileLength = fileInfo.Length;

            // is this a Range request?
            rangeHeader = request.Headers["Range"];
            if (rangeHeader != null && rangeHeader.StartsWith("bytes", StringComparison.OrdinalIgnoreCase) &&
                ProcessRangeRequest(context, physicalPath, fileLength, rangeHeader, etag, lastModifiedInUtc))
            {
                return;
            }

            // if we get this far, we're sending the entire file
            SendFile(physicalPath, 0, fileLength, fileLength, context);

            // Specify content type. Use extension to do the mapping
            response.ContentType = MimeMapping.GetMapping(physicalPath);
            // Static file handler supports byte ranges
            response.AppendHeader("Accept-Ranges", "bytes");
            // We want to flush cache entry when static file has changed
            response.AddFileDependency(physicalPath);

            /*
             * NOTE: This was the code originally in the handler:
             * // Set an expires in the future.
             * response.Cache.SetExpires(utcNow.AddMinutes(5));
             * // always set Last-Modified
             * response.Cache.SetLastModified(lastModifiedInUtc);
             * // always set ETag
             * response.Cache.SetETag(etag);
             * // always set Cache-Control to public
             * response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
             */

            // set cache headers
            HttpCachePolicy cachePolicy = response.Cache;

            SetCachingPolicy(cachePolicy);

            // set cache file info
            cachePolicy.SetETag(etag);
            cachePolicy.SetLastModified(lastModifiedInUtc);
        }
示例#16
0
 public override void SetLastModified(DateTime date)
 {
     _httpCachePolicy.SetLastModified(date);
 }
示例#17
0
        /// <summary>
        /// Configures ASP.Net's Cache policy based on properties set
        /// </summary>
        /// <param name="policy">cache policy to set</param>
        void ICachePolicyConfigurer.Configure(HttpCachePolicy policy)
        {
            policy.SetAllowResponseInBrowserHistory(allowInHistory);
            policy.SetCacheability(cacheability);
            policy.SetOmitVaryStar(omitVaryStar);
            policy.SetRevalidation(revalidation);
            policy.SetSlidingExpiration(slidingExpiration);
            policy.SetValidUntilExpires(validUntilExpires);

            if (duration != 0)
            {
                policy.SetExpires(DateTime.Now.AddSeconds(duration));
            }

            if (varyByContentEncodings != null)
            {
                foreach (var header in varyByContentEncodings.Split(','))
                {
                    policy.VaryByContentEncodings[header.Trim()] = true;
                }
            }

            if (varyByCustom != null)
            {
                policy.SetVaryByCustom(varyByCustom);
            }

            if (varyByHeaders != null)
            {
                foreach (var header in varyByHeaders.Split(','))
                {
                    policy.VaryByHeaders[header.Trim()] = true;
                }
            }

            if (varyByParams != null)
            {
                foreach (var param in varyByParams.Split(','))
                {
                    policy.VaryByParams[param.Trim()] = true;
                }
            }

            if (cacheExtension != null)
            {
                policy.AppendCacheExtension(cacheExtension);
            }

            if (setEtagFromFileDependencies)
            {
                policy.SetETagFromFileDependencies();
            }

            if (setLastModifiedFromFileDependencies)
            {
                policy.SetLastModifiedFromFileDependencies();
            }

            if (setNoServerCaching)
            {
                policy.SetNoServerCaching();
            }

            if (setNoStore)
            {
                policy.SetNoStore();
            }

            if (setNoTransforms)
            {
                policy.SetNoTransforms();
            }

            if (etag != null)
            {
                policy.SetETag(etag);
            }

            if (isLastModifiedSet)
            {
                policy.SetLastModified(lastModified);
            }

            if (isMaxAgeSet)
            {
                policy.SetMaxAge(TimeSpan.FromSeconds(maxAge));
            }

            if (isProxyMaxAgeSet)
            {
                policy.SetProxyMaxAge(TimeSpan.FromSeconds(proxyMaxAge));
            }
        }
示例#18
0
    private void GetFile()
    {
        try
        {
            if (Request.QueryString["image"] != null)
            {
                string sPath = MojoCube.Api.Text.Security.DecryptString(Request.QueryString["image"]);

                string path = "";

                if (sPath.Length > 0)
                {
                    if (sPath == "no_image.jpg")
                    {
                        path = Server.MapPath("~/Images/no_image.jpg");
                    }
                    else
                    {
                        path = Server.MapPath("~/Files/" + sPath);
                    }
                }
                else
                {
                    path = Server.MapPath("~/Images/blank.png");
                }

                ///////////////////////////////////////////////把图片文档缓存起来(开始)///////////////////////////////////////////////////////
                //获取实体的日期和时间
                DateTime input = System.IO.File.GetLastWriteTime(path);
                // 格式化日期时间,去掉毫秒和微秒:
                DateTime dt = new DateTime(input.Year, input.Month, input.Day, input.Hour, input.Minute, input.Second);
                // 获取浏览器发出的日期和时间
                string s = Request.Headers["If-Modified-Since"];

                // 判断是否修改过
                DateTime TempDate;
                if (((s != null) && DateTime.TryParse(s, out TempDate)) && (TempDate >= dt))
                {
                    // 没有修改过,使用浏览器缓存
                    Response.StatusCode = 0x130;
                }
                // 修改过,在Http头增加浏览器缓存控制
                else if (dt.ToUniversalTime() < DateTime.UtcNow)
                {
                    HttpCachePolicy cache = Response.Cache;
                    cache.SetCacheability(HttpCacheability.Public);
                    cache.SetLastModified(dt);
                }
                ///////////////////////////////////////////////把图片文档缓存起来(结束)///////////////////////////////////////////////////////

                byte[] bFile = null;

                System.Drawing.Image img = System.Drawing.Image.FromFile(path);

                int width  = img.Width;
                int height = img.Height;

                //按比例缩图
                if (Request.QueryString["w"] != null && Request.QueryString["h"] != null && sPath.Length > 0)
                {
                    if (width > height && width > int.Parse(Request.QueryString["w"]))
                    {
                        width  = int.Parse(Request.QueryString["w"]);
                        height = img.Height * width / img.Width;
                    }
                    else if (height > width && height > int.Parse(Request.QueryString["h"]))
                    {
                        height = int.Parse(Request.QueryString["h"]);
                        width  = img.Width * height / img.Height;
                    }
                    else if (width == height)
                    {
                        height = int.Parse(Request.QueryString["h"]);
                        width  = img.Width * height / img.Height;
                    }
                }

                System.Drawing.Image bitmap = null;

                //缩图并裁剪
                if (Request.QueryString["cut"] != null)
                {
                    System.IO.FileInfo myFile   = new System.IO.FileInfo(path);
                    byte[]             bytelist = CutPhoto(myFile, Request.QueryString["cut"]);
                    MemoryStream       ms1      = new MemoryStream(bytelist);
                    bitmap = (Bitmap)System.Drawing.Image.FromStream(ms1);
                    ms1.Close();
                }
                else
                {
                    bitmap = new Bitmap(width, height);
                    Graphics g = Graphics.FromImage(bitmap);
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.SmoothingMode      = SmoothingMode.HighQuality;
                    g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                    g.DrawImage(img, new System.Drawing.Rectangle(0, 0, width, height));
                }

                MemoryStream stream = new MemoryStream();

                string fileType = MojoCube.Api.File.Function.GetContentType(sPath);

                if (fileType == "image/png")
                {
                    bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                }
                else
                {
                    ImageCodecInfo[]  info = ImageCodecInfo.GetImageEncoders();
                    EncoderParameters ep   = new EncoderParameters(1);
                    ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)100);
                    bitmap.Save(stream, info[1], ep);
                }

                bFile = stream.ToArray();

                Response.Clear();
                Response.ContentType = fileType;
                string fileName = Server.HtmlEncode(sPath.Substring(sPath.LastIndexOf('/') + 1));
                Response.AddHeader("Content-Disposition", "inline;filename=\"" + fileName + "\"");

                Response.Charset         = "";
                Response.ContentEncoding = System.Text.Encoding.Unicode;
                Response.AddHeader("Connection", "close");
                Response.BinaryWrite(bFile);

                //Response.Clear();
                bitmap.Dispose();
                stream.Dispose();
                img.Dispose();
            }
            else if (Request.QueryString["file"] != null)
            {
                string sPath = MojoCube.Api.Text.Security.DecryptString(Request.QueryString["file"]);
                byte[] bFile = null;

                System.IO.FileInfo     File = new System.IO.FileInfo(Server.MapPath("~/Files/" + sPath));
                System.IO.FileStream   FS   = File.OpenRead();
                System.IO.BinaryReader BR   = new System.IO.BinaryReader(FS);
                bFile = BR.ReadBytes((int)FS.Length);
                FS.Dispose();
                BR.Close();

                Response.Clear();
                Response.ContentType = MojoCube.Api.File.Function.GetContentType(sPath);
                string fileName = Server.HtmlEncode(sPath.Substring(sPath.LastIndexOf('/') + 1));
                Response.AddHeader("Content-Disposition", "inline;filename=\"" + fileName + "\"");

                Response.Charset         = "";
                Response.ContentEncoding = System.Text.Encoding.Unicode;
                Response.AddHeader("Connection", "close");
                Response.BinaryWrite(bFile);
            }
        }
        catch
        {
            Response.Write("Error!");
        }
    }
示例#19
0
        public void Deny_Unrestricted()
        {
            HttpCachePolicy cache = response.Cache;

            Assert.IsNotNull(cache.VaryByHeaders, "VaryByHeaders");
            Assert.IsNotNull(cache.VaryByParams, "VaryByParams");
            cache.AddValidationCallback(new HttpCacheValidateHandler(Validate), null);
            cache.AppendCacheExtension("mono");
            cache.SetCacheability(HttpCacheability.NoCache);
            cache.SetCacheability(HttpCacheability.NoCache, "mono");
            cache.SetETag("etag");
            try
            {
                cache.SetETagFromFileDependencies();
            }
            catch (TypeInitializationException)
            {
                // 1.1 tries to initialize HttpRuntime
            }
            catch (InvalidOperationException)
            {
                // expected
            }
            cache.SetExpires(DateTime.MinValue);
            cache.SetLastModified(DateTime.Now);
            try
            {
                cache.SetLastModifiedFromFileDependencies();
            }
            catch (InvalidOperationException)
            {
                // expected
            }
            catch (NotImplementedException)
            {
                // mono
            }
            cache.SetMaxAge(TimeSpan.FromTicks(1000));
            try
            {
                cache.SetNoServerCaching();
            }
            catch (NotImplementedException)
            {
                // mono
            }
            try
            {
                cache.SetNoStore();
            }
            catch (NotImplementedException)
            {
                // mono
            }
            try
            {
                cache.SetNoTransforms();
            }
            catch (NotImplementedException)
            {
                // mono
            }
            cache.SetProxyMaxAge(TimeSpan.FromTicks(2000));
            cache.SetRevalidation(HttpCacheRevalidation.None);
            cache.SetSlidingExpiration(true);
            try
            {
                cache.SetValidUntilExpires(true);
            }
            catch (NotImplementedException)
            {
                // mono
            }
            cache.SetVaryByCustom("custom");
            cache.SetAllowResponseInBrowserHistory(true);

#if NET_2_0
            try
            {
                cache.SetOmitVaryStar(false);
            }
            catch (NotImplementedException)
            {
                // mono
            }
#endif
        }
示例#20
0
        public static bool OutputCombineScriptResourcesFile(HttpContext context)
        {
            bool        result  = false;
            HttpRequest request = context.Request;
            string      text    = request.QueryString["resources"];

            if (!string.IsNullOrEmpty(text))
            {
                HttpResponse response = context.Response;
                response.ContentType = "application/x-javascript";
                HttpCachePolicy cache = response.Cache;
                cache.SetCacheability(HttpCacheability.Private);
                cache.VaryByParams["resources"] = true;
                cache.VaryByParams["v"]         = true;
                cache.VaryByParams["c"]         = true;
                cache.SetOmitVaryStar(true);
                cache.SetExpires(DateTime.Now.AddDays(365.0));
                cache.SetValidUntilExpires(true);
                DateTime lastWriteTime = new FileInfo(new Uri(Assembly.GetCallingAssembly().CodeBase).LocalPath).LastWriteTime;
                DateTime lastModified  = (DateTime.UtcNow > lastWriteTime.ToUniversalTime()) ? lastWriteTime : DateTime.Now;
                cache.SetLastModified(lastModified);
                Stream stream = response.OutputStream;
                if (!request.Browser.IsBrowser("IE") || 6 < request.Browser.MajorVersion)
                {
                    foreach (string b in (request.Headers["Accept-Encoding"] ?? string.Empty).ToUpperInvariant().Split(new char[]
                    {
                        ','
                    }))
                    {
                        if ("GZIP" == b)
                        {
                            response.AddHeader("Content-encoding", "gzip");
                            stream = new GZipStream(stream, CompressionMode.Compress);
                            break;
                        }
                        if ("DEFLATE" == b)
                        {
                            response.AddHeader("Content-encoding", "deflate");
                            stream = new DeflateStream(stream, CompressionMode.Compress);
                            break;
                        }
                    }
                }
                CultureInfo currentCulture   = Thread.CurrentThread.CurrentCulture;
                CultureInfo currentUICulture = Thread.CurrentThread.CurrentUICulture;
                try
                {
                    string text2 = request.QueryString["c"];
                    if (!string.IsNullOrEmpty(text2))
                    {
                        CultureInfo cultureInfoByIetfLanguageTag = CultureInfo.GetCultureInfoByIetfLanguageTag(text2);
                        Thread.CurrentThread.CurrentCulture = (Thread.CurrentThread.CurrentUICulture = cultureInfoByIetfLanguageTag);
                    }
                }
                catch (ArgumentException)
                {
                }
                CombinableScripts scriptByAlias = ToolkitScriptManager.CacheScriptBuckets.GetScriptByAlias(HttpUtility.UrlDecode(text), false);
                if (scriptByAlias != null)
                {
                    using (StreamWriter streamWriter = new StreamWriter(stream))
                    {
                        ToolkitScriptManager.WriteScriptsResources(scriptByAlias.Scripts, streamWriter);
                        streamWriter.WriteLine("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");
                    }
                    result = true;
                }
                else
                {
                    stream.Close();
                    stream = null;
                }
                Thread.CurrentThread.CurrentCulture   = currentCulture;
                Thread.CurrentThread.CurrentUICulture = currentUICulture;
            }
            return(result);
        }
        public ActionResult ProcessRequest()
        {
            var Request = HttpContext.Request;

            string resourceSet = Request.Query["ResourceSet"];


            string localeId = Request.Query["LocaleId"];

            if (string.IsNullOrEmpty(localeId))
            {
                localeId = "auto";
            }
            string resourceMode = Request.Query["ResourceMode"];

            if (string.IsNullOrEmpty(resourceMode))
            {
                resourceMode = "Resx"; // Resx/ResDb/Auto
            }
            string varname = Request.Query["VarName"];

            if (string.IsNullOrEmpty(varname))
            {
                varname = "resources";
            }

            // varname is embedded into script so validate to avoid script injection
            // it's gotta be a valid C# and valid JavaScript name
            Match match = Regex.Match(varname, @"^[\w|\d|_|$|@|\.]*$");

            if (match.Length < 1 || match.Groups[0].Value != varname)
            {
                SendErrorResponse("Invalid variable name passed.");
            }

            if (string.IsNullOrEmpty(resourceSet))
            {
                SendErrorResponse("Invalid ResourceSet specified.");
            }

            // pick current UI Culture
            if (localeId == "auto")
            {
                try
                {
                    // Use ASP.NET Core RequestLocalization Mapping
                    var cultureProvider = HttpContext.Features.Get <IRequestCultureFeature>();
                    if (cultureProvider != null)
                    {
                        localeId = cultureProvider.RequestCulture.UICulture.IetfLanguageTag;
                    }
                    else
                    {
                        localeId = Thread.CurrentThread.CurrentUICulture.IetfLanguageTag;
                    }
                }
                catch
                {
                    localeId = Thread.CurrentThread.CurrentUICulture.IetfLanguageTag;
                }
            }

            Dictionary <string, object> resDict = null;

            resourceMode = string.IsNullOrEmpty(resourceMode) ? "auto" : resourceMode.ToLower();

            ResourceAccessMode mode = ResourceAccessMode.Resx;

            if (resourceMode == "resdb")
            {
                mode = ResourceAccessMode.DbResourceManager;
            }
            else if (resourceMode == "auto")
            {
                mode = DbResourceConfiguration.Current.ResourceAccessMode;
            }


            if (mode == ResourceAccessMode.DbResourceManager)
            {
                var resManager = DbResourceDataManager.CreateDbResourceDataManager(
                    Config.DbResourceDataManagerType);
                resDict = resManager.GetResourceSetNormalizedForLocaleId(localeId, resourceSet);
                if (resDict == null || resDict.Count == 0)
                {
                    mode = ResourceAccessMode.Resx; // try Resx resources from disk instead
                }
            }
            if (mode != ResourceAccessMode.DbResourceManager) // Resx Resources loaded from disk
            {
                string          basePath  = Request.MapPath(DbResourceConfiguration.Current.ResxBaseFolder, basePath: Host.ContentRootPath);
                DbResXConverter converter = new DbResXConverter(basePath);

                resDict = converter.GetCompiledResourcesNormalizedForLocale(resourceSet,
                                                                            DbResourceConfiguration.Current.ResourceBaseNamespace,
                                                                            localeId);

                if (resDict == null)
                {
                    // check for .resx disk resources
                    string resxPath = converter.FormatResourceSetPath(resourceSet);
                    resDict = converter.GetResXResourcesNormalizedForLocale(resxPath, localeId);
                }
                else
                {
                    resDict = resDict.OrderBy(kv => kv.Key).ToDictionary(k => k.Key, v => v.Value);
                }
            }

            // return all resource strings
            resDict = resDict.Where(res => res.Value is string)
                      .ToDictionary(dict => dict.Key, dict => dict.Value);

            string javaScript = SerializeResourceDictionary(resDict, varname);



#if NETFULL // client cache
            if (!HttpContext.Current.IsDebuggingEnabled)
            {
                Response.ExpiresAbsolute = DateTime.UtcNow.AddDays(1);
                Response.AppendHeader("Accept-Ranges", "bytes");
                Response.AppendHeader("Vary", "Accept-Encoding");
                Response.Cache.SetETag("\"" + javaScript.GetHashCode().ToString("x") + "\"");
                Response.Cache.SetLastModified(DateTime.UtcNow);

                // OutputCache settings
                HttpCachePolicy cache = Response.Cache;

                cache.VaryByParams["ResourceSet"]     = true;
                cache.VaryByParams["LocaleId"]        = true;
                cache.VaryByParams["ResoureType"]     = true;
                cache.VaryByParams["IncludeControls"] = true;
                cache.VaryByParams["VarName"]         = true;
                cache.VaryByParams["ResourceMode"]    = true;
                //cache.SetOmitVaryStar(true);

                DateTime now = DateTime.Now;
                cache.SetCacheability(HttpCacheability.Public);
                cache.SetExpires(now + TimeSpan.FromDays(1));
                cache.SetValidUntilExpires(true);
                cache.SetLastModified(now);
            }
#endif

            return(SendTextOutput(javaScript, "text/javascript; charset=utf-8"));
        }
示例#22
0
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            Image        image;
            ImageFormat  imageFormat;
            string       contentType = null;
            MemoryStream memStream   = null;
            ImageCache   imageCache;
            bool         enableCaching = true;
            bool         cacheValid    = false;
            int          minutes       = Null.NullInteger;
            string       cacheKey      = null;
            string       eTag          = null;
            // Get params
            string imagePath  = context.Request.QueryString["IP"];
            string thumbWidth = context.Request.QueryString["IW"];
            string background = context.Request.QueryString["BC"];
            string duration   = context.Request.QueryString["CD"];
            // Get Header Etag
            string headerEtag = context.Request.Headers["If-None-Match"];
            // When image param start by http or https,
            // it's probably an external image!
            ImageTypeName imageType;

            if (imagePath.IndexOf("http://") > -1 || imagePath.IndexOf("https://") > -1)
            {
                // Image will be get from an http request
                imageType = ImageTypeName.URI;
            }
            else
            {
                // Image will be read from disk
                imageType = ImageTypeName.FilePath;
                imagePath = context.Server.MapPath(imagePath);
            }
            // Default image if not found
            string defaultImage = context.Server.MapPath("~/images/thumbnail.jpg");

            try
            {
                if (string.IsNullOrEmpty(imagePath) == false)
                {
                    // Initializations
                    if (string.IsNullOrEmpty(thumbWidth))
                    {
                        thumbWidth = "175";
                    }
                    if (string.IsNullOrEmpty(duration))
                    {
                        enableCaching = false;
                    }
                    else
                    {
                        minutes = Convert.ToInt32(duration);
                    }
                    // Get cached image thumbnail
                    if (enableCaching)
                    {
                        cacheKey   = string.Format("Store_{0}_{1}_{2}", imagePath, thumbWidth, background);
                        eTag       = cacheKey.GetHashCode().ToString("X");
                        imageCache = (ImageCache)DataCache.GetCache(cacheKey);
                        if (imageCache != null)
                        {
                            contentType = imageCache.ContentType;
                            memStream   = new MemoryStream(imageCache.Data);
                            cacheValid  = true;
                        }
                    }
                    // If cache is null, create the thumbnail
                    if (!cacheValid)
                    {
                        image       = GetImage(imageType, imagePath, defaultImage);
                        imageFormat = image.RawFormat;
                        contentType = GetContentType(imageFormat);
                        Size     thumbSize = ThumbSize(image.Width, image.Height, Convert.ToInt16(thumbWidth));
                        Bitmap   thumb     = new Bitmap(thumbSize.Width, thumbSize.Height);
                        Graphics g         = Graphics.FromImage(thumb);
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                        g.SmoothingMode      = SmoothingMode.HighQuality;
                        g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                        // Fill background with specified color
                        // to mimics original GIF transparency
                        if (imageFormat.Equals(ImageFormat.Gif))
                        {
                            Brush bgBrush = GetBrush(GetHexDigits(background));
                            g.FillRectangle(bgBrush, 0, 0, thumbSize.Width, thumbSize.Height);
                        }
                        g.DrawImage(image, 0, 0, thumbSize.Width, thumbSize.Height);
                        // Create memory stream from thumbnail
                        memStream = new MemoryStream();
                        thumb.Save(memStream, imageFormat);
                        image.Dispose();
                        thumb.Dispose();
                        // Save thumbnail to cache
                        if (enableCaching)
                        {
                            imageCache = new ImageCache(contentType, memStream.ToArray());
                            TimeSpan sliding = new TimeSpan(0, Convert.ToInt32(duration), 0);
                            DataCache.SetCache(cacheKey, imageCache, sliding);
                        }
                    }
                    // If an Etag is present and valid
                    if (string.IsNullOrEmpty(headerEtag) == false && headerEtag == eTag)
                    {
                        // Return 304 Not Modified
                        context.Response.Clear();
                        context.Response.StatusCode      = (int)HttpStatusCode.NotModified;
                        context.Response.SuppressContent = true;
                    }
                    else
                    {
                        // Return thumbnail to browser
                        context.Response.StatusCode  = (int)HttpStatusCode.OK;
                        context.Response.ContentType = contentType;
                        if (enableCaching)
                        {
                            HttpCachePolicy contextCache = context.Response.Cache;
                            contextCache.SetCacheability(HttpCacheability.ServerAndPrivate);
                            contextCache.SetExpires(DateTime.Now.AddMinutes(minutes).ToUniversalTime());
                            contextCache.SetLastModified(DateTime.Now.ToUniversalTime());
                            contextCache.SetETag(eTag);
                        }
                        memStream.WriteTo(context.Response.OutputStream);
                    }
                    memStream.Close();
                    memStream.Dispose();
                }
            }
            catch
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
            }
        }
示例#23
0
    private void GetFile()
    {
        try
        {
            if (Request.QueryString["image"] != null)
            {
                string sPath = MojoCube.Api.Text.Security.DecryptString(Request.QueryString["image"]);

                string path = "";

                if (sPath.Length > 0)
                {
                    if (sPath == "no_image.jpg")
                    {
                        path = Server.MapPath("~/Images/no_image.jpg");
                    }
                    else
                    {
                        path = Server.MapPath("~/Files/" + sPath);
                    }
                }
                else
                {
                    path = Server.MapPath("~/Images/blank.png");
                }

                ///////////////////////////////////////////////把图片文档缓存起来(开始)///////////////////////////////////////////////////////
                //获取实体的日期和时间
                DateTime input = System.IO.File.GetLastWriteTime(path);
                // 格式化日期时间,去掉毫秒和微秒:
                DateTime dt = new DateTime(input.Year, input.Month, input.Day, input.Hour, input.Minute, input.Second);
                // 获取浏览器发出的日期和时间
                string s = Request.Headers["If-Modified-Since"];

                // 判断是否修改过
                DateTime TempDate;
                if (((s != null) && DateTime.TryParse(s, out TempDate)) && (TempDate >= dt))
                {
                    // 没有修改过,使用浏览器缓存
                    Response.StatusCode = 0x130;
                }
                // 修改过,在Http头增加浏览器缓存控制
                else if (dt.ToUniversalTime() < DateTime.UtcNow)
                {
                    HttpCachePolicy cache = Response.Cache;
                    cache.SetCacheability(HttpCacheability.Public);
                    cache.SetLastModified(dt);
                }
                ///////////////////////////////////////////////把图片文档缓存起来(结束)///////////////////////////////////////////////////////

                byte[] bFile = null;

                System.Drawing.Image img = System.Drawing.Image.FromFile(path);

                int width  = img.Width;
                int height = img.Height;

                //按比例缩图
                if (Request.QueryString["w"] != null && Request.QueryString["h"] != null && sPath.Length > 0)
                {
                    if (width > height && width > int.Parse(Request.QueryString["w"]))
                    {
                        width  = int.Parse(Request.QueryString["w"]);
                        height = img.Height * width / img.Width;
                    }
                    else if (height > width && height > int.Parse(Request.QueryString["h"]))
                    {
                        height = int.Parse(Request.QueryString["h"]);
                        width  = img.Width * height / img.Height;
                    }
                    else if (width == height)
                    {
                        height = int.Parse(Request.QueryString["h"]);
                        width  = img.Width * height / img.Height;
                    }
                }

                System.Drawing.Image bitmap = null;

                //缩图并裁剪
                if (Request.QueryString["cut"] != null)
                {
                    System.IO.FileInfo myFile   = new System.IO.FileInfo(path);
                    byte[]             bytelist = CutPhoto(myFile, Request.QueryString["cut"]);
                    MemoryStream       ms1      = new MemoryStream(bytelist);
                    bitmap = (Bitmap)System.Drawing.Image.FromStream(ms1);
                    ms1.Close();
                }
                else
                {
                    bitmap = new Bitmap(width, height);
                    Graphics g = Graphics.FromImage(bitmap);
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.SmoothingMode      = SmoothingMode.HighQuality;
                    g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                    g.DrawImage(img, new System.Drawing.Rectangle(0, 0, width, height));
                }

                //是否显示水印
                MojoCube.Web.Site.Config config = new MojoCube.Web.Site.Config();
                config.GetData(1, MojoCube.Api.UI.Language.GetLanguage());

                if (width == 582)
                {
                    config.WM_IsShow = false;
                }

                if (config.WM_IsShow && width > config.WM_Show_W || config.WM_IsShow && height > config.WM_Show_H)
                {
                    int WM_Bottom = config.WM_Bottom;
                    int WM_Right  = config.WM_Right;
                    int WM_Alpha  = config.WM_Alpha;
                    int WM_Red    = config.WM_Red;
                    int WM_Green  = config.WM_Green;
                    int WM_Blue   = config.WM_Blue;
                    int WM_Rotate = config.WM_Rotate;
                    int WM_Size   = config.WM_Size;

                    //文字模式
                    if (!config.WM_Mode)
                    {
                        string WM_Text     = config.WM_Text;
                        string WM_Font     = config.WM_Font;
                        int    WM_FontSize = config.WM_FontSize;

                        Graphics grPhoto = Graphics.FromImage(bitmap);

                        //消除锯齿
                        grPhoto.SmoothingMode     = SmoothingMode.AntiAlias;
                        grPhoto.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

                        Font  crFont = new Font(WM_Font, WM_FontSize, FontStyle.Bold);
                        SizeF crSize = grPhoto.MeasureString(WM_Text, crFont);

                        int iRotate = WM_Rotate;

                        float pCenterX = 0;
                        float pCenterY = 0;
                        //设置字体在图片中的位置
                        float yPosFromBottom = 0;
                        float xCenterOfImg   = 0;
                        switch (WM_Size)
                        {
                        case 0:     //center
                            yPosFromBottom = height / 2 - (crSize.Height / 2);
                            pCenterX       = xCenterOfImg = width / 2;
                            pCenterY       = height / 2;
                            break;

                        case 1:     //top left
                            pCenterY = yPosFromBottom = crSize.Height / 2 - WM_Bottom;
                            pCenterX = xCenterOfImg = crSize.Width / 2 + WM_Right;
                            break;

                        case 2:     //top right
                            pCenterY = yPosFromBottom = crSize.Height / 2 - WM_Bottom;
                            pCenterX = xCenterOfImg = width - crSize.Width / 2 - WM_Right;
                            break;

                        case 3:     //bottom left
                            pCenterY = yPosFromBottom = height - WM_Bottom - (crSize.Height);
                            pCenterX = xCenterOfImg = crSize.Width / 2 + WM_Right;
                            break;

                        case 4:     //bottom right
                            pCenterY = yPosFromBottom = height - WM_Bottom - (crSize.Height);
                            pCenterX = xCenterOfImg = width - WM_Right - (crSize.Width / 2);
                            break;
                        }

                        //设置字体居中
                        StringFormat StrFormat = new StringFormat();
                        StrFormat.Alignment = StringAlignment.Center;

                        //设置绘制文本的颜色和纹理 (Alpha=153)
                        SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(WM_Alpha, WM_Red, WM_Green, WM_Blue));

                        //旋转水印
                        PointF pCenter = new PointF(pCenterX, pCenterY);
                        grPhoto.TranslateTransform(pCenter.X, pCenter.Y);
                        grPhoto.RotateTransform(iRotate);
                        grPhoto.TranslateTransform(-pCenter.X, -pCenter.Y);

                        //将版权信息绘制到图象上
                        grPhoto.DrawString(WM_Text, crFont, semiTransBrush2, new PointF(xCenterOfImg, yPosFromBottom), StrFormat);
                    }
                    //图片模式
                    else
                    {
                        int iMarkRightSpace  = 0;
                        int iMarkButtomSpace = 0;
                        //创建一个需要填充水银的Image对象
                        System.Drawing.Image imgWatermark = new Bitmap(Server.MapPath("~/Files/" + config.WM_ImagePath));
                        int iMarkWidth   = imgWatermark.Width;
                        int iMarkmHeight = imgWatermark.Height;

                        Graphics grWatermark = null;

                        //将位图bmWatermark加载到Graphics对象
                        grWatermark = Graphics.FromImage(bitmap);
                        ImageAttributes imageAttributes = new ImageAttributes();

                        ColorMap colorMap = new ColorMap();

                        colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                        colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

                        ColorMap[] remapTable = { colorMap };

                        imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                        float[][] colorMatrixElements =
                        {
                            new float[] { 1.0f, 0.0f, 0.0f,                                 0.0f, 0.0f },
                            new float[] { 0.0f, 1.0f, 0.0f,                                 0.0f, 0.0f },
                            new float[] { 0.0f, 0.0f, 1.0f,                                 0.0f, 0.0f },
                            new float[] { 0.0f, 0.0f, 0.0f, (float)((WM_Alpha / 50) * 20) / 100f, 0.0f }, //设置透明度
                            new float[] { 0.0f, 0.0f, 0.0f,                                 0.0f, 1.0f }
                        };
                        ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);

                        imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

                        iMarkRightSpace  = width - iMarkWidth - WM_Right;
                        iMarkButtomSpace = height - iMarkmHeight - WM_Bottom;

                        grWatermark.DrawImage(imgWatermark, new Rectangle(iMarkRightSpace, iMarkButtomSpace, iMarkWidth, iMarkmHeight), 0, 0, iMarkWidth, iMarkmHeight, GraphicsUnit.Pixel, imageAttributes);
                    }
                }

                MemoryStream stream = new MemoryStream();

                string fileType = MojoCube.Api.File.Function.GetContentType(sPath);

                if (fileType == "image/png")
                {
                    bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                }
                else
                {
                    ImageCodecInfo[]  info = ImageCodecInfo.GetImageEncoders();
                    EncoderParameters ep   = new EncoderParameters(1);
                    ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)100);
                    bitmap.Save(stream, info[1], ep);
                }

                bFile = stream.ToArray();

                Response.Clear();
                Response.ContentType = fileType;
                string fileName = Server.HtmlEncode(sPath.Substring(sPath.LastIndexOf('/') + 1));
                Response.AddHeader("Content-Disposition", "inline;filename=\"" + fileName + "\"");

                Response.Charset         = "";
                Response.ContentEncoding = System.Text.Encoding.Unicode;
                Response.AddHeader("Connection", "close");
                Response.BinaryWrite(bFile);

                //Response.Clear();
                bitmap.Dispose();
                stream.Dispose();
                img.Dispose();
            }
            else if (Request.QueryString["file"] != null)
            {
                string sPath = MojoCube.Api.Text.Security.DecryptString(Request.QueryString["file"]);
                byte[] bFile = null;

                System.IO.FileInfo     File = new System.IO.FileInfo(Server.MapPath("~/Files/" + sPath));
                System.IO.FileStream   FS   = File.OpenRead();
                System.IO.BinaryReader BR   = new System.IO.BinaryReader(FS);
                bFile = BR.ReadBytes((int)FS.Length);
                FS.Dispose();
                BR.Close();

                Response.Clear();
                Response.ContentType = MojoCube.Api.File.Function.GetContentType(sPath);
                string fileName = Server.HtmlEncode(sPath.Substring(sPath.LastIndexOf('/') + 1));
                Response.AddHeader("Content-Disposition", "inline;filename=\"" + fileName + "\"");

                Response.Charset         = "";
                Response.ContentEncoding = System.Text.Encoding.Unicode;
                Response.AddHeader("Connection", "close");
                Response.BinaryWrite(bFile);
            }
        }
        catch
        {
            Response.Write("Error!");
        }
    }
示例#24
0
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest  Request  = HttpContext.Current.Request;
            HttpResponse Response = HttpContext.Current.Response;

            string resourceSet     = Request.Params["ResourceSet"];
            string localeId        = Request.Params["LocaleId"] ?? "";
            string resourceType    = Request.Params["ResourceType"] ?? "Resx"; // Resx/ResDb
            bool   includeControls = (Request.Params["IncludeControls"] ?? "") != "";
            string varname         = Request.Params["VarName"] ?? "resources";
            string resourceMode    = (Request.Params["ResourceMode"] ?? "0");

            // varname is embedded into script so validate to avoid script injection
            // it's gotta be a valid C# and valid JavaScript name
            Match match = Regex.Match(varname, @"^[\w|\d|_|$|@|\.]*$");

            if (match.Length < 1 || match.Groups[0].Value != varname)
            {
                SendErrorResponse("Invalid variable name passed.");
            }

            if (string.IsNullOrEmpty(resourceSet))
            {
                SendErrorResponse("Invalid ResourceSet specified.");
            }

            Dictionary <string, object> resDict = null;

            if (resourceType.ToLower() == "resdb")
            {
                DbResourceDataManager manager = new DbResourceDataManager();
                resDict = manager.GetResourceSetNormalizedForLocaleId(localeId, resourceSet) as Dictionary <string, object>;
            }
            else  // Resx Resources
            {
                DbResXConverter converter = new DbResXConverter();
                // must figure out the path
                string resxPath = null;
                //if (DbResourceConfiguration.Current.ResxExportProjectType == GlobalizationResxExportProjectTypes.WebForms)
                //    resxPath = converter.FormatWebResourceSetPath(resourceSet, (resourceMode == "0") );
                //else
                resxPath = converter.FormatResourceSetPath(resourceSet);

                resDict = converter.GetResXResourcesNormalizedForLocale(resxPath, localeId) as Dictionary <string, object>;
            }


            if (resourceMode == "0" && !includeControls)
            {
                // filter the list to strip out controls (anything that contains a . in the ResourceId
                // is considered a control value
                resDict = resDict.Where(res => !res.Key.Contains('.') && res.Value is string)
                          .ToDictionary(dict => dict.Key, dict => dict.Value);
            }
            else
            {
                // return all resource strings
                resDict = resDict.Where(res => res.Value is string)
                          .ToDictionary(dict => dict.Key, dict => dict.Value);
            }

            string javaScript = SerializeResourceDictionary(resDict, varname);


            // client cache
            if (!HttpContext.Current.IsDebuggingEnabled)
            {
                Response.ExpiresAbsolute = DateTime.UtcNow.AddDays(30);
                Response.Cache.SetLastModified(DateTime.UtcNow);
                Response.AppendHeader("Accept-Ranges", "bytes");
                Response.AppendHeader("Vary", "Accept-Encoding");
                Response.Cache.SetETag("\"" + javaScript.GetHashCode().ToString("x") + "\"");
                Response.Cache.SetLastModified(DateTime.UtcNow);
            }

            // OutputCache settings
            HttpCachePolicy cache = Response.Cache;

            cache.VaryByParams["LocaleId"]        = true;
            cache.VaryByParams["ResoureType"]     = true;
            cache.VaryByParams["IncludeControls"] = true;
            cache.VaryByParams["VarName"]         = true;
            cache.VaryByParams["ResourceMode"]    = true;
            //cache.SetOmitVaryStar(true);

            DateTime now = DateTime.Now;

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetExpires(now + TimeSpan.FromDays(10));
            cache.SetValidUntilExpires(true);
            cache.SetLastModified(now);

            SendTextOutput(javaScript, "application/javascript");
        }
示例#25
0
        internal static void ProcessRequestInternal(HttpContext context, string pathOverride)
        {
            HttpRequest  request  = context.Request;
            HttpResponse response = context.Response;

            string physicalPath = context.Request.PhysicalPath;
            string fileName     = Path.GetFileName(physicalPath);

            if (pathOverride != null)
            {
                physicalPath = pathOverride;
            }

            FileInfo info;

            if (!FileExists(physicalPath))
            {
                string error = "File does not exist";
                if (context.IsDebuggingEnabled)
                {
                    error += String.Format(": {0}", physicalPath);
                }
                throw new HttpException(404, error);
            }

            try
            {
                info = new FileInfo(physicalPath);
            }
            catch (IOException exception)
            {
                throw new HttpException(404, "Error trying to enumerate files", exception);
            }
            catch (SecurityException exception2)
            {
                throw new HttpException(401, "File enumerator access denied", exception2);
            }

            if (info.Length == 0)
            {
                throw new HttpException(404, "File is empty");
            }

            if ((info.Attributes & FileAttributes.Hidden) != 0)
            {
                throw new HttpException(404, "File is hidden");
            }

            if (physicalPath[physicalPath.Length - 1] == '.')
            {
                throw new HttpException(404, "File does not exist");
            }

            if ((info.Attributes & FileAttributes.Directory) != 0)
            {
                if (request.Path.EndsWith("/"))
                {
                    throw new HttpException(403, SR.GetString("Missing star mapping"));
                }
                response.Redirect(request.Path + "/");
            }
            else
            {
                DateTime lastModTime = new DateTime(info.LastWriteTime.Year, info.LastWriteTime.Month, info.LastWriteTime.Day, info.LastWriteTime.Hour, info.LastWriteTime.Minute, info.LastWriteTime.Second, 0);

                if (lastModTime > DateTime.Now)
                {
                    lastModTime = DateTime.Now;
                }

                string strETag = GenerateETag(context, lastModTime);

                try
                {
                    BuildFileItemResponse(context, physicalPath, info.Length, lastModTime, strETag);
                }
                catch (Exception exception3)
                {
                    if ((exception3 is ExternalException) && IsSecurityError(((ExternalException)exception3).ErrorCode))
                    {
                        throw new HttpException(401, "Resource access forbidden");
                    }
                }

                // set cache headers
                HttpCachePolicy cachePolicy = context.Response.Cache;
                SetCachingPolicy(cachePolicy);

                // set cache file info
                cachePolicy.SetETag(strETag);
                cachePolicy.SetLastModified(lastModTime);
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest  Request  = HttpContext.Current.Request;
            HttpResponse Response = HttpContext.Current.Response;

            string resourceSet     = Request.Params["ResourceSet"];
            string localeId        = Request.Params["LocaleId"] ?? "auto";
            string resourceType    = Request.Params["ResourceType"] ?? "Resx"; // Resx/ResDb
            bool   includeControls = (Request.Params["IncludeControls"] ?? "") != "";
            string varname         = Request.Params["VarName"] ?? "resources";
            string resourceMode    = (Request.Params["ResourceMode"] ?? "0");

            // varname is embedded into script so validate to avoid script injection
            // it's gotta be a valid C# and valid JavaScript name
            Match match = Regex.Match(varname, @"^[\w|\d|_|$|@|\.]*$");

            if (match.Length < 1 || match.Groups[0].Value != varname)
            {
                SendErrorResponse("Invalid variable name passed.");
            }

            if (string.IsNullOrEmpty(resourceSet))
            {
                SendErrorResponse("Invalid ResourceSet specified.");
            }

            // pick current UI Culture
            if (localeId == "auto")
            {
                localeId = Thread.CurrentThread.CurrentUICulture.IetfLanguageTag;
            }

            Dictionary <string, object> resDict = null;

            if (string.IsNullOrEmpty(resourceType) || resourceType == "auto")
            {
                if (DbResourceProvider.ProviderLoaded || DbSimpleResourceProvider.ProviderLoaded)
                {
                    resourceType = "resdb";
                }
                else
                {
                    resourceType = "resx";
                }
            }


            if (resourceType.ToLower() == "resdb")
            {
                // use existing/cached resource manager if previously used
                // so database is accessed only on first hit
                var resManager = DbRes.GetResourceManager(resourceSet);

                DbResXConverter converter = new DbResXConverter(context.Server.MapPath(DbResourceConfiguration.Current.ResxBaseFolder));
                resDict = converter.GetResourcesNormalizedForLocale(resManager, localeId);

                //resDict = manager.GetResourceSetNormalizedForLocaleId(localeId, resourceSet);
                if (resDict == null || resDict.Keys.Count < 1)
                {
                    // try resx instead
                    string resxPath = converter.FormatResourceSetPath(resourceSet);
                    resDict = converter.GetResXResourcesNormalizedForLocale(resxPath, localeId);
                }
            }
            else  // Resx Resources
            {
                string          basePath  = context.Server.MapPath(DbResourceConfiguration.Current.ResxBaseFolder);
                DbResXConverter converter = new DbResXConverter(basePath);

                resDict = converter.GetCompiledResourcesNormalizedForLocale(resourceSet,
                                                                            DbResourceConfiguration.Current.ResourceBaseNamespace,
                                                                            localeId);

                if (resDict == null)
                {
                    // check for .resx disk resources
                    string resxPath = converter.FormatResourceSetPath(resourceSet);
                    resDict = converter.GetResXResourcesNormalizedForLocale(resxPath, localeId);
                }
                else
                {
                    resDict = resDict.OrderBy(kv => kv.Key).ToDictionary(k => k.Key, v => v.Value);
                }
            }


            if (resourceMode == "0" && !includeControls)
            {
                // filter the list to strip out controls (anything that contains a . in the ResourceId
                // is considered a control value
                resDict = resDict.Where(res => !res.Key.Contains('.') && res.Value is string)
                          .ToDictionary(dict => dict.Key, dict => dict.Value);
            }
            else
            {
                // return all resource strings
                resDict = resDict.Where(res => res.Value is string)
                          .ToDictionary(dict => dict.Key, dict => dict.Value);
            }

            string javaScript = SerializeResourceDictionary(resDict, varname);


            // client cache
            if (!HttpContext.Current.IsDebuggingEnabled)
            {
                Response.ExpiresAbsolute = DateTime.UtcNow.AddDays(1);
                Response.AppendHeader("Accept-Ranges", "bytes");
                Response.AppendHeader("Vary", "Accept-Encoding");
                Response.Cache.SetETag("\"" + javaScript.GetHashCode().ToString("x") + "\"");
                Response.Cache.SetLastModified(DateTime.UtcNow);

                // OutputCache settings
                HttpCachePolicy cache = Response.Cache;

                cache.VaryByParams["ResourceSet"]     = true;
                cache.VaryByParams["LocaleId"]        = true;
                cache.VaryByParams["ResoureType"]     = true;
                cache.VaryByParams["IncludeControls"] = true;
                cache.VaryByParams["VarName"]         = true;
                cache.VaryByParams["ResourceMode"]    = true;
                //cache.SetOmitVaryStar(true);

                DateTime now = DateTime.Now;
                cache.SetCacheability(HttpCacheability.Public);
                cache.SetExpires(now + TimeSpan.FromDays(1));
                cache.SetValidUntilExpires(true);
                cache.SetLastModified(now);
            }

            SendTextOutput(javaScript, "text/javascript");
        }
示例#27
0
        /// <internalonly/>
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            // Make sure we don't get any extra content in this handler (like Application.BeginRequest stuff);
            context.Response.Clear();

            Stream resourceStream            = null;
            string decryptedData             = null;
            bool   resourceIdentifierPresent = false;

            Exception exception = null;

            try {
                NameValueCollection queryString = context.Request.QueryString;

                string encryptedData = queryString["d"];
                if (String.IsNullOrEmpty(encryptedData))
                {
                    throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_InvalidRequest));
                }
                resourceIdentifierPresent = true;

                decryptedData = Page.DecryptString(encryptedData, Purpose.AssemblyResourceLoader_WebResourceUrl);

                int separatorIndex = decryptedData.IndexOf('|');
                Debug.Assert(separatorIndex != -1, "The decrypted data must contain a separator.");

                string assemblyName = decryptedData.Substring(0, separatorIndex);
                if (String.IsNullOrEmpty(assemblyName))
                {
                    throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_AssemblyNotFound, assemblyName));
                }

                string resourceName = decryptedData.Substring(separatorIndex + 1);
                if (String.IsNullOrEmpty(resourceName))
                {
                    throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_ResourceNotFound, resourceName));
                }

                char nameType = assemblyName[0];
                assemblyName = assemblyName.Substring(1);

                Assembly assembly = null;

                // If it was a full name, create an AssemblyName and load from that
                if (nameType == 'f')
                {
                    string[] parts = assemblyName.Split(',');

                    if (parts.Length != 4)
                    {
                        throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_InvalidRequest));
                    }

                    AssemblyName realName = new AssemblyName();
                    realName.Name    = parts[0];
                    realName.Version = new Version(parts[1]);
                    string cultureString = parts[2];

                    // Try to determine the culture, using the invariant culture if there wasn't one (doesn't work without it)
                    if (cultureString.Length > 0)
                    {
                        realName.CultureInfo = new CultureInfo(cultureString);
                    }
                    else
                    {
                        realName.CultureInfo = CultureInfo.InvariantCulture;
                    }

                    // Parse up the public key token which is represented as hex bytes in a string
                    string token      = parts[3];
                    byte[] tokenBytes = new byte[token.Length / 2];
                    for (int i = 0; i < tokenBytes.Length; i++)
                    {
                        tokenBytes[i] = Byte.Parse(token.Substring(i * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
                    }
                    realName.SetPublicKeyToken(tokenBytes);

                    assembly = Assembly.Load(realName);
                }
                // System.Web special case
                else if (nameType == 's')
                {
                    assembly = typeof(AssemblyResourceLoader).Assembly;
                }
                // If was a partial name, just try to load it
                else if (nameType == 'p')
                {
                    assembly = Assembly.Load(assemblyName);
                }
                else
                {
                    throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_InvalidRequest));
                }

                // Dev10 Bugs 602949: Throw 404 if resource not found rather than do nothing.
                // This is done before creating the cache entry, since it could be that the assembly is loaded
                // later on without the app restarting.
                if (assembly == null)
                {
                    throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_InvalidRequest));
                }

                bool   performSubstitution = false;
                bool   validResource       = false;
                string contentType         = String.Empty;

                // Check the validation cache to see if the resource has already been validated
                int     cacheKey        = HashCodeCombiner.CombineHashCodes(assembly.GetHashCode(), resourceName.GetHashCode());
                Triplet resourceTriplet = (Triplet)_webResourceCache[cacheKey];
                if (resourceTriplet != null)
                {
                    validResource       = (bool)resourceTriplet.First;
                    contentType         = (string)resourceTriplet.Second;
                    performSubstitution = (bool)resourceTriplet.Third;
                }
                else
                {
                    // Validation cache is empty, find out if it's valid and add it to the cache
                    WebResourceAttribute wra = FindWebResourceAttribute(assembly, resourceName);
                    if (wra != null)
                    {
                        resourceName        = wra.WebResource;
                        validResource       = true;
                        contentType         = wra.ContentType;
                        performSubstitution = wra.PerformSubstitution;
                    }

                    // Cache the result so we don't have to do this again
                    try {
                        if (validResource)
                        {
                            // a WebResourceAttribute was found, but does the resource really exist?
                            validResource  = false;
                            resourceStream = assembly.GetManifestResourceStream(resourceName);
                            validResource  = (resourceStream != null);
                        }
                    }
                    finally {
                        // Cache the results, even if there was an exception getting the stream,
                        // so we don't have to do this again
                        Triplet triplet = new Triplet();
                        triplet.First  = validResource;
                        triplet.Second = contentType;
                        triplet.Third  = performSubstitution;
                        _webResourceCache[cacheKey] = triplet;
                    }
                }

                if (validResource)
                {
                    // Cache the resource so we don't keep processing the same requests
                    HttpCachePolicy cachePolicy = context.Response.Cache;
                    cachePolicy.SetCacheability(HttpCacheability.Public);
                    cachePolicy.VaryByParams["d"] = true;
                    cachePolicy.SetOmitVaryStar(true);
                    cachePolicy.SetExpires(DateTime.Now + TimeSpan.FromDays(365));
                    cachePolicy.SetValidUntilExpires(true);
                    Pair assemblyInfo = GetAssemblyInfo(assembly);
                    cachePolicy.SetLastModified(new DateTime((long)assemblyInfo.Second));

                    StreamReader reader = null;
                    try {
                        if (resourceStream == null)
                        {
                            // null in the case that _webResourceCache had the item
                            resourceStream = assembly.GetManifestResourceStream(resourceName);
                        }
                        if (resourceStream != null)
                        {
                            context.Response.ContentType = contentType;

                            if (performSubstitution)
                            {
                                //
                                reader = new StreamReader(resourceStream, true);

                                string content = reader.ReadToEnd();

                                // Looking for something of the form: WebResource("resourcename")
                                MatchCollection matches    = webResourceRegex.Matches(content);
                                int             startIndex = 0;
                                StringBuilder   newContent = new StringBuilder();
                                foreach (Match match in matches)
                                {
                                    newContent.Append(content.Substring(startIndex, match.Index - startIndex));

                                    Group group = match.Groups["resourceName"];
                                    if (group != null)
                                    {
                                        string embeddedResourceName = group.ToString();
                                        if (embeddedResourceName.Length > 0)
                                        {
                                            //
                                            if (String.Equals(embeddedResourceName, resourceName, StringComparison.Ordinal))
                                            {
                                                throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_NoCircularReferences, resourceName));
                                            }
                                            newContent.Append(GetWebResourceUrlInternal(assembly, embeddedResourceName, htmlEncoded: false, forSubstitution: true, scriptManager: null));
                                        }
                                    }

                                    startIndex = match.Index + match.Length;
                                }

                                newContent.Append(content.Substring(startIndex, content.Length - startIndex));

                                StreamWriter writer = new StreamWriter(context.Response.OutputStream, reader.CurrentEncoding);
                                writer.Write(newContent.ToString());
                                writer.Flush();
                            }
                            else
                            {
                                byte[] buffer       = new byte[1024];
                                Stream outputStream = context.Response.OutputStream;
                                int    count        = 1;
                                while (count > 0)
                                {
                                    count = resourceStream.Read(buffer, 0, 1024);
                                    outputStream.Write(buffer, 0, count);
                                }
                                outputStream.Flush();
                            }
                        }
                    }
                    finally {
                        if (reader != null)
                        {
                            reader.Close();
                        }
                        if (resourceStream != null)
                        {
                            resourceStream.Close();
                        }
                    }
                }
            }
            catch (Exception e) {
                exception = e;
                // MSRC 10405: ---- all errors in the event of failure. In particular, we don't want to
                // bubble the inner exceptions up in the YSOD, as they might contain sensitive cryptographic
                // information. Setting 'resourceStream' to null will cause an appropriate exception to
                // be thrown.
                resourceStream = null;
            }

            // Dev10 Bugs 602949: 404 if the assembly is not found or if the resource does not exist
            if (resourceStream == null)
            {
                if (resourceIdentifierPresent)
                {
                    LogWebResourceFailure(decryptedData, exception);
                }
                throw new HttpException(404, SR.GetString(SR.AssemblyResourceLoader_InvalidRequest));
            }

            context.Response.IgnoreFurtherWrites();
        }
示例#28
0
        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            GetCultureFromRequest();
            InitializeGlobalContext();
            GlobalResourceManager.Initialize(HostingEnvironment.MapPath("~/App_GlobalResources/GlobalResources.xml"));

            string path = Request.Path;

            #region Remove /portals/ from query
            string constOldUrl = "/portals/";
            if (path.IndexOf(constOldUrl, StringComparison.OrdinalIgnoreCase) >= 0)
            {
                string fullPath    = Request.RawUrl;
                int    index       = fullPath.IndexOf(constOldUrl, StringComparison.OrdinalIgnoreCase);
                string begin       = fullPath.Substring(0, index);
                string end         = fullPath.Substring(index + constOldUrl.Length);
                int    endOfDomain = end.IndexOf('/');
                if (endOfDomain >= 0)
                {
                    end = end.Substring(endOfDomain + 1);
                }
                path = begin + '/' + end;

                //OZ: RewritePath чтобы работали старые клиентские инструменты
                //AK: 2009-01-26 - exclude css
                if (path.EndsWith(".css", StringComparison.OrdinalIgnoreCase))
                {
                    Response.Redirect(path, true);
                }
                else
                {
                    HttpContext.Current.RewritePath(path);
                }
            }
            #endregion

            bool pathContainsFiles  = (path.IndexOf("/files/", StringComparison.OrdinalIgnoreCase) >= 0);
            bool pathContainsWebDav = (path.IndexOf("/webdav/", StringComparison.OrdinalIgnoreCase) >= 0);

            if (!pathContainsFiles && !pathContainsWebDav &&
                (path.EndsWith("error.aspx", StringComparison.OrdinalIgnoreCase) ||
                 path.EndsWith(".css", StringComparison.OrdinalIgnoreCase) ||
                 path.EndsWith(".html", StringComparison.OrdinalIgnoreCase) ||
                 path.EndsWith("webresource.axd", StringComparison.OrdinalIgnoreCase) ||
                 path.EndsWith("scriptresource.axd", StringComparison.OrdinalIgnoreCase) ||
                 path.EndsWith("licenseexpired.aspx", StringComparison.OrdinalIgnoreCase)
                )
                )
            {
                return;
            }


            //Обработка файлов которые подвергаются кэшированию
            // TODO: перенести список строк и время жизни кеша в web.config
            if (!pathContainsFiles && !pathContainsWebDav &&
                !path.EndsWith("Reserved.ReportViewerWebControl.axd", StringComparison.OrdinalIgnoreCase) &&
                (path.EndsWith(".js", StringComparison.OrdinalIgnoreCase) ||
                 path.EndsWith(".gif", StringComparison.OrdinalIgnoreCase) ||
                 path.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) ||
                 path.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
                 path.EndsWith(".axd", StringComparison.OrdinalIgnoreCase)
                )
                )
            {
                HttpCachePolicy cache = HttpContext.Current.Response.Cache;
                //HttpContext.Current.Response.AddFileDependency(Server.MapPath(path));
                bool _hanldeFlag = true;

                //Вид кэширования (включает возможность кэширования на прокси)
                cache.SetCacheability(HttpCacheability.Public);

                //кэширование по параметрам в QueryString (d, versionUid)
                //все запросы включающие любой из этих параметров будут кешироваться по значению параметра
                cache.VaryByParams["d"]          = true;
                cache.VaryByParams["versionUid"] = true;
                cache.SetOmitVaryStar(true);

                //устанавливаем срок годности закэшированого файла
                //Можно сделать для разных типов фалов - разные сроки хранения
                double cacheExpires = 1;
                if (System.Configuration.ConfigurationManager.AppSettings["ClientCache"] != null)
                {
                    cacheExpires = Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["ClientCache"], CultureInfo.InvariantCulture);
                }
                cache.SetExpires(DateTime.Now + TimeSpan.FromMinutes(cacheExpires));
                //cache.SetMaxAge(TimeSpan.FromSeconds(259200));


                //разрешаем хранить кэш на диске
                cache.SetAllowResponseInBrowserHistory(true);
                cache.SetValidUntilExpires(true);

#if (DEBUG)
                cache.SetExpires(DateTime.Now);
                cache.SetAllowResponseInBrowserHistory(false);
#endif

                DateTime dtRequest = DateTime.MinValue;

#if (!DEBUG)
                //проверка даты модификации файла
                if (File.Exists(Server.MapPath(path)))
                {
                    cache.SetLastModified(File.GetLastWriteTime(Server.MapPath(path)).ToUniversalTime());

                    //Не удалять(!) Включает режим более строгово кеширования
                    //Кэшеирует файлы даже после рестарта IIS, вернусь после отпуска протестирую и включу (dvs)

                    if (HttpContext.Current.Request.Headers["If-Modified-Since"] != null)
                    {
                        try
                        {
                            dtRequest = Convert.ToDateTime(HttpContext.Current.Request.Headers["If-Modified-Since"], CultureInfo.InvariantCulture);
                        }
                        catch
                        {
                        }

                        //если файл существует и его дата модификации совпадает с версией на клиенте то возвращаем 304, в противном случае
                        //обрабатывать данный запрос будет дефолтный хэндлер ASP.NET (подробнее см. System.Web.Cachig.OutputCacheModule)
                        if (File.GetLastWriteTime(Server.MapPath(path)).ToUniversalTime().ToString("r") == dtRequest.ToUniversalTime().ToString("r"))
                        {
                            //Если отладка загрузки скриптов включена, то не кэшируем их
                            if ((path.EndsWith(".js", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".axd", StringComparison.OrdinalIgnoreCase)) && Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["LogSriptLoading"], CultureInfo.InvariantCulture))
                            {
                                cache.SetExpires(DateTime.Now);
                            }
                            else
                            {
                                Response.ClearContent();
                                Response.StatusCode = 304;
                                _hanldeFlag         = false;
                            }
                        }
                    }
                }
#endif

                if (_hanldeFlag)
                {
                    return;
                }
            }
            else
            {
                //25.02.2009 et: Не выполнять проверку для WebDav запросов
                if (!pathContainsFiles && !pathContainsWebDav)
                {
                    if (path.IndexOf('\\') >= 0 || System.IO.Path.GetFullPath(Request.PhysicalPath) != Request.PhysicalPath)
                    {
                        throw new HttpException(404, "not found");
                    }
                }

                InitializeDatabase();                 // Terminates request if error occurs.

                //AK 2009-01-16
                if (!PortalConfig.SystemIsActive)
                {
                    if (Request.AppRelativeCurrentExecutionFilePath.Equals("~/default.aspx", StringComparison.OrdinalIgnoreCase))
                    {
                        return;
                    }
                    else
                    {
                        Response.Redirect("~/default.aspx", true);
                    }
                }

                //Init TemplateResolver
                TemplateResolver.Current = new TemplateResolver();

                TemplateResolver.Current.AddSource("QueryString", new TemplateSource(HttpContext.Current.Request.QueryString));

                if (HttpContext.Current.Session != null)
                {
                    TemplateResolver.Current.AddSource("Session", new TemplateSource(HttpContext.Current.Session));
                }

                TemplateResolver.Current.AddSource("HttpContext", new TemplateSource(HttpContext.Current.Items));
                TemplateResolver.Current.AddSource("DataContext", new TemplateSource(DataContext.Current.Attributes));

                TemplateResolver.Current.AddSource("DateTime", new DateTimeTemplateSource());
                TemplateResolver.Current.AddSource("Security", new Mediachase.Ibn.Data.Services.SecurityTemplateSource());

                TemplateResolver.Current.AddSource("TimeTrackingSecurity", new Mediachase.IbnNext.TimeTracking.TimeTrackingSecurityTemplateSource());

                //Init PathTemplateResolver
                PathTemplateResolver.Current = new PathTemplateResolver();

                PathTemplateResolver.Current.AddSource("QueryString", new PathTemplateSource(HttpContext.Current.Request.QueryString));

                if (HttpContext.Current.Session != null)
                {
                    PathTemplateResolver.Current.AddSource("Session", new PathTemplateSource(HttpContext.Current.Session));
                }

                PathTemplateResolver.Current.AddSource("HttpContext", new PathTemplateSource(HttpContext.Current.Items));
                PathTemplateResolver.Current.AddSource("DataContext", new PathTemplateSource(DataContext.Current.Attributes));

                PathTemplateResolver.Current.AddSource("DateTime", new Mediachase.Ibn.Web.UI.Controls.Util.DateTimePathTemplateSource());
                PathTemplateResolver.Current.AddSource("Security", new Mediachase.Ibn.Web.UI.Controls.Util.SecurityPathTemplateSource());

                //PathTemplateResolver.Current.AddSource("TimeTrackingSecurity", new Mediachase.IbnNext.TimeTracking.TimeTrackingSecurityTemplateSource());

                // O.R. [2009-07-28]: Check license and .NET Framework version
                if (Configuration.WorkflowModule && WorkflowActivityWrapper.IsFramework35Installed())
                {
                    GlobalWorkflowRuntime.StartRuntime(DataContext.Current.SqlContext.ConnectionString);
                }
            }
        }
示例#29
0
 /// <summary>
 ///     Sets the Last-Modified HTTP header to the <see cref="T:System.DateTime" /> value supplied.
 /// </summary>
 /// <param name="date">The new <see cref="T:System.DateTime" /> value for the Last-Modified header. </param>
 /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="date" /> is later than the current DateTime. </exception>
 public void SetLastModified(DateTime date)
 {
     policy.SetLastModified(date);
 }
        void SetCacheFromCacheProfile()
        {
            HttpCachePolicy cache = HttpContext.Current.Response.Cache;

            if (this.cacheProfile.NoStore)
            {
                cache.SetNoStore();
            }

            // Location is not required to be set in the config.  The default is Any,
            // but if it is not set in the config the value will be -1.  So must correct for this.
            if ((int)(this.cacheProfile.Location) == -1)
            {
                cache.SetCacheability(HttpCacheability.Public);
            }
            else
            {
                switch (this.cacheProfile.Location)
                {
                case OutputCacheLocation.Any:
                    cache.SetCacheability(HttpCacheability.Public);
                    break;

                case OutputCacheLocation.Client:
                    cache.SetCacheability(HttpCacheability.Private);
                    break;

                case OutputCacheLocation.Downstream:
                    cache.SetCacheability(HttpCacheability.Public);
                    cache.SetNoServerCaching();
                    break;

                case OutputCacheLocation.None:
                    cache.SetCacheability(HttpCacheability.NoCache);
                    break;

                case OutputCacheLocation.Server:
                    cache.SetCacheability(HttpCacheability.ServerAndNoCache);
                    break;

                case OutputCacheLocation.ServerAndClient:
                    cache.SetCacheability(HttpCacheability.ServerAndPrivate);
                    break;

                default:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR2.GetString(SR2.CacheProfileLocationNotSupported, this.cacheProfile.Location)));
                }
            }

            if (this.cacheProfile.Location != OutputCacheLocation.None)
            {
                cache.SetExpires(HttpContext.Current.Timestamp.AddSeconds((double)this.cacheProfile.Duration));
                cache.SetMaxAge(new TimeSpan(0, 0, this.cacheProfile.Duration));
                cache.SetValidUntilExpires(true);
                cache.SetLastModified(HttpContext.Current.Timestamp);

                if (this.cacheProfile.Location != OutputCacheLocation.Client)
                {
                    if (!string.IsNullOrEmpty(this.cacheProfile.VaryByContentEncoding))
                    {
                        foreach (string contentEncoding in this.cacheProfile.VaryByContentEncoding.Split(seperatorChar))
                        {
                            cache.VaryByContentEncodings[contentEncoding.Trim()] = true;
                        }
                    }

                    if (!string.IsNullOrEmpty(this.cacheProfile.VaryByHeader))
                    {
                        foreach (string header in this.cacheProfile.VaryByHeader.Split(seperatorChar))
                        {
                            cache.VaryByHeaders[header.Trim()] = true;
                        }
                    }

                    if (this.cacheProfile.Location != OutputCacheLocation.Downstream)
                    {
                        if (!string.IsNullOrEmpty(this.cacheProfile.VaryByCustom))
                        {
                            cache.SetVaryByCustom(this.cacheProfile.VaryByCustom);
                        }

                        if (!string.IsNullOrEmpty(this.cacheProfile.VaryByParam))
                        {
                            foreach (string parameter in cacheProfile.VaryByParam.Split(seperatorChar))
                            {
                                cache.VaryByParams[parameter.Trim()] = true;
                            }
                        }

                        if (!string.IsNullOrEmpty(this.cacheProfile.SqlDependency))
                        {
                            CacheDependency cacheDependency = this.CreateSingleCacheDependency(cacheProfile.SqlDependency);
                            HttpContext.Current.Response.AddCacheDependency(new CacheDependency[] { cacheDependency });
                        }
                    }
                }
            }
        }