Exemple #1
0
        public static string GetCssBundle(string cssUrl)
        {
            Initialize();

            string bundleKey;

            if (cssUrl != null && cssUrl.StartsWith("dynamic://",
                                                    StringComparison.OrdinalIgnoreCase))
            {
                var scriptName = cssUrl.Substring(10);
                if (!isEnabled || !bundleKeyBySourceUrl.TryGetValue(cssUrl, out bundleKey))
                {
                    cssUrl = DynamicScriptManager.GetScriptInclude(scriptName, ".css");
                    return(VirtualPathUtility.ToAbsolute("~/DynJS.axd/" + cssUrl));
                }
            }
            else
            {
                cssUrl = BundleUtils.ExpandVersionVariable(cssUrl);
                cssUrl = VirtualPathUtility.ToAbsolute(cssUrl);

                if (!isEnabled ||
                    bundleKeyBySourceUrl == null ||
                    !bundleKeyBySourceUrl.TryGetValue(cssUrl, out bundleKey))
                {
                    return(cssUrl);
                }
            }

            string include = DynamicScriptManager.GetScriptInclude("CssBundle." + bundleKey, ".css");

            return(VirtualPathUtility.ToAbsolute("~/DynJS.axd/" + include));
        }
Exemple #2
0
        public static string GetScriptBundle(string scriptUrl)
        {
            string bundleKey;
            var    bySrcUrl = Instance.bundleKeyBySourceUrl;

            if (scriptUrl != null && scriptUrl.StartsWith("dynamic://",
                                                          StringComparison.OrdinalIgnoreCase))
            {
                var scriptName = scriptUrl.Substring(10);
                if (bySrcUrl == null || !bySrcUrl.TryGetValue(scriptUrl, out bundleKey))
                {
                    scriptUrl = DynamicScriptManager.GetScriptInclude(scriptName);
                    return(VirtualPathUtility.ToAbsolute("~/DynJS.axd/" + scriptUrl));
                }
            }
            else
            {
                scriptUrl = BundleUtils.ExpandVersionVariable(scriptUrl);
                scriptUrl = VirtualPathUtility.ToAbsolute(scriptUrl);

                if (bySrcUrl == null ||
                    !bySrcUrl.TryGetValue(scriptUrl, out bundleKey))
                {
                    return(scriptUrl);
                }
            }

            string include = DynamicScriptManager.GetScriptInclude("Bundle." + bundleKey);

            return(VirtualPathUtility.ToAbsolute("~/DynJS.axd/" + include));
        }
        public static IHtmlString StyleBundle(this HtmlHelper helper, string bundleKey)
        {
            if (helper == null)
            {
                throw new ArgumentNullException("helper");
            }

            if (String.IsNullOrEmpty(bundleKey))
            {
                throw new ArgumentNullException("bundleKey");
            }

            var context = helper.ViewContext.HttpContext;

            if (!CssBundleManager.IsEnabled)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var include in CssBundleManager.GetBundleIncludes(bundleKey))
                {
                    var cssUrl = include;
                    if (string.IsNullOrEmpty(cssUrl))
                    {
                        continue;
                    }

                    if (cssUrl != null && cssUrl.StartsWith("dynamic://", StringComparison.OrdinalIgnoreCase))
                    {
                        var scriptName = cssUrl.Substring(10);
                        cssUrl = DynamicScriptManager.GetScriptInclude(scriptName, ".css");
                        cssUrl = VirtualPathUtility.ToAbsolute("~/DynJS.axd/" + cssUrl);
                    }
                    else
                    {
                        cssUrl = BundleUtils.ExpandVersionVariable(cssUrl);
                        cssUrl = VirtualPathUtility.ToAbsolute(cssUrl);
                    }

                    var cssList = GetIncludedCssList(context);

                    if (!cssList.Contains(cssUrl))
                    {
                        cssList.Add(cssUrl);
                        sb.AppendLine(String.Format("    <link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\"/>\n",
#if !ASPNETMVC
                                                    WebUtility.HtmlEncode(ContentHashCache.ResolveWithHash(cssUrl))));
#else
                                                    HttpUtility.HtmlAttributeEncode(ContentHashCache.ResolveWithHash(cssUrl))));
#endif
                    }
                }

                return(new HtmlString(sb.ToString()));
            }

            return(Stylesheet(helper, "dynamic://CssBundle." + bundleKey));
        }
        public static IHtmlString ScriptBundle(this HtmlHelper helper, string bundleKey)
        {
            if (helper == null)
            {
                throw new ArgumentNullException("helper");
            }

            if (String.IsNullOrEmpty(bundleKey))
            {
                throw new ArgumentNullException("bundleKey");
            }

            var context = helper.ViewContext.HttpContext;

            if (!ScriptBundleManager.IsEnabled)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var include in ScriptBundleManager.GetBundleIncludes(bundleKey))
                {
                    var scriptUrl = include;
                    if (string.IsNullOrEmpty(scriptUrl))
                    {
                        continue;
                    }

                    if (scriptUrl != null && scriptUrl.StartsWith("dynamic://", StringComparison.OrdinalIgnoreCase))
                    {
                        var scriptName = scriptUrl.Substring(10);
                        scriptUrl = DynamicScriptManager.GetScriptInclude(scriptName);
                        scriptUrl = VirtualPathUtility.ToAbsolute("~/DynJS.axd/" + scriptUrl);
                    }
                    else
                    {
                        scriptUrl = BundleUtils.ExpandVersionVariable(scriptUrl);
                        scriptUrl = VirtualPathUtility.ToAbsolute(scriptUrl);
                    }

                    var scripts = GetIncludedScripts(context);

                    if (!scripts.Contains(scriptUrl))
                    {
                        scripts.Add(scriptUrl);
                        sb.AppendLine(String.Format("    <script src=\"{0}\" type=\"text/javascript\"></script>\n",
#if !ASPNETMVC
                                                    WebUtility.HtmlEncode(ContentHashCache.ResolveWithHash(scriptUrl))));
#else
                                                    HttpUtility.HtmlAttributeEncode(ContentHashCache.ResolveWithHash(scriptUrl))));
#endif
                    }
                }

                return(new HtmlString(sb.ToString()));
            }

            return(Script(helper, "dynamic://Bundle." + bundleKey));
        }
Exemple #5
0
        public static void ScriptsChanged()
        {
            BundleUtils.ClearVersionCache();
            var instance = ScriptBundleManager.instance;

            if (instance != null &&
                instance.bundleByKey != null)
            {
                foreach (var bundle in instance.bundleByKey.Values)
                {
                    bundle.Changed();
                }
            }

            instance = null;
        }
Exemple #6
0
        public static void CssChanged()
        {
            BundleUtils.ClearVersionCache();
            cssBundles = null;

            if (isEnabled && bundleByKey != null)
            {
                var s = bundleByKey;
                if (s != null)
                {
                    foreach (var bundle in s.Values)
                    {
                        bundle.Changed();
                    }
                }

                isInitialized = false;
            }
        }
Exemple #7
0
        public ScriptBundleManager()
        {
            var settings = Config.Get <ScriptBundlingSettings>();

            var bundles = JsonConfigHelper.LoadConfig <Dictionary <string, string[]> >(
                HostingEnvironment.MapPath("~/Scripts/site/ScriptBundles.json"));

            bundleIncludes = BundleUtils.ExpandBundleIncludes(bundles, "dynamic://Bundle.", "script");

            if (bundles.Count == 0 ||
                settings.Enabled != true)
            {
                return;
            }

            bundleKeyBySourceUrl  = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
            bundleKeysBySourceUrl = new Dictionary <string, HashSet <string> >(StringComparer.OrdinalIgnoreCase);
            bundleByKey           = new Dictionary <string, ConcatenatedScript>(StringComparer.OrdinalIgnoreCase);

            bool minimize   = settings.Minimize == true;
            var  noMinimize = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            if (settings.NoMinimize != null)
            {
                noMinimize.AddRange(settings.NoMinimize);
            }

            foreach (var pair in bundles)
            {
                var sourceFiles = pair.Value;
                if (sourceFiles == null ||
                    sourceFiles.Length == 0)
                {
                    continue;
                }

                var bundleKey   = pair.Key;
                var bundleName  = "Bundle." + bundleKey;
                var bundleParts = new List <Func <string> >();
                var scriptNames = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

                Action <string> registerInBundle = delegate(string sourceFile)
                {
                    if (bundleKey.IndexOf('/') < 0 && !bundleKeyBySourceUrl.ContainsKey(sourceFile))
                    {
                        bundleKeyBySourceUrl[sourceFile] = bundleKey;
                    }

                    HashSet <string> bundleKeys;
                    if (!bundleKeysBySourceUrl.TryGetValue(sourceFile, out bundleKeys))
                    {
                        bundleKeys = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                        bundleKeysBySourceUrl[sourceFile] = new HashSet <string>();
                    }

                    bundleKeys.Add(bundleKey);
                };

                foreach (var sourceFile in sourceFiles)
                {
                    if (sourceFile.IsNullOrEmpty())
                    {
                        continue;
                    }

                    if (sourceFile.StartsWith("dynamic://", StringComparison.OrdinalIgnoreCase))
                    {
                        registerInBundle(sourceFile);

                        var scriptName = sourceFile.Substring(10);
                        scriptNames.Add(scriptName);
                        bundleParts.Add(() =>
                        {
                            if (recursionCheck != null)
                            {
                                if (recursionCheck.Contains(scriptName) || recursionCheck.Count > 100)
                                {
                                    return(String.Format(errorLines,
                                                         String.Format("Caught infinite recursion with dynamic scripts '{0}'!",
                                                                       String.Join(", ", recursionCheck))));
                                }
                            }
                            else
                            {
                                recursionCheck = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                            }

                            recursionCheck.Add(scriptName);
                            try
                            {
                                var code = DynamicScriptManager.GetScriptText(scriptName);
                                if (code == null)
                                {
                                    return(String.Format(errorLines,
                                                         String.Format("Dynamic script with name '{0}' is not found!", scriptName)));
                                }

                                if (minimize &&
                                    !scriptName.StartsWith("Bundle.", StringComparison.OrdinalIgnoreCase))
                                {
                                    try
                                    {
                                        var result = NUglify.Uglify.Js(code);
                                        if (!result.HasErrors)
                                        {
                                            code = result.Code;
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        ex.Log();
                                    }
                                }

                                return(code);
                            }
                            finally
                            {
                                recursionCheck.Remove(scriptName);
                            }
                        });

                        continue;
                    }

                    string sourceUrl = BundleUtils.ExpandVersionVariable(sourceFile);
                    sourceUrl = VirtualPathUtility.ToAbsolute(sourceUrl);

                    if (sourceUrl.IsNullOrEmpty())
                    {
                        continue;
                    }

                    registerInBundle(sourceUrl);

                    bundleParts.Add(() =>
                    {
                        var sourcePath = HostingEnvironment.MapPath(sourceUrl);
                        if (!File.Exists(sourcePath))
                        {
                            return(String.Format(errorLines, String.Format("File {0} is not found!", sourcePath)));
                        }

                        if (minimize && !noMinimize.Contains(sourceFile))
                        {
                            if (settings.UseMinJS == true)
                            {
                                var minPath = Path.ChangeExtension(sourcePath, ".min.js");
                                if (File.Exists(minPath))
                                {
                                    sourcePath = minPath;
                                    using (StreamReader sr = new StreamReader(File.OpenRead(sourcePath)))
                                        return(sr.ReadToEnd());
                                }
                            }

                            string code;
                            using (StreamReader sr = new StreamReader(File.OpenRead(sourcePath)))
                                code = sr.ReadToEnd();

                            try
                            {
                                var result = NUglify.Uglify.Js(code);
                                if (result.HasErrors)
                                {
                                    return(code);
                                }
                                return(result.Code);
                            }
                            catch (Exception ex)
                            {
                                ex.Log();
                                return(code);
                            }
                        }

                        using (StreamReader sr = new StreamReader(File.OpenRead(sourcePath)))
                            return(sr.ReadToEnd());
                    });
                }

                var bundle = new ConcatenatedScript(bundleParts, checkRights: () =>
                {
                    foreach (var scriptName in scriptNames)
                    {
                        if (recursionCheck != null)
                        {
                            if (recursionCheck.Contains(scriptName) || recursionCheck.Count > 100)
                            {
                                throw new InvalidOperationException(String.Format(
                                                                        "Caught infinite recursion with dynamic scripts '{0}'!",
                                                                        String.Join(", ", recursionCheck)));
                            }
                        }
                        else
                        {
                            recursionCheck = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                        }

                        recursionCheck.Add(scriptName);
                        try
                        {
                            DynamicScriptManager.CheckScriptRights(scriptName);
                        }
                        finally
                        {
                            recursionCheck.Remove(scriptName);
                        }
                    }
                });

                DynamicScriptManager.Register(bundleName, bundle);
                bundleByKey[bundleKey] = bundle;
            }

            isEnabled = true;
        }
Exemple #8
0
        public void Reset()
        {
            lock (sync)
            {
                isEnabled = false;
                var settings = options.Value;
                var bundles  = settings.Bundles ?? new Dictionary <string, string[]>();

                bundles = bundles.Keys.ToDictionary(k => k,
                                                    k => (bundles[k] ?? Array.Empty <string>())
                                                    .Select(u => BundleUtils.DoReplacements(u, settings.Replacements))
                                                    .Where(u => !string.IsNullOrEmpty(u))
                                                    .ToArray());

                bundleIncludes = BundleUtils.ExpandBundleIncludes(bundles, "dynamic://CssBundle.", "css");

                if (bundles.Count == 0 ||
                    settings.Enabled != true)
                {
                    bundleKeyBySourceUrl  = null;
                    bundleKeysBySourceUrl = null;
                    bundleKeys            = null;
                    return;
                }

                bundleKeyBySourceUrl  = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
                bundleKeysBySourceUrl = new Dictionary <string, HashSet <string> >(StringComparer.OrdinalIgnoreCase);
                bundleKeys            = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

                bool minimize   = settings.Minimize == true;
                var  noMinimize = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                if (settings.NoMinimize != null)
                {
                    noMinimize.AddRange(settings.NoMinimize);
                }

                foreach (var pair in bundles)
                {
                    var sourceFiles = pair.Value;
                    if (sourceFiles == null ||
                        sourceFiles.Length == 0)
                    {
                        continue;
                    }

                    var bundleKey   = pair.Key;
                    var bundleName  = "CssBundle." + bundleKey;
                    var bundleParts = new List <Func <string> >();
                    var scriptNames = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

                    void registerInBundle(string sourceFile)
                    {
                        if (bundleKey.IndexOf('/', StringComparison.Ordinal) < 0 && !bundleKeyBySourceUrl.ContainsKey(sourceFile))
                        {
                            bundleKeyBySourceUrl[sourceFile] = bundleKey;
                        }

                        if (!bundleKeysBySourceUrl.TryGetValue(sourceFile, out HashSet <string> bundleKeys))
                        {
                            bundleKeys = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                            bundleKeysBySourceUrl[sourceFile] = new HashSet <string>();
                        }

                        bundleKeys.Add(bundleKey);
                    }

                    foreach (var sourceFile in sourceFiles)
                    {
                        if (sourceFile.IsNullOrEmpty())
                        {
                            continue;
                        }

                        if (sourceFile.StartsWith("dynamic://", StringComparison.OrdinalIgnoreCase))
                        {
                            registerInBundle(sourceFile);

                            var scriptName = sourceFile[10..];