public string GetCompositeScript(string[] urls) {
     var script = new StringBuilder();
     IHttpHandler handler = new ScriptResourceHandler();
     var absoluteUri = Page.Request.Url.AbsoluteUri;
     var fileNameIndex = absoluteUri.LastIndexOf(Page.Request.Url.Segments[2]);
     var scriptResourcePath = absoluteUri.Substring(0, fileNameIndex) + "ScriptResource.axd";
     foreach(var url in urls) {
         // Is script resource-based?
         if (url.IndexOf("/scriptresource.axd", StringComparison.OrdinalIgnoreCase) != -1) {
             var queryStringIndex = url.IndexOf('?');
             var queryString = url.Substring(queryStringIndex + 1);
             var request = new HttpRequest("scriptresource.axd", scriptResourcePath, queryString);
             using (var textWriter = new StringWriter(script)) {
                 HttpResponse response = new HttpResponse(textWriter);
                 HttpContext context = new HttpContext(request, response);
                 handler.ProcessRequest(context);
             }
             script.AppendLine();
         }
         else {
             using (var textReader = new StreamReader(Page.Server.MapPath(url), true)) {
                 script.AppendLine(textReader.ReadToEnd());
             }
         }
     }
     script.AppendLine("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");
     return script.ToString();
 }
Ejemplo n.º 2
0
            string PerformSubstitutionReplace(Match m)
            {
                string resourceName = m.Groups [1].Value;

#if SYSTEM_WEB_EXTENSIONS
                return(ScriptResourceHandler.GetResourceUrl(_assembly, resourceName, false));
#else
                return(AssemblyResourceLoader.GetResourceUrl(_assembly, resourceName, false));
#endif
            }
Ejemplo n.º 3
0
        private static bool ShouldSkipAuthorization(HttpContext context)
        {
            if (context == null || context.Request == null)
            {
                return(false);
            }

            string path = context.Request.FilePath;

            if (ScriptResourceHandler.IsScriptResourceRequest(path))
            {
                return(true);
            }

            // if auth service is disabled, dont bother checking.
            // (NOTE: if a custom webservice is used, it will be up to them to enable anon access to it)
            // if it isn't a rest request dont bother checking.
            if (!ApplicationServiceHelper.AuthenticationServiceEnabled || !RestHandlerFactory.IsRestRequest(context))
            {
                return(false);
            }

            if (context.SkipAuthorization)
            {
                return(true);
            }

            // it may be a rest request to a webservice. It must end in axd if it is an app service.
            if ((path == null) || !path.EndsWith(".axd", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            // WebServiceData caches the object in cache, so this should be a quick lookup.
            // If it hasnt been cached yet, this will cause it to be cached, so later in the request
            // it will be a cache-hit anyway.
            WebServiceData wsd = WebServiceData.GetWebServiceData(context, path, false, false);

            if ((wsd != null) && (_authenticationServiceType == wsd.TypeData.Type))
            {
                return(true);
            }

            return(false);
        }
        public void ProcessRequest(HttpContext context)
        {
            bool shouldProcessRequest = true;
            string[] scriptKeys = null;
            string keys = context.Server.UrlDecode(context.Request.Params["keys"]);
            string scriptResourcePath = String.Empty;
            ScriptManager objScriptManager = new ScriptManager();
            StringBuilder scriptBuilder = new StringBuilder();
            IHttpHandler handler = new ScriptResourceHandler();
            ///StringCollection _gescHdrStatus = new StringCollection();

            if (String.IsNullOrEmpty(keys) || keys.Equals("-1")) shouldProcessRequest = false;

            if (shouldProcessRequest)
            {
                Dictionary<string, string> _scriptContents = null;
                try
                {
                    _scriptContents = (Dictionary<string, string>)HttpContext.Current.Cache["ScriptContents"];
                }
                catch (Exception ex) { }

                scriptKeys = keys.Split('.');
                ///_gescHdrStatus.Add("incount:" + scripts.Length.ToString()); //script count
                scriptResourcePath = string.Format("{0}{1}{2}{3}{4}{5}{6}{7}", context.Request.Url.Scheme, "://", context.Request.Url.Host, ":", context.Request.Url.Port, "/", context.Request.ApplicationPath, "/ScriptResource.axd");
                scriptResourcePath = scriptResourcePath.Replace("///", "/");
                foreach (string key in scriptKeys)
                {
                    ScriptElement element = OptimizerConfig.GetScriptByKey(key);
                    if (element == null) continue;

                    #region Generating resource url dynamically and creating WebRequest object to extract stream of script

                    if (element != null)
                    {
                        ScriptReference reference = null;
                        bool isPathBased = false;
                        if (element.Path.Length > 0)
                        {
                            reference = new ScriptReference(element.Path);
                            isPathBased = true;
                        }
                        else if (element.Assembly.Length > 0 && element.Name.Length > 0)
                        {
                            reference = new ScriptReference(element.Name, element.Assembly);
                        }
                        try
                        {
                            OptimizeScriptReference openReference = new OptimizeScriptReference(reference);
                            string url = string.Empty;
                            if (!isPathBased)
                            {
                                url = context.Request.Url.OriginalString.Replace(context.Request.RawUrl, "") + openReference.GetUrl(objScriptManager);
                                var queryStringIndex = url.IndexOf('?');
                                var queryString = url.Substring(queryStringIndex + 1);
                                var request = new HttpRequest("scriptresource.axd", scriptResourcePath, queryString);

                                using (StringWriter textWriter = new StringWriter(scriptBuilder))
                                {
                                    try
                                    {
                                        //HttpResponse response = new HttpResponse(textWriter);
                                        //HttpContext ctx = new HttpContext(request, response);
                                        //handler.ProcessRequest(ctx); //raising error in .Net 2.0
                                        if (_scriptContents.ContainsKey(key))
                                        {
                                            scriptBuilder.Append(_scriptContents[key]);
                                        }
                                    }
                                    catch (Exception ctxEx)
                                    {
                                    }
                                }
                            }
                            else
                            {
                                string absolutePath = OptimizerHelper.GetAbsolutePath(element);
                                if (OptimizerHelper.IsAbsolutePathExists(absolutePath))
                                {
                                    using (StreamReader objJsReader = new StreamReader(absolutePath, true))
                                    {
                                        scriptBuilder.Append(objJsReader.ReadToEnd());
                                    }
                                }
                            }
                            scriptBuilder.AppendLine();
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                    #endregion
                }
            }

            objScriptManager = null;

            #region Writing combine output scripts to the Response.OutputStream

            context.Response.Clear();
            context.Response.ContentType = "application/x-javascript";

            try
            {
                SetResponseCache(context.Response);
                scriptBuilder.AppendLine();
                //scriptBuilder.AppendLine("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");
                string combinedScripts = scriptBuilder.ToString();

                if (shouldProcessRequest)
                {
                    if (OptimizerConfig.EnableScriptMinification)
                    {
                        combinedScripts = JsMinifier.GetMinifiedCode(combinedScripts);
                    }

                    string encodingTypes = string.Empty;
                    string compressionType = "none";
                    if (OptimizerConfig.EnableScriptCompression)
                    {
                        encodingTypes = context.Request.Headers["Accept-Encoding"];

                        if (!string.IsNullOrEmpty(encodingTypes))
                        {
                            encodingTypes = encodingTypes.ToLower();
                            if (context.Request.Browser.Browser == "IE")
                            {
                                if (context.Request.Browser.MajorVersion < 6)
                                    compressionType = "none";
                                else if (context.Request.Browser.MajorVersion == 6 && !string.IsNullOrEmpty(context.Request.ServerVariables["HTTP_USER_AGENT"]) && context.Request.ServerVariables["HTTP_USER_AGENT"].Contains("EV1"))
                                    compressionType = "none";
                            }
                            if ((encodingTypes.Contains("gzip") || encodingTypes.Contains("x-gzip") || encodingTypes.Contains("*")))
                                compressionType = "gzip";
                            else if (encodingTypes.Contains("deflate"))
                                compressionType = "deflate";
                        }
                    }
                    else
                    {
                        compressionType = "none";
                    }
                    if (compressionType == "gzip")
                    {
                        using (MemoryStream stream = new MemoryStream())
                        {
                            using (StreamWriter writer = new StreamWriter(new GZipStream(stream, CompressionMode.Compress), Encoding.UTF8))
                            {
                                writer.Write(combinedScripts);
                            }
                            byte[] buffer = stream.ToArray();
                            context.Response.AddHeader("Content-encoding", "gzip");
                            context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                        }
                    }
                    else if (compressionType == "deflate")
                    {
                        using (MemoryStream stream = new MemoryStream())
                        {
                            using (StreamWriter writer = new StreamWriter(new DeflateStream(stream, CompressionMode.Compress), Encoding.UTF8))
                            {
                                writer.Write(combinedScripts);
                            }
                            byte[] buffer = stream.ToArray();
                            context.Response.AddHeader("Content-encoding", "deflate");
                            context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                        }
                    }
                    else
                    {
                        //no compression plain text...
                        context.Response.AddHeader("Content-Length", combinedScripts.Length.ToString());
                        context.Response.Write(combinedScripts);
                    }
                }
                scriptBuilder = null;
            }
            catch (Exception ex)
            {
                context.Response.Write(ex.ToString().Replace("\n", "<br>"));
            }
            #endregion
        }