Example #1
0
 private static WebResourceAttribute FindWebResourceAttribute(Assembly assembly, string resourceName)
 {
     object[] customAttributes = assembly.GetCustomAttributes(false);
     for (int i = 0; i < customAttributes.Length; i++)
     {
         WebResourceAttribute attribute = customAttributes[i] as WebResourceAttribute;
         if ((attribute != null) && string.Equals(attribute.WebResource, resourceName, StringComparison.Ordinal))
         {
             return(attribute);
         }
     }
     return(null);
 }
Example #2
0
        public ActionResult Index(string innerUrl)
        {
            Assembly             assembly  = Assembly.GetExecutingAssembly();
            string               location  = "L24CM." + innerUrl.Replace("/", ".");
            WebResourceAttribute attribute = assembly.GetCustomAttributes(true)
                                             .OfType <WebResourceAttribute>()
                                             .FirstOrDefault(wra => wra.WebResource == location);
            string contentType = (attribute == null ? "text/plain" : attribute.ContentType);

            Stream stream = assembly.GetManifestResourceStream(location);

            return(File(stream, contentType));
        }
 private static WebResourceAttribute FindWebResourceAttribute(Assembly assembly, string resourceName)
 {
     object[] attrs = assembly.GetCustomAttributes(false);
     for (int i = 0; i < attrs.Length; i++)
     {
         WebResourceAttribute wra = attrs[i] as WebResourceAttribute;
         if ((wra != null) && String.Equals(wra.WebResource, resourceName, StringComparison.Ordinal))
         {
             return(wra);
         }
     }
     return(null);
 }
Example #4
0
        private static string GetCdnPath(string resourceName, Assembly assembly, bool secureConnection)
        {
            string str = null;
            WebResourceAttribute attribute = FindWebResourceAttribute(assembly, resourceName);

            if (attribute != null)
            {
                str = secureConnection ? attribute.CdnPathSecureConnection : attribute.CdnPath;
                if (!string.IsNullOrEmpty(str))
                {
                    str = FormatCdnUrl(assembly, str);
                }
            }
            return(str);
        }
        private static string GetCdnPath(string resourceName, Assembly assembly, bool secureConnection)
        {
            string cdnPath           = null;
            WebResourceAttribute wra = FindWebResourceAttribute(assembly, resourceName);

            if (wra != null)
            {
                cdnPath = secureConnection ? wra.CdnPathSecureConnection : wra.CdnPath;
                if (!String.IsNullOrEmpty(cdnPath))
                {
                    cdnPath = FormatCdnUrl(assembly, cdnPath);
                }
            }
            return(cdnPath);
        }
Example #6
0
        public ActionResult GetAssemblyResource(string assemblyName, string resourceName)
        {
            Assembly asm;

            if (Utils.TryFindAssembly(assemblyName, out asm))
            {
                WebResourceAttribute attr = asm.GetCustomAttributes(typeof(WebResourceAttribute), false).Cast <WebResourceAttribute>().SingleOrDefault(x => x.PublicResourceName == resourceName);
                if (attr != null)
                {
                    string mime;
                    mimeMap.TryGetValue(Path.GetExtension(resourceName).ToLowerInvariant(), out mime);

                    return(File(asm.GetManifestResourceStream(attr.ResourceQualifiedName), mime ?? "application/octet-stream"));
                }
            }
            throw new HttpException(404, "File not found");
        }
Example #7
0
        void System.Web.IHttpHandler.ProcessRequest(HttpContext context)
#endif
        {
            HttpRequest  request  = context.Request;
            HttpResponse response = context.Response;
            string       resourceName;
            string       asmName;
            Assembly     assembly;

            DecryptAssemblyResource(request.QueryString ["d"], out asmName, out resourceName);
            if (resourceName == null)
            {
                throw new HttpException(404, "No resource name given");
            }

            if (asmName == null || asmName == "s")
            {
                assembly = currAsm;
            }
            else
            {
                assembly = Assembly.Load(asmName);
            }

            WebResourceAttribute wra = null;

            WebResourceAttribute [] attrs = (WebResourceAttribute [])assembly.GetCustomAttributes(typeof(WebResourceAttribute), false);
            for (int i = 0; i < attrs.Length; i++)
            {
                if (attrs [i].WebResource == resourceName)
                {
                    wra = attrs [i];
                    break;
                }
            }
#if SYSTEM_WEB_EXTENSIONS
            if (wra == null && resourceName.Length > 9 && resourceName.EndsWith(".debug.js", StringComparison.OrdinalIgnoreCase))
            {
                resourceName = String.Concat(resourceName.Substring(0, resourceName.Length - 9), ".js");
                for (int i = 0; i < attrs.Length; i++)
                {
                    if (attrs [i].WebResource == resourceName)
                    {
                        wra = attrs [i];
                        break;
                    }
                }
            }
#endif
            if (wra == null)
            {
                throw new HttpException(404, String.Concat("Resource ", resourceName, " not found"));
            }

            string req_cache = request.Headers ["Cache-Control"];
            if (req_cache == "max-age=0")
            {
                long atime;
#if NET_2_0
                if (Int64.TryParse(request.QueryString ["t"], out atime))
                {
#else
                atime = -1;
                try {
                    atime = Int64.Parse(request.QueryString ["t"]);
                }
                catch {}
                if (atime > -1)
                {
#endif
                    if (atime == File.GetLastWriteTimeUtc(assembly.Location).Ticks)
                    {
                        response.Clear();
                        response.StatusCode   = 304;
                        response.ContentType  = null;
                        response.CacheControl = "public";                         // easier to set it to public as MS than remove it
                        context.ApplicationInstance.CompleteRequest();
                        return;
                    }
                }
            }
            string modif_since = request.Headers ["If-Modified-Since"];
            if (modif_since != null && modif_since != "")
            {
                try {
                    DateTime modif;
#if NET_2_0
                    if (DateTime.TryParseExact(modif_since, "r", null, 0, out modif))
#else
                    modif = DateTime.MinValue;
                    try {
                        modif = DateTime.ParseExact(modif_since, "r", null, 0);
                    } catch { }
                    if (modif != DateTime.MinValue)
#endif
                    { if (File.GetLastWriteTimeUtc(assembly.Location) <= modif)
                      {
                          response.Clear();
                          response.StatusCode   = 304;
                          response.ContentType  = null;
                          response.CacheControl = "public";                               // easier to set it to public as MS than remove it
                          context.ApplicationInstance.CompleteRequest();
                          return;
                      }
                    }
                } catch {}
            }

            response.ContentType = wra.ContentType;

            DateTime utcnow = DateTime.UtcNow;
            response.Headers.Add("Last-Modified", utcnow.ToString("r"));
            response.ExpiresAbsolute = utcnow.AddYears(1);
            response.CacheControl    = "public";

            Stream s = assembly.GetManifestResourceStream(resourceName);
            if (s == null)
            {
                throw new HttpException(404, String.Concat("Resource ", resourceName, " not found"));
            }

            if (wra.PerformSubstitution)
            {
                using (StreamReader r = new StreamReader(s)) {
                    TextWriter w = response.Output;
                    new PerformSubstitutionHelper(assembly).PerformSubstitution(r, w);
                }
#if NET_2_0
            }
            else if (response.OutputStream is HttpResponseStream)
            {
                UnmanagedMemoryStream st      = (UnmanagedMemoryStream)s;
                HttpResponseStream    hstream = (HttpResponseStream)response.OutputStream;
                unsafe {
                    hstream.WritePtr(new IntPtr(st.PositionPointer), (int)st.Length);
                }
#endif
            }
            else
            {
                byte [] buf    = new byte [1024];
                Stream  output = response.OutputStream;
                int     c;
                do
                {
                    c = s.Read(buf, 0, 1024);
                    output.Write(buf, 0, c);
                } while (c > 0);
            }
#if SYSTEM_WEB_EXTENSIONS
            TextWriter writer = response.Output;
            foreach (ScriptResourceAttribute sra in assembly.GetCustomAttributes(typeof(ScriptResourceAttribute), false))
            {
                if (sra.ScriptName == resourceName)
                {
                    string      scriptResourceName = sra.ScriptResourceName;
                    ResourceSet rset = null;
                    try {
                        rset = new ResourceManager(scriptResourceName, assembly).GetResourceSet(Threading.Thread.CurrentThread.CurrentUICulture, true, true);
                    }
                    catch (MissingManifestResourceException) {
#if TARGET_JVM // GetResourceSet does not throw  MissingManifestResourceException if ressource is not exists
                    }
                    if (rset == null)
                    {
#endif
                        if (scriptResourceName.EndsWith(".resources"))
                        {
                            scriptResourceName = scriptResourceName.Substring(0, scriptResourceName.Length - 10);
                            rset = new ResourceManager(scriptResourceName, assembly).GetResourceSet(Threading.Thread.CurrentThread.CurrentUICulture, true, true);
                        }
#if !TARGET_JVM
                        else
                        {
                            throw;
                        }
#endif
                    }
                    if (rset == null)
                    {
                        break;
                    }
                    writer.WriteLine();
                    string ns   = sra.TypeName;
                    int    indx = ns.LastIndexOf('.');
                    if (indx > 0)
                    {
                        writer.WriteLine("Type.registerNamespace('" + ns.Substring(0, indx) + "')");
                    }
                    writer.Write("{0}={{", sra.TypeName);
                    bool first = true;
                    foreach (DictionaryEntry entry in rset)
                    {
                        string value = entry.Value as string;
                        if (value != null)
                        {
                            if (first)
                            {
                                first = false;
                            }
                            else
                            {
                                writer.Write(',');
                            }
                            writer.WriteLine();
                            writer.Write("{0}:{1}", GetScriptStringLiteral((string)entry.Key), GetScriptStringLiteral(value));
                        }
                    }
                    writer.WriteLine();
                    writer.WriteLine("};");
                    break;
                }
            }

            bool notifyScriptLoaded = request.QueryString ["n"] == "t";
            if (notifyScriptLoaded)
            {
                writer.WriteLine();
                writer.WriteLine("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");
            }
#endif
        }
Example #8
0
        void SendEmbeddedResource(HttpContext context, out EmbeddedResource res, out Assembly assembly)
        {
            HttpRequest         request     = context.Request;
            NameValueCollection queryString = request.QueryString;

            // val is URL-encoded, which means every + has been replaced with ' ', we
            // need to revert that or the base64 conversion will fail.
            string d = queryString ["d"];

            if (!String.IsNullOrEmpty(d))
            {
                d = d.Replace(' ', '+');
            }

            AssemblyEmbeddedResources entry;

            res = DecryptAssemblyResource(d, out entry);
            WebResourceAttribute wra = res != null ? res.Attribute : null;

            if (wra == null)
            {
                throw new HttpException(404, "Resource not found");
            }

            if (entry.AssemblyName == "s")
            {
                assembly = currAsm;
            }
            else
            {
                assembly = Assembly.Load(entry.AssemblyName);
            }

            long atime;

            if (HasCacheControl(request, queryString, out atime))
            {
                if (atime == File.GetLastWriteTimeUtc(assembly.Location).Ticks)
                {
                    RespondWithNotModified(context);
                    return;
                }
            }

            DateTime modified;

            if (HasIfModifiedSince(request, out modified))
            {
                if (File.GetLastWriteTimeUtc(assembly.Location) <= modified)
                {
                    RespondWithNotModified(context);
                    return;
                }
            }

            HttpResponse response = context.Response;

            response.ContentType = wra.ContentType;

            DateTime utcnow = DateTime.UtcNow;

            response.Headers.Add("Last-Modified", utcnow.ToString("r"));
            response.ExpiresAbsolute = utcnow.AddYears(1);
            response.CacheControl    = "public";

            Stream s = assembly.GetManifestResourceStream(res.Name);

            if (s == null)
            {
                throw new HttpException(404, "Resource " + res.Name + " not found");
            }

            if (wra.PerformSubstitution)
            {
                using (StreamReader r = new StreamReader(s)) {
                    TextWriter w = response.Output;
                    new PerformSubstitutionHelper(assembly).PerformSubstitution(r, w);
                }
            }
            else if (response.OutputStream is HttpResponseStream)
            {
                UnmanagedMemoryStream st      = (UnmanagedMemoryStream)s;
                HttpResponseStream    hstream = (HttpResponseStream)response.OutputStream;
                unsafe {
                    hstream.WritePtr(new IntPtr(st.PositionPointer), (int)st.Length);
                }
            }
            else
            {
                byte [] buf    = new byte [1024];
                Stream  output = response.OutputStream;
                int     c;
                do
                {
                    c = s.Read(buf, 0, 1024);
                    output.Write(buf, 0, c);
                } while (c > 0);
            }
        }
Example #9
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine(@"
Utility to extract embedded script resources (libraries) to disk version " +
                                  typeof(Program).Assembly.GetName().Version.ToString());
                Console.WriteLine(@"Copyright (c) Microsoft Corporation 2008.");
                Console.WriteLine(@"All rights reserved.");
                Console.WriteLine();
                Console.WriteLine(@"Run 'ExtractJsFromAssembly -?' for a list of valid options.");
                return;
            }
            if ((args[0].Length == 2) &&
                ((args[0][0] == '-') || (args[0][0] == '/')) &&
                ((args[0][1] == '?') || (args[0][1] == 'h')))
            {
                Console.WriteLine(@"
Utility to extract embedded script resources (libraries) to disk.
Copyright (C) Microsoft Corporation 2008.
All rights reserved.

Usage:
------
ExtractJsFromAssembly -?
    Prints this help text.

ExtractJsFromAssembly [-v] assemblyPath outputPath
    Extracts all script resources from an assembly.

    -v            If specified, does not include the file version in the
                  output path. Use this option for ASP.NET 2.0 assemblies.
    assemblyPath  The path to the assembly from which to extract embedded
                  script resources from. This includes the assembly name.
    outputPath    The path to the root folder into which the embedded
                  script resources will be extracted.
                  Note that the tool will create a folder structure under
                  this root.

Example:
--------
    extractjsfromassembly customassembly.dll scripts
");
                return;
            }

            string assemblyPath, outputPath;
            bool   outputVersion = !((args[0].Length == 2) &&
                                     ((args[0][0] == '-') || (args[0][0] == '/')) &&
                                     (args[0][1] == 'v'));

            if ((outputVersion && (args.Length != 2)) ||
                (!outputVersion && (args.Length != 3)))
            {
                Console.WriteLine("Invalid number of arguments.");
                return;
            }

            if (outputVersion)
            {
                assemblyPath = args[0];
                outputPath   = args[1];
            }
            else
            {
                assemblyPath = args[1];
                outputPath   = args[2];
            }

            try {
                assemblyPath = Path.GetFullPath(assemblyPath);
            }
            catch (ArgumentException) {
                WriteAssemblyPathError();
                return;
            }
            catch (SecurityException) {
                WriteAssemblyPathError();
                return;
            }
            catch (NotSupportedException) {
                WriteAssemblyPathError();
                return;
            }
            catch (PathTooLongException) {
                WriteAssemblyPathError();
                return;
            }

            Assembly assembly;

            try {
                assembly = Assembly.LoadFrom(assemblyPath);
            }
            catch (FileNotFoundException) {
                WriteAssemblyLoadError();
                return;
            }
            catch (FileLoadException) {
                WriteAssemblyLoadError();
                return;
            }
            catch (BadImageFormatException) {
                WriteAssemblyLoadError();
                return;
            }
            catch (SecurityException) {
                WriteAssemblyLoadError();
                return;
            }
            catch (PathTooLongException) {
                WriteAssemblyLoadError();
                return;
            }

            List <CultureInfo> cultures = new List <CultureInfo>();

            cultures.Add(CultureInfo.InvariantCulture);
            foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes.AllCultures))
            {
                try {
                    assembly.GetSatelliteAssembly(culture);
                    cultures.Add(culture);
                }
                catch (FileLoadException) { }
                catch (FileNotFoundException) { }
            }

            try {
                outputPath = Path.GetFullPath(outputPath);
            }
            catch (ArgumentException) {
                WriteOutputPathError();
                return;
            }
            catch (SecurityException) {
                WriteOutputPathError();
                return;
            }
            catch (NotSupportedException) {
                WriteOutputPathError();
                return;
            }
            catch (PathTooLongException) {
                WriteOutputPathError();
                return;
            }
            EnsureDirectory(outputPath);

            if (assembly != null)
            {
                // Create the name and version directories
                AssemblyName assemblyName = assembly.GetName();
                outputPath = Path.Combine(outputPath, assemblyName.Name);
                EnsureDirectory(outputPath);
                outputPath = Path.Combine(outputPath, assemblyName.Version.ToString());
                EnsureDirectory(outputPath);

                string fileVersion = null;
                // Get the assembly file version
                AssemblyFileVersionAttribute[] attributes =
                    (AssemblyFileVersionAttribute[])assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false);
                if (attributes.Length > 0)
                {
                    fileVersion = attributes[0].Version;
                    if (String.IsNullOrEmpty(fileVersion))
                    {
                        fileVersion = "0.0.0.0";
                    }
                }
                else
                {
                    fileVersion = "0.0.0.0";
                }
                if (outputVersion)
                {
                    outputPath = Path.Combine(outputPath, fileVersion);
                    EnsureDirectory(outputPath);
                }

                // Find the neutral resource language for the assembly
                object[]    attrs = assembly.GetCustomAttributes(typeof(NeutralResourcesLanguageAttribute), true);
                CultureInfo assemblyDefaultCulture = CultureInfo.InvariantCulture;
                if (attrs.Length != 0)
                {
                    assemblyDefaultCulture =
                        new CultureInfo(((NeutralResourcesLanguageAttribute)attrs[0]).CultureName);
                    Console.WriteLine();
                    Console.WriteLine("Default assembly culture: " + assemblyDefaultCulture);
                }
                else
                {
                    Console.WriteLine();
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("* WARNING * Assembly doesn't define the neutral culture of the resources, which may result in localized script files not being created. Please add a NeutralResourcesLanguageAttribute to the assembly.");
                    Console.ResetColor();
                }

                // Set up the list of resource infos
                Dictionary <string, ScriptResourceInfo> scriptResourceInfos =
                    new Dictionary <string, ScriptResourceInfo>();
                attrs = assembly.GetCustomAttributes(true);
                for (int i = 0; i < attrs.Length; i++)
                {
                    object attr     = attrs[i];
                    Type   attrType = attr.GetType();
                    if (attrType.Name.IndexOf("ScriptResourceAttribute") != -1)
                    {
                        PropertyInfo scriptNameProperty         = attrType.GetProperty("ScriptName");
                        string       scriptName                 = (string)scriptNameProperty.GetValue(attr, null);
                        PropertyInfo scriptResourceNameProperty = attrType.GetProperty("ScriptResourceName");
                        string       scriptResourceName         = (string)scriptResourceNameProperty.GetValue(attr, null);
                        PropertyInfo typeNameProperty           = attrType.GetProperty("TypeName");
                        string       typeName = (string)typeNameProperty.GetValue(attr, null);
                        scriptResourceInfos.Add(scriptName,
                                                new ScriptResourceInfo(scriptName, scriptResourceName, typeName));
                    }
                }
                // Also create entries for web resources that are not localized
                attrs = assembly.GetCustomAttributes(typeof(WebResourceAttribute), true);
                for (int i = 0; i < attrs.Length; i++)
                {
                    WebResourceAttribute wra = (WebResourceAttribute)attrs[i];
                    if ((wra != null) &&
                        (String.Equals(wra.ContentType, "application/x-javascript", StringComparison.OrdinalIgnoreCase) ||
                         String.Equals(wra.ContentType, "application/javascript", StringComparison.OrdinalIgnoreCase) ||
                         String.Equals(wra.ContentType, "text/javascript", StringComparison.OrdinalIgnoreCase)) &&
                        !scriptResourceInfos.ContainsKey(wra.WebResource))
                    {
                        scriptResourceInfos.Add(wra.WebResource,
                                                new ScriptResourceInfo(wra.WebResource, null, null));
                    }
                }

                foreach (ScriptResourceInfo resource in scriptResourceInfos.Values)
                {
                    string scriptPath = Path.Combine(outputPath, resource.ResourceName);

                    Console.WriteLine();
                    Console.WriteLine(Path.GetFileName(scriptPath));

                    bool debug = resource.ResourceName.EndsWith(".debug.js", StringComparison.OrdinalIgnoreCase);

                    ScriptResourceInfo releaseResource = debug ?
                                                         scriptResourceInfos[resource.ResourceName.Substring(0, resource.ResourceName.Length - 9) + ".js"] :
                                                         null;

                    ResourceManager resourceManager = String.IsNullOrEmpty(resource.ScriptResourceName) ?
                                                      null : new ResourceManager(resource.ScriptResourceName, assembly);
                    ResourceManager releaseResourceManager = (releaseResource != null) &&
                                                             !String.IsNullOrEmpty(releaseResource.ScriptResourceName) ?
                                                             new ResourceManager(releaseResource.ScriptResourceName, assembly) :
                                                             null;

                    if (String.IsNullOrEmpty(resource.ScriptResourceName) &&
                        ((releaseResource == null) || String.IsNullOrEmpty(releaseResource.ScriptResourceName)))
                    {
                        using (Stream scriptStream =
                                   assembly.GetManifestResourceStream(resource.ResourceName)) {
                            if (scriptStream == null)
                            {
                                Console.WriteLine("Can't find resource stream " + resource.ResourceName);
                                continue;
                            }

                            using (StreamReader reader = new StreamReader(scriptStream, true)) {
                                using (StreamWriter writer =
                                           new StreamWriter(scriptPath, false, reader.CurrentEncoding)) {
                                    if (debug)
                                    {
                                        WriteVersion(writer, resource.ResourceName, assemblyName, fileVersion);
                                    }
                                    string script = reader.ReadToEnd();
                                    writer.WriteLine(script);
                                    WriteLoadedNotification(writer, debug);
                                }
                            }
                        }
                        continue;
                    }

                    try {
                        ResourceSet neutralSet = (resourceManager != null) ?
                                                 resourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, true) : null;
                        ResourceSet releaseNeutralSet = (releaseResourceManager != null) ?
                                                        releaseResourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, true) :
                                                        null;

                        foreach (CultureInfo culture in cultures)
                        {
                            // Skip the assembly's default culture, invariant will work the same.
                            if (String.Equals(culture.Name, assemblyDefaultCulture.Name,
                                              StringComparison.OrdinalIgnoreCase))
                            {
                                continue;
                            }

                            System.Threading.Thread.CurrentThread.CurrentUICulture = culture;

                            // Try to read the local set to check if the culture was explicitly defined
                            ResourceSet localSet = (resourceManager != null) ?
                                                   resourceManager.GetResourceSet(culture, true, false) : null;
                            if (localSet == null)
                            {
                                if (releaseResourceManager == null)
                                {
                                    continue;
                                }
                                localSet = releaseResourceManager.GetResourceSet(culture, true, false);
                                // Culture not defined explicitly, try the next one.
                                if (localSet == null)
                                {
                                    continue;
                                }
                            }

                            Console.WriteLine(" - " + culture.DisplayName);

                            string localizedScriptPath =
                                (!String.IsNullOrEmpty(culture.Name)) ?
                                scriptPath.Substring(0, scriptPath.Length - 2) + culture.Name + ".js" :
                                scriptPath;

                            using (Stream scriptStream =
                                       assembly.GetManifestResourceStream(resource.ResourceName)) {
                                if (scriptStream == null)
                                {
                                    Console.WriteLine("Can't find resource stream " + resource.ResourceName);
                                    return;
                                }

                                using (StreamReader reader = new StreamReader(scriptStream, true)) {
                                    using (StreamWriter writer =
                                               new StreamWriter(localizedScriptPath, false, reader.CurrentEncoding)) {
                                        if (debug)
                                        {
                                            WriteVersion(writer, resource.ResourceName, assemblyName, fileVersion);
                                        }
                                        string script = reader.ReadToEnd();
                                        writer.Write(script);
                                        if (!String.IsNullOrEmpty(resource.ScriptResourceName))
                                        {
                                            writer.WriteLine();
                                            int lastDot = resource.TypeName.LastIndexOf('.');
                                            if (lastDot != -1)
                                            {
                                                writer.Write("Type.registerNamespace('");
                                                writer.Write(resource.TypeName.Substring(0, lastDot));
                                                writer.Write("');");
                                                if (debug)
                                                {
                                                    writer.WriteLine();
                                                    writer.WriteLine();
                                                }
                                            }
                                            writer.Write(resource.TypeName);
                                            writer.Write("={");
                                            bool first = true;
                                            if (resourceManager != null)
                                            {
                                                first = WriteResource(
                                                    resourceManager, neutralSet,
                                                    writer, debug, first);
                                            }
                                            if (releaseResourceManager != null)
                                            {
                                                first = WriteResource(
                                                    releaseResourceManager, releaseNeutralSet,
                                                    writer, debug, first);
                                            }
                                            if (debug)
                                            {
                                                writer.WriteLine();
                                            }
                                            writer.WriteLine("};");
                                        }
                                        WriteLoadedNotification(writer, debug);
                                    }
                                }
                            }
                        }

                        if (releaseNeutralSet != null)
                        {
                            releaseNeutralSet.Dispose();
                        }
                        if (neutralSet != null)
                        {
                            neutralSet.Dispose();
                        }
                    }
                    catch (Exception e) {
                        Console.WriteLine("Exception while reading resource " + resource.ScriptResourceName);
                        Console.WriteLine(e.Message);
                    }
                }
            }
        }
Example #10
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();
        }
Example #11
0
        void System.Web.IHttpHandler.ProcessRequest(HttpContext context)
#endif
        {
            HttpRequest request = context.Request;
            // val is URL-encoded, which means every + has been replaced with ' ', we
            // need to revert that or the base64 conversion will fail.
            string d = request.QueryString ["d"];

            if (!String.IsNullOrEmpty(d))
            {
                d = d.Replace(' ', '+');
            }

            AssemblyEmbeddedResources entry;
            EmbeddedResource          res = DecryptAssemblyResource(d, out entry);
            WebResourceAttribute      wra = res != null ? res.Attribute : null;

            if (wra == null)
            {
                throw new HttpException(404, "Resource not found");
            }

            Assembly assembly;

            if (entry.AssemblyName == "s")
            {
                assembly = currAsm;
            }
            else
            {
                assembly = Assembly.Load(entry.AssemblyName);
            }

            HttpResponse response  = context.Response;
            string       req_cache = request.Headers ["Cache-Control"];

            if (String.Compare(req_cache, "max-age=0", StringComparison.Ordinal) == 0)
            {
                long atime;
                if (Int64.TryParse(request.QueryString ["t"], out atime))
                {
                    if (atime == File.GetLastWriteTimeUtc(assembly.Location).Ticks)
                    {
                        response.Clear();
                        response.StatusCode   = 304;
                        response.ContentType  = null;
                        response.CacheControl = "public";                         // easier to set it to public as MS than remove it
                        context.ApplicationInstance.CompleteRequest();
                        return;
                    }
                }
            }
            string modif_since = request.Headers ["If-Modified-Since"];

            if (!String.IsNullOrEmpty(modif_since))
            {
                try {
                    DateTime modif;
                    if (DateTime.TryParseExact(modif_since, "r", null, 0, out modif))
                    {
                        if (File.GetLastWriteTimeUtc(assembly.Location) <= modif)
                        {
                            response.Clear();
                            response.StatusCode   = 304;
                            response.ContentType  = null;
                            response.CacheControl = "public";                             // easier to set it to public as MS than remove it
                            context.ApplicationInstance.CompleteRequest();
                            return;
                        }
                    }
                } catch {}
            }

            response.ContentType = wra.ContentType;

            DateTime utcnow = DateTime.UtcNow;

            response.Headers.Add("Last-Modified", utcnow.ToString("r"));
            response.ExpiresAbsolute = utcnow.AddYears(1);
            response.CacheControl    = "public";

            Stream s = assembly.GetManifestResourceStream(res.Name);

            if (s == null)
            {
                throw new HttpException(404, "Resource " + res.Name + " not found");
            }

            if (wra.PerformSubstitution)
            {
                using (StreamReader r = new StreamReader(s)) {
                    TextWriter w = response.Output;
                    new PerformSubstitutionHelper(assembly).PerformSubstitution(r, w);
                }
            }
            else if (response.OutputStream is HttpResponseStream)
            {
                UnmanagedMemoryStream st      = (UnmanagedMemoryStream)s;
                HttpResponseStream    hstream = (HttpResponseStream)response.OutputStream;
                unsafe {
                    hstream.WritePtr(new IntPtr(st.PositionPointer), (int)st.Length);
                }
            }
            else
            {
                byte [] buf    = new byte [1024];
                Stream  output = response.OutputStream;
                int     c;
                do
                {
                    c = s.Read(buf, 0, 1024);
                    output.Write(buf, 0, c);
                } while (c > 0);
            }
#if SYSTEM_WEB_EXTENSIONS
            TextWriter writer = response.Output;
            foreach (ScriptResourceAttribute sra in assembly.GetCustomAttributes(typeof(ScriptResourceAttribute), false))
            {
                if (String.Compare(sra.ScriptName, res.Name, StringComparison.Ordinal) == 0)
                {
                    string      scriptResourceName = sra.ScriptResourceName;
                    ResourceSet rset = null;
                    try {
                        rset = new ResourceManager(scriptResourceName, assembly).GetResourceSet(Threading.Thread.CurrentThread.CurrentUICulture, true, true);
                    }
                    catch (MissingManifestResourceException) {
#if TARGET_JVM // GetResourceSet does not throw  MissingManifestResourceException if ressource is not exists
                    }
                    if (rset == null)
                    {
#endif
                        if (scriptResourceName.EndsWith(".resources"))
                        {
                            scriptResourceName = scriptResourceName.Substring(0, scriptResourceName.Length - 10);
                            rset = new ResourceManager(scriptResourceName, assembly).GetResourceSet(Threading.Thread.CurrentThread.CurrentUICulture, true, true);
                        }
#if !TARGET_JVM
                        else
                        {
                            throw;
                        }
#endif
                    }
                    if (rset == null)
                    {
                        break;
                    }
                    writer.WriteLine();
                    string ns   = sra.TypeName;
                    int    indx = ns.LastIndexOf('.');
                    if (indx > 0)
                    {
                        writer.WriteLine("Type.registerNamespace('" + ns.Substring(0, indx) + "')");
                    }
                    writer.Write("{0}={{", sra.TypeName);
                    bool first = true;
                    foreach (DictionaryEntry de in rset)
                    {
                        string value = de.Value as string;
                        if (value != null)
                        {
                            if (first)
                            {
                                first = false;
                            }
                            else
                            {
                                writer.Write(',');
                            }
                            writer.WriteLine();
                            writer.Write("{0}:{1}", GetScriptStringLiteral((string)de.Key), GetScriptStringLiteral(value));
                        }
                    }
                    writer.WriteLine();
                    writer.WriteLine("};");
                    break;
                }
            }

            bool notifyScriptLoaded = request.QueryString ["n"] == "t";
            if (notifyScriptLoaded)
            {
                writer.WriteLine();
                writer.WriteLine("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");
            }
#endif
        }
        /// <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();
        }