Inheritance: DynamicScript
        public void Initialize(string[] rootUrls, bool watchForChanges = true)
        {
            var bundleList = new List<Func<string>>();

            foreach (var rootUrl in rootUrls)
            {
                var path = rootUrl;
                if (path.StartsWith("~/"))
                    path = HostingEnvironment.MapPath(path);

                if (!Directory.Exists(path))
                    continue;

                foreach (var file in Directory.EnumerateFiles(path, "*.html", SearchOption.AllDirectories))
                {
                    var key = GetKey(file);
                    if (key == null)
                        continue;

                    var script = new TemplateScript(key, () => File.ReadAllText(file));
                    DynamicScriptManager.Register(script);
                    scriptByKey[key.ToLowerInvariant()] = script;
                    bundleList.Add(script.GetScript);
                }

                if (watchForChanges)
                    WatchForChanges(rootUrl);
            }

            bundle = new ConcatenatedScript(bundleList);
            DynamicScriptManager.Register("TemplateBundle", bundle);
        }
        public void Initialize(string[] rootUrls, bool watchForChanges = true)
        {
            var bundleList = new List <Func <string> >();

            foreach (var rootUrl in rootUrls)
            {
                var path = rootUrl;
                if (path.StartsWith("~/"))
                {
                    path = HostingEnvironment.MapPath(path);
                }

                if (!path.EndsWith(Path.DirectorySeparatorChar.ToString()))
                {
                    path = path + Path.DirectorySeparatorChar;
                }

                if (!Directory.Exists(path))
                {
                    continue;
                }

                foreach (var file in Directory.EnumerateFiles(path, "*.html", SearchOption.AllDirectories))
                {
                    var key = GetKey(path, file);
                    if (key == null)
                    {
                        continue;
                    }

                    var script = new TemplateScript(key, () => File.ReadAllText(file));
                    DynamicScriptManager.Register(script);
                    scriptByKey[key.ToLowerInvariant()] = script;
                    bundleList.Add(script.GetScript);
                }

                if (watchForChanges)
                {
                    WatchForChanges(path);
                }
            }

            bundle = new ConcatenatedScript(bundleList);
            DynamicScriptManager.Register("TemplateBundle", bundle);
        }
Exemplo n.º 3
0
        public void Initialize(string[] rootUrls, bool watchForChanges = true)
        {
            var bundleList = new List <Func <string> >();

            foreach (var rootUrl in rootUrls)
            {
                var rootPath = HttpContext.Current.Server.MapPath(rootUrl);

                if (!Directory.Exists(rootPath))
                {
                    continue;
                }

                foreach (var file in Directory.EnumerateFiles(rootPath, "*.html", SearchOption.AllDirectories))
                {
                    var key = GetKey(file);
                    if (key == null)
                    {
                        continue;
                    }

                    var script = new TemplateScript(key, () => File.ReadAllText(file));
                    DynamicScriptManager.Register(script);
                    scriptByKey[key.ToLowerInvariant()] = script;
                    bundleList.Add(script.GetScript);
                }

                if (watchForChanges)
                {
                    WatchForChanges(rootUrl);
                }
            }

            bundle = new ConcatenatedScript(bundleList);
            DynamicScriptManager.Register("TemplateBundle", bundle);
        }
Exemplo n.º 4
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;
        }
Exemplo n.º 5
0
        public static void Initialize()
        {
            if (isInitialized)
            {
                return;
            }

            isInitialized        = true;
            isEnabled            = false;
            bundleKeyBySourceUrl = null;
            bundleByKey          = null;
            try
            {
                var setting  = ConfigurationManager.AppSettings["ScriptBundling"];
                var settings = JsonConvert.DeserializeObject <ScriptBundlingSettings>(
                    setting.TrimToNull() ?? "{}", JsonSettings.Tolerant);

                if (settings == null ||
                    settings.Enabled != true)
                {
                    return;
                }

                var bundles = ScriptBundles;

                if (bundles == null ||
                    bundles.Count == 0)
                {
                    return;
                }

                var  bundleKeyBySourceUrlNew = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
                var  bundleByKeyNew          = new Dictionary <string, ConcatenatedScript>(StringComparer.OrdinalIgnoreCase);
                bool minimize = settings.Minimize == true;

                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> >();

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

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

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

                        bundleKeyBySourceUrlNew[sourceUrl] = bundleKey;

                        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)
                            {
                                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);
                    DynamicScriptManager.Register(bundleName, bundle);
                    bundleByKeyNew[bundleKey] = bundle;
                }

                bundleKeyBySourceUrl = bundleKeyBySourceUrlNew;
                bundleByKey          = bundleByKeyNew;
                isEnabled            = true;
            }
            catch (Exception ex)
            {
                ex.Log();
            }
        }
Exemplo n.º 6
0
        public static void Initialize()
        {
            if (isInitialized)
                return;

            isInitialized = true;
            isEnabled = false;
            bundleKeyBySourceUrl = null;
            bundleByKey = null;
            MsieJsEngine jsEngine = null;
            try
            {
                var settings = JsonConvert.DeserializeObject<ScriptBundlingSettings>(
                    ConfigurationManager.AppSettings["ScriptBundling"].TrimToNull() ?? "{}", JsonSettings.Tolerant);

                if (settings == null ||
                    settings.Enabled != true)
                    return;

                var bundles = ScriptBundles;

                if (bundles == null ||
                    bundles.Count == 0)
                {
                    return;
                }

                var bundleKeyBySourceUrlNew = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                var bundleByKeyNew = new Dictionary<string, ConcatenatedScript>(StringComparer.OrdinalIgnoreCase);
                bool minimize = settings.Minimize == true;

                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>>();

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

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

                        if (sourceUrl.IsNullOrEmpty())
                            continue;

                        bundleKeyBySourceUrlNew[sourceUrl] = bundleKey;

                        bundleParts.Add(() =>
                        {
                            if (HttpContext.Current == null)
                                return String.Format(errorLines, "Tried to generate script while HttpContext is null");

                            var sourcePath = HttpContext.Current.Server.MapPath(sourceUrl);
                            if (!File.Exists(sourcePath))
                                return String.Format(errorLines, String.Format("File {0} is not found!", sourcePath));

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

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

                                return MinimizeWithUglifyJS(ref jsEngine, code);
                            }

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

                    var bundle = new ConcatenatedScript(bundleParts);
                    DynamicScriptManager.Register(bundleName, bundle);
                    bundleByKeyNew[bundleKey] = bundle;
                }

                bundleKeyBySourceUrl = bundleKeyBySourceUrlNew;
                bundleByKey = bundleByKeyNew;
                isEnabled = true;
            }
            catch (Exception ex)
            {
                ex.Log();
            }
            finally
            {
                if (jsEngine != null)
                    jsEngine.Dispose();
            }
        }
Exemplo n.º 7
0
        public static void Initialize()
        {
            if (isInitialized)
            {
                return;
            }

            isInitialized        = true;
            isEnabled            = false;
            bundleKeyBySourceUrl = null;
            bundleByKey          = null;
            try
            {
                var settings = JsonConvert.DeserializeObject <ScriptBundlingSettings>(
                    ConfigurationManager.AppSettings["ScriptBundling"].TrimToNull() ?? "{}", JsonSettings.Tolerant);

                if (settings == null ||
                    settings.Enabled != true)
                {
                    return;
                }

                if (settings.Bundles == null ||
                    settings.Bundles.Count == 0)
                {
                    settings.Bundles = JsConfigHelper.LoadConfig <Dictionary <string, string[]> >(
                        "~/Scripts/Site/ScriptBundles.js");

                    if (settings.Bundles == null ||
                        settings.Bundles.Count == 0)
                    {
                        return;
                    }
                }

                var  bundleKeyBySourceUrlNew = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
                var  bundleByKeyNew          = new Dictionary <string, ConcatenatedScript>(StringComparer.OrdinalIgnoreCase);
                bool minimize = settings.Minimize == true;

                foreach (var pair in settings.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> >();

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

                        string sourceUrl =
                            UrlHelper.ResolveUrl(sourceFile);
                        if (sourceUrl.IsNullOrEmpty())
                        {
                            continue;
                        }

                        bundleKeyBySourceUrlNew[sourceUrl] = bundleKey;

                        bundleParts.Add(() =>
                        {
                            if (HttpContext.Current == null)
                            {
                                return(String.Format(errorLines, "Tried to generate script while HttpContext is null"));
                            }

                            var sourcePath = HttpContext.Current.Server.MapPath(sourceUrl);
                            if (!File.Exists(sourcePath))
                            {
                                return(String.Format(errorLines, String.Format("File {0} is not found!", sourcePath)));
                            }

                            if (minimize)
                            {
                                var minPath = Path.ChangeExtension(sourcePath, ".min.js");
                                if (File.Exists(minPath))
                                {
                                    sourcePath = minPath;
                                }
                            }

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

                    var bundle = new ConcatenatedScript(bundleParts);
                    bundle.Minimize = settings.Minimize == true;
                    DynamicScriptManager.Register(bundleName, bundle);
                    bundleByKeyNew[bundleKey] = bundle;
                }

                bundleKeyBySourceUrl = bundleKeyBySourceUrlNew;
                bundleByKey          = bundleByKeyNew;
                isEnabled            = true;
            }
            catch (Exception ex)
            {
                ex.Log();
            }
        }