コード例 #1
0
 /// <summary>
 /// Loads the associated Assembly
 /// </summary>
 /// <returns>Assembly reference</returns>
 public Assembly LoadAssembly()
 {
     //if (!LoadedAssembly.ContainsKey(_assembly))
     //    LoadedAssembly.Add(_assembly, Assembly.Load(_assembly));
     //return LoadedAssembly[_assembly];
     return(ToolkitScriptManagerHelper.GetAssembly(_assembly));
 }
コード例 #2
0
        /// <summary>
        /// Get all types of controls referenced by control bundle names.
        /// If control bundle names is empty then default control bundle defined in AjaxControlToolkit.config will be use to retrieved control types.
        /// If AjaxControlToolkit.config file is not found then all standard control types of AjaxControlToolkit will be retrieved and if control bundle names is defined exception will thrown.
        /// </summary>
        /// <param name="context">Current HttpContext.</param>
        /// <param name="bundles">Control bundle names. Will be ignored if AjaxControlToolkit.config file is not found.</param>
        /// <returns></returns>
        public virtual List <Type> GetControlTypesInBundles(HttpContextBase context, string[] bundles, out ScriptReference[] addedScriptReferences, out ScriptReference[] removedScriptReferences)
        {
            var registeredControls = new List <Type>();
            var registeredBundles  = new List <string>();
            var fileName           = context.Server.MapPath(ConfigFileName);

            addedScriptReferences   = null;
            removedScriptReferences = null;

            if (!File.Exists(fileName))
            {
                // No configuration config (AjaxControlToolkit.config) is specified

                // Bundle names specified, but AjaxControlToolkit.config is not provided then exception should be thrown
                if (bundles != null && bundles.Length > 0)
                {
                    throw new Exception("Can not resolve requested control bundle since " + ConfigFileName +
                                        " file is not defined.");
                }

                // Parse all controls type name in ControlDependencyTypeMaps
                var allControlTypesName = new List <string>();
                foreach (var map in ControlDependencyTypeMaps)
                {
                    allControlTypesName.AddRange(map.Value);
                }

                // Load all AjaxControlToolkit controls if there is no bundle specified neither the config file
                registeredControls.AddRange(allControlTypesName.Select(c => Type.GetType(c))
                                            .ToList());
            }
            else
            {
                var actConfig = ParseConfiguration(fileName);
                if (actConfig.ScriptsSections != null && actConfig.ScriptsSections.Length > 0)
                {
                    var addScripts    = new List <ScriptReference>();
                    var removeScripts = new List <ScriptReference>();
                    var actAssembly   = Assembly.GetCallingAssembly().ToString();

                    foreach (var scriptsSection in actConfig.ScriptsSections)
                    {
                        if (scriptsSection.AddScripts != null)
                        {
                            foreach (var script in scriptsSection.AddScripts)
                            {
                                addScripts.Add(new ScriptReference(script.Name,
                                                                   string.IsNullOrEmpty(script.Assembly) ? actAssembly : script.Assembly));
                            }
                        }

                        if (scriptsSection.RemoveScripts != null)
                        {
                            foreach (var script in scriptsSection.RemoveScripts)
                            {
                                removeScripts.Add(new ScriptReference(script.Name,
                                                                      string.IsNullOrEmpty(script.Assembly) ? actAssembly : script.Assembly));
                            }
                        }
                    }

                    addedScriptReferences   = addScripts.ToArray();
                    removedScriptReferences = removeScripts.ToArray();
                }

                if (actConfig.ControlBundleSections != null && actConfig.ControlBundleSections.Length > 0)
                {
                    // Iterate all control bundle sections. Normaly, there will be only 1 section.
                    foreach (var bundle in actConfig.ControlBundleSections)
                    {
                        if (bundle != null && bundle.ControlBundles != null && bundle.ControlBundles.Length > 0)
                        {
                            // Iterate all control bundles in a section.
                            foreach (var controlBundle in bundle.ControlBundles)
                            {
                                // Only add control types if ...
                                if (

                                    // ... bundle contains control(s) and ...
                                    (controlBundle.Controls != null && controlBundle.Controls.Length > 0) && (

                                        // ... this is default control bundle and requested bundle not specified.
                                        (string.IsNullOrEmpty(controlBundle.Name) &&
                                         (bundles == null || bundles.Length == 0)) ||

                                        // .. or this is not default bundle and its specified in requested bundle
                                        (bundles != null && bundles.Contains(controlBundle.Name))
                                        ))
                                {
                                    // Iterate all controls registered in control bundle. Determining control types is works here.
                                    foreach (var control in controlBundle.Controls)
                                    {
                                        if (string.IsNullOrEmpty(control.Assembly) ||
                                            control.Assembly == "AjaxControlToolkit")
                                        {
                                            // Processing AjaxControlToolkit controls
                                            var controlName = "AjaxControlToolkit." + control.Name;

                                            // Verify that control is a standard AjaxControlToolkit control
                                            if (!ControlDependencyTypeMaps.ContainsKey(controlName))
                                            {
                                                throw new Exception(
                                                          string.Format(
                                                              "Could not find control '{0}'. Please make sure you entered the correct control name in AjaxControlToolkit.config file.",
                                                              control.Name));
                                            }

                                            registeredControls.AddRange(ControlDependencyTypeMaps[controlName]
                                                                        .Select(c => Type.GetType(c)));
                                        }
                                        else
                                        {
                                            // Processing custom controls
                                            registeredControls.Add(
                                                ToolkitScriptManagerHelper.GetAssembly(control.Assembly)
                                                .GetType(control.Assembly + "." + control.Name));
                                        }
                                    }

                                    // Mark that bundle is registered for future verification
                                    registeredBundles.Add(controlBundle.Name);
                                }
                            }
                        }
                    }
                }

                // Verify, is there any control in bundle that not registered yet
                if (bundles != null)
                {
                    foreach (var bundle in bundles)
                    {
                        if (!registeredBundles.Contains(bundle))
                        {
                            throw new Exception(string.Format("Could not resolve bundle {0}.", bundle));
                        }
                    }
                }
            }

            // Return unique types
            return(registeredControls.Distinct().ToList());
        }
コード例 #3
0
 protected static void AppendCharAsUnicode(StringBuilder builder, char c)
 {
     ToolkitScriptManagerHelper.AppendCharAsUnicode(builder, c);
 }
コード例 #4
0
 protected static string QuoteString(string value)
 {
     return(ToolkitScriptManagerHelper.QuoteString(value));
 }
コード例 #5
0
        /// <summary>
        /// Outputs the combined script file requested by the HttpRequest to the HttpResponse
        /// </summary>
        /// <param name="context">HttpContext for the transaction</param>
        /// <returns>true if the script file was output</returns>
        public bool OutputCombinedScriptFile(HttpContextBase context)
        {
            // Initialize
            var request = context.Request;

            // Determine is there any combine script request in http context
            var combinedScripts = ToolkitScriptManagerHelper.GetRequestParamValue(request,
                                                                                  ToolkitScriptManager.CombinedScriptsParamName);

            if (string.IsNullOrEmpty(combinedScripts))
            {
                return(false);
            }

            // This is a request for a combined script file
            var response = context.Response;

            response.ContentType = "application/x-javascript";

            var cache = response.Cache;

            // Set the same (~forever) caching rules that ScriptResource.axd uses
            cache.SetCacheability(HttpCacheability.Public);
            cache.VaryByParams[ToolkitScriptManager.CombinedScriptsParamName] = true;
            cache.VaryByParams[ToolkitScriptManager.HiddenFieldParamName]     = true;
            cache.VaryByParams[ToolkitScriptManager.CacheBustParamName]       = true;
            cache.VaryByParams[ToolkitScriptManager.EnableCdnParamName]       = true;
            cache.SetOmitVaryStar(true);
            cache.SetExpires(DateTime.Now.AddDays(365));
            cache.SetValidUntilExpires(true);
            cache.SetLastModifiedFromFileDependencies();

            // Get the stream to write the combined script to (using a compressed stream if requested)
            // Note that certain versions of IE6 have difficulty with compressed responses, so we
            // don't compress for those browsers (just like ASP.NET AJAX's ScriptResourceHandler)
            var outputStream = response.OutputStream;

            if (!request.Browser.IsBrowser("IE") || (6 < request.Browser.MajorVersion))
            {
                foreach (
                    string acceptEncoding in (request.Headers["Accept-Encoding"] ?? "").ToUpperInvariant().Split(','))
                {
                    if ("GZIP" == acceptEncoding)
                    {
                        // Browser wants GZIP; wrap the output stream with a GZipStream
                        response.AddHeader("Content-encoding", "gzip");
                        outputStream = new GZipStream(outputStream, CompressionMode.Compress);
                        break;
                    }

                    if ("DEFLATE" == acceptEncoding)
                    {
                        // Browser wants Deflate; wrap the output stream with a DeflateStream
                        response.AddHeader("Content-encoding", "deflate");
                        outputStream = new DeflateStream(outputStream, CompressionMode.Compress);
                        break;
                    }
                }
            }


            // Output the combined script
            using (var outputWriter = new StreamWriter(outputStream)) {
                var hash = ToolkitScriptManagerHelper.GetRequestParamValue(request,
                                                                           ToolkitScriptManager.CacheBustParamName);
                var bundlesParam = ToolkitScriptManagerHelper.GetRequestParamValue(request,
                                                                                   ToolkitScriptManager.ControlBundleParamName);
                var enableCdn = bool.Parse(ToolkitScriptManagerHelper.GetRequestParamValue(request, ToolkitScriptManager.EnableCdnParamName));

                string[] bundles = null;
                if (!string.IsNullOrEmpty(bundlesParam))
                {
                    bundles = bundlesParam.Split(new[] { ToolkitScriptManager.QueryStringBundleDelimiter },
                                                 StringSplitOptions.RemoveEmptyEntries);
                }

                var js = GetCombinedScriptContent(context, hash, bundles, enableCdn);


                var minifyResult = _helper.MinifyJS(js);
                if (minifyResult.ErrorList.Count > 0)
                {
                    _helper.WriteErrors(outputWriter, minifyResult.ErrorList);
                }
                else
                {
                    // Write minified scripts
                    _helper.WriteToStream(outputWriter, minifyResult.Result);
                    // Write the ASP.NET AJAX script notification code
                    _helper.WriteToStream(outputWriter,
                                          "if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");
                }
            }
            return(true);
        }
コード例 #6
0
 /// <summary>
 /// Helper class to provide combine and minification for ToolkitScriptManager.
 /// This API supports the AjaxControlToolkit infrastructure and is not intended to be used directly from your code.
 /// </summary>
 /// <param name="toolkitScriptManagerConfig"></param>
 /// <param name="helper"></param>
 public ToolkitScriptManagerCombiner(ToolkitScriptManagerConfig toolkitScriptManagerConfig,
                                     ToolkitScriptManagerHelper helper)
 {
     _scriptManagerConfig = toolkitScriptManagerConfig;
     _helper = helper;
 }
コード例 #7
0
        /// <summary>
        /// Writes scripts (including localized script resources) to the specified stream
        /// </summary>
        /// <param name="scriptEntries">list of scripts to write</param>
        /// <param name="outputWriter">writer for output stream</param>
        private void WriteScripts(List <ScriptEntry> scriptEntries, TextWriter outputWriter, bool enableCdn)
        {
            foreach (ScriptEntry scriptEntry in scriptEntries)
            {
                if (!scriptEntry.Loaded)
                {
                    var combineStatus = IsScriptCombinable(scriptEntry, enableCdn);

                    if (combineStatus == ScriptCombineStatus.NotCorrespondingWebResourceAttribute)
                    {
                        throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture,
                                                                      "Combined script request includes uncombinable script \"{0}\".",
                                                                      scriptEntry.Name));
                    }

                    if (combineStatus == ScriptCombineStatus.Combineable)
                    {
                        // This script hasn't been loaded by the browser, so add it to the combined script file
                        string script = scriptEntry.GetScript();
                        if (WebResourceRegex.IsMatch(script))
                        {
                            // This script uses script substitution which isn't supported yet, so throw an exception since it's too late to fix
                            throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture,
                                                                          "ToolkitScriptManager does not support <%= WebResource/ScriptResource(...) %> substitution as used by script file \"{0}\".",
                                                                          scriptEntry.Name));
                        }
                        outputWriter.WriteLine(script);

                        // Save current culture and set the specified culture
                        CultureInfo currentUiCulture = Thread.CurrentThread.CurrentUICulture;
                        try {
                            try {
                                Thread.CurrentThread.CurrentUICulture = new CultureInfo(scriptEntry.Culture);
                            }
                            catch (ArgumentException) {
                                // Invalid culture; proceed with default culture (just as for unsupported cultures)
                            }

                            // Write out the associated script resources (if any) in the proper culture
                            Assembly scriptAssembly = scriptEntry.LoadAssembly();
                            foreach (
                                ScriptResourceAttribute scriptResourceAttribute in
                                GetScriptResourceAttributes(scriptAssembly))
                            {
                                if (scriptResourceAttribute.ScriptName == scriptEntry.Name)
                                {
#pragma warning disable 0618 // obsolete members of ScriptResourceAttribute are used but necessary in the 3.5 build
                                    // Found a matching script resource; write it out
                                    outputWriter.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0}={{",
                                                                         scriptResourceAttribute.TypeName));

                                    // Get the script resource name (without the trailing ".resources")
                                    string scriptResourceName = scriptResourceAttribute.ScriptResourceName;
                                    if (scriptResourceName.EndsWith(".resources", StringComparison.OrdinalIgnoreCase))
                                    {
                                        scriptResourceName = scriptResourceName.Substring(0,
                                                                                          scriptResourceName.Length - 10);
                                    }
#pragma warning restore 0618

                                    // Load a ResourceManager/ResourceSet and walk through the list to output them all
                                    System.Resources.ResourceManager resourceManager =
                                        new System.Resources.ResourceManager(scriptResourceName, scriptAssembly);
                                    using (
                                        System.Resources.ResourceSet resourceSet =
                                            resourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, true)) {
                                        bool first = true;
                                        foreach (System.Collections.DictionaryEntry de in resourceSet)
                                        {
                                            if (!first)
                                            {
                                                // Need a comma between all entries
                                                outputWriter.Write(",");
                                            }
                                            // Output the entry
                                            string name  = (string)de.Key;
                                            string value = resourceManager.GetString(name);
                                            outputWriter.Write(string.Format(CultureInfo.InvariantCulture,
                                                                             "\"{0}\":\"{1}\"", ToolkitScriptManagerHelper.QuoteString(name),
                                                                             ToolkitScriptManagerHelper.QuoteString(value)));
                                            first = false;
                                        }
                                    }
                                    outputWriter.WriteLine("};");
                                }
                            }
                        }
                        finally {
                            // Restore culture
                            Thread.CurrentThread.CurrentUICulture = currentUiCulture;
                        }

                        // Done with this script
                        // This script is now (or will be soon) loaded by the browser
                        scriptEntry.Loaded = true;
                    }
                }
            }
        }
コード例 #8
0
        /// <summary>
        /// Get all types of controls referenced by control bundle names.
        /// If control bundle names is empty then default control bundle defined in AjaxControlToolkit.config will be use to retrieved control types.
        /// If AjaxControlToolkit.config file is not found then all standard control types of AjaxControlToolkit will be retrieved and if control bundle names is defined exception will thrown.
        /// </summary>
        /// <param name="context">Current HttpContext.</param>
        /// <param name="bundles">Control bundle names. Will be ignored if AjaxControlToolkit.config file is not found.</param>
        /// <returns></returns>
        public virtual List <Type> GetControlTypesInBundles(HttpContextBase context, string[] bundles)
        {
            var registeredControls = new List <Type>();
            var registeredBundles  = new List <string>();
            var fileName           = context.Server.MapPath(ConfigFileName);

            if (!File.Exists(fileName))
            {
                // No configuration config (AjaxControlToolkit.config) is specified

                // Bundle names specified, but AjaxControlToolkit.config is not provided then exception should be thrown
                if (bundles != null && bundles.Length > 0)
                {
                    throw new Exception("Can not resolve requested control bundle since " + ConfigFileName +
                                        " file is not defined.");
                }

                // Parse all controls type name in ControlDependencyTypeMaps
                var allControlTypesName = new List <string>();
                foreach (var map in ControlDependencyTypeMaps)
                {
                    allControlTypesName.AddRange(map.Value);
                }

                // Load all AjaxControlToolkit controls if there is no bundle specified neither the config file
                registeredControls.AddRange(allControlTypesName.Select(c => Type.GetType(c))
                                            .ToList());
            }
            else
            {
                // Bundle configuration (AjaxControlToolkit.config) specified
                // Try read config content from cache
                var configContent = _cacheProvider.Get <string>(CacheConfigName);
                if (string.IsNullOrEmpty(configContent))
                {
                    using (StreamReader sr = File.OpenText(fileName)) {
                        // Retrieve config content from file and caching it
                        configContent = sr.ReadToEnd();
                        _cacheProvider.Set(CacheConfigName, configContent, fileName);
                    }
                }

                // Deserialize bundle configuration
                var bundleConfig = (Config.Settings)(new XmlSerializer(typeof(Config.Settings)))
                                   .Deserialize(new StringReader(configContent));

                // Iterate all control bundle sections. Normaly, there will be only 1 section.
                foreach (var bundle in bundleConfig.ControlBundleSections)
                {
                    // Iterate all control bundles in a section.
                    foreach (var controlBundle in bundle.ControlBundles)
                    {
                        // Only add control types if ...
                        if (
                            // ... this is default control bundle and requested bundle not specified.
                            (string.IsNullOrEmpty(controlBundle.Name) && (bundles == null || bundles.Length == 0)) ||

                            // .. or this is not default bundle and its specified in requested bundle
                            (bundles != null && bundles.Contains(controlBundle.Name)))
                        {
                            // Iterate all controls registered in control bundle. Determining control types is works here.
                            foreach (var control in controlBundle.Controls)
                            {
                                if (string.IsNullOrEmpty(control.Assembly) || control.Assembly == "AjaxControlToolkit")
                                {
                                    // Processing AjaxControlToolkit controls
                                    var controlName = "AjaxControlToolkit." + control.Name;

                                    // Verify that control is a standard AjaxControlToolkit control
                                    if (!ControlDependencyTypeMaps.ContainsKey(controlName))
                                    {
                                        throw new Exception(
                                                  string.Format(
                                                      "Could not find control '{0}'. Please make sure you entered the correct control name in AjaxControlToolkit.config file.",
                                                      control.Name));
                                    }

                                    registeredControls.AddRange(ControlDependencyTypeMaps[controlName]
                                                                .Select(c => Type.GetType(c)));
                                }
                                else
                                {
                                    // Processing custom controls
                                    registeredControls.Add(
                                        ToolkitScriptManagerHelper.GetAssembly(control.Assembly)
                                        .GetType(control.Assembly + "." + control.Name));
                                }
                            }

                            // Mark that bundle is registered for future verification
                            registeredBundles.Add(controlBundle.Name);
                        }
                    }
                }

                // Verify, is there any control in bundle that not registered yet
                if (bundles != null)
                {
                    foreach (var bundle in bundles)
                    {
                        if (!registeredBundles.Contains(bundle))
                        {
                            throw new Exception(string.Format("Could not resolve bundle {0}.", bundle));
                        }
                    }
                }
            }

            // Return unique types
            return(registeredControls.Distinct().ToList());
        }