Пример #1
0
        public static string GetScriptBundle(string scriptUrl)
        {
            if (scriptUrl.IsNullOrEmpty())
            {
                return(scriptUrl);
            }

            scriptUrl = UrlHelper.ResolveUrl(scriptUrl);

            Initialize();

            if (!isEnabled || bundleKeyBySourceUrl == null)
            {
                return(scriptUrl);
            }

            string bundleKey;

            if (!bundleKeyBySourceUrl.TryGetValue(scriptUrl, out bundleKey))
            {
                return(scriptUrl);
            }

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

            return(UrlHelper.ResolveUrl("~/DynJS.axd/" + include));
        }
Пример #2
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));
        }
Пример #3
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));
        }
Пример #4
0
 public FormScript(string name, Type formType)
 {
     _formType   = formType;
     _name       = name;
     _scriptName = "Form." + name;
     DynamicScriptManager.Register(this);
 }
Пример #5
0
 public TemplateScript(string key, string template)
 {
     _template   = template;
     _key        = key;
     _scriptName = "Template." + key;
     DynamicScriptManager.Register(this);
 }
Пример #6
0
        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));
        }
Пример #7
0
        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));
        }
Пример #8
0
        public static string GetLocalTextInclude(this HtmlHelper page, string package)
        {
            int    languageId = (int)LocalText.ContextLanguageID;
            bool   isPending  = LocalText.ContextPending;
            string scriptName = LocalTextScript.GetScriptName(package, languageId, isPending);

            DynamicScriptManager.IfNotRegistered(scriptName, () =>
            {
                var script = new LocalTextScript(package, languageId, isPending);
                DynamicScriptManager.Register(script);
            });

            return(DynamicScriptManager.GetScriptInclude(scriptName));
        }
Пример #9
0
        public static string GetLocalTextInclude(this HtmlHelper page, string package)
        {
            string languageId = CultureInfo.CurrentUICulture.Name.TrimToNull() ?? "invariant";
            var    context    = Dependency.TryResolve <ILocalTextContext>();
            var    isPending  = context != null && context.IsApprovalMode;
            string scriptName = LocalTextScript.GetScriptName(package, languageId, isPending);

            DynamicScriptManager.IfNotRegistered(scriptName, () =>
            {
                var script = new LocalTextScript(package, (string)languageId, isPending);
                DynamicScriptManager.Register(script);
            });

            return(DynamicScriptManager.GetScriptInclude(scriptName));
        }
Пример #10
0
 static CssBundleManager()
 {
     DynamicScriptManager.ScriptChanged += name =>
     {
         HashSet <string> bundleKeys;
         var b = bundleKeysBySourceUrl;
         if (b != null &&
             b.TryGetValue("dynamic://" + name, out bundleKeys))
         {
             foreach (var bundleKey in bundleKeys)
             {
                 DynamicScriptManager.Changed("Bundle." + bundleKey);
             }
         }
     };
 }
Пример #11
0
        public static void RegisterLookupScripts()
        {
            var assemblies = ExtensibilityHelper.SelfAssemblies;

            foreach (var assembly in assemblies)
            {
                foreach (var type in assembly.GetTypes())
                {
                    var attr = type.GetCustomAttribute <LookupScriptAttribute>();
                    if (attr == null)
                    {
                        continue;
                    }

                    LookupScript script;

                    if (typeof(Row).IsAssignableFrom(type))
                    {
                        script = (LookupScript)Activator.CreateInstance(typeof(RowLookupScript <>).MakeGenericType(type));
                    }
                    else if (!typeof(LookupScript).IsAssignableFrom(type) ||
                             type.GetIsAbstract())
                    {
                        throw new InvalidOperationException(String.Format("Type {0} can't be registered as a lookup script!", type.FullName));
                    }
                    else
                    {
                        script = (LookupScript)Activator.CreateInstance(type);
                    }

                    script.LookupKey = attr.Key;

                    if (attr.Permission != null)
                    {
                        script.Permission = attr.Permission;
                    }

                    if (attr.Expiration != 0)
                    {
                        script.Expiration = TimeSpan.FromSeconds(attr.Expiration);
                    }

                    DynamicScriptManager.Register(script.ScriptName, script);
                }
            }
        }
        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);
        }
Пример #13
0
        static ScriptBundleManager()
        {
            DynamicScriptManager.ScriptChanged += name =>
            {
                var instance = ScriptBundleManager.instance;

                HashSet <string> bundleKeys;
                if (instance != null &&
                    instance.bundleKeysBySourceUrl != null &&
                    instance.bundleKeysBySourceUrl.TryGetValue("dynamic://" + name, out bundleKeys))
                {
                    foreach (var bundleKey in bundleKeys)
                    {
                        DynamicScriptManager.Changed("Bundle." + bundleKey);
                    }
                }
            };
        }
Пример #14
0
        public DataScript(string name, bool authorize = false, string right = null, bool nonCached = false,
                          Func <TData> getData        = null)
        {
            _lookupParams = new Dictionary <string, object>();

            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            _scriptName = name;
            _getData    = getData;
            _authorize  = authorize;
            _right      = right;
            _nonCached  = nonCached;

            LocalExpiration  = CacheExpiration.Never;
            RemoteExpiration = CacheExpiration.OneDay;

            DynamicScriptManager.Register(this);
        }
Пример #15
0
        public static string GetScriptBundle(string scriptUrl)
        {
            scriptUrl = ExpandVersionVariable(scriptUrl);
            scriptUrl = VirtualPathUtility.ToAbsolute(scriptUrl);
            Initialize();

            if (!isEnabled || bundleKeyBySourceUrl == null)
            {
                return(scriptUrl);
            }
            string bundleKey;

            if (!bundleKeyBySourceUrl.TryGetValue(scriptUrl, out bundleKey))
            {
                return(scriptUrl);
            }

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

            return(VirtualPathUtility.ToAbsolute("~/DynJS.axd/" + include));
        }
Пример #16
0
        public static void RegisterFormScripts()
        {
            var assemblies = ExtensibilityHelper.SelfAssemblies;

            var scripts = new List <Func <string> >();

            foreach (var assembly in assemblies)
            {
                foreach (var type in assembly.GetTypes())
                {
                    var attr = type.GetCustomAttribute <FormScriptAttribute>();
                    if (attr != null)
                    {
                        var script = new FormScript(attr.Key, type);
                        DynamicScriptManager.Register(script);
                        scripts.Add(script.GetScript);
                    }
                }
            }

            DynamicScriptManager.Register("FormBundle", new ConcatenatedScript(scripts));
        }
Пример #17
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);
        }
Пример #18
0
        public static void RegisterLookupScripts()
        {
            var assemblies     = ExtensibilityHelper.SelfAssemblies;
            var registeredType = new Dictionary <string, Type>(StringComparer.OrdinalIgnoreCase);

            foreach (var assembly in assemblies)
            {
                foreach (var type in assembly.GetTypes())
                {
                    var attr = type.GetCustomAttribute <LookupScriptAttribute>();
                    if (attr == null)
                    {
                        continue;
                    }

                    LookupScript script;

                    if (typeof(Row).IsAssignableFrom(type))
                    {
                        if (attr.LookupType == null)
                        {
                            script = (LookupScript)Activator.CreateInstance(typeof(RowLookupScript <>).MakeGenericType(type));
                        }
                        else if (attr.LookupType.IsGenericType)
                        {
                            script = (LookupScript)Activator.CreateInstance(attr.LookupType.MakeGenericType(type));
                        }
                        else if (attr.LookupType.GetCustomAttribute <LookupScriptAttribute>() == null)
                        {
                            script = (LookupScript)Activator.CreateInstance(attr.LookupType);
                        }
                        else
                        {
                            // lookup script type already has a LookupScript attribute,
                            // so it's dynamic script will be generated on itself
                            continue;
                        }
                    }
                    else if (!typeof(LookupScript).IsAssignableFrom(type) ||
                             type.IsAbstract)
                    {
                        throw new InvalidOperationException(String.Format("Type {0} can't be registered as a lookup script!", type.FullName));
                    }
                    else
                    {
                        script = (LookupScript)Activator.CreateInstance(type);
                    }

                    script.LookupKey = attr.Key ??
                                       LookupScriptAttribute.AutoLookupKeyFor(type);

                    Type otherType;
                    if (registeredType.TryGetValue(script.LookupKey, out otherType))
                    {
                        throw new InvalidOperationException(String.Format("Types {0} and {1} has the same lookup key (\"{2}\"). " +
                                                                          "\r\n\r\nPlease remove LookupScript attribute from one of them or change the lookup key!",
                                                                          type.FullName, otherType.FullName, script.LookupKey));
                    }

                    registeredType[script.LookupKey] = type;

                    if (attr.Permission != null)
                    {
                        script.Permission = attr.Permission;
                    }

                    if (attr.Expiration != 0)
                    {
                        script.Expiration = TimeSpan.FromSeconds(attr.Expiration);
                    }

                    DynamicScriptManager.Register(script.ScriptName, script);
                }
            }
        }
Пример #19
0
 public string GetScript()
 {
     return("Q$ScriptData.setRegisteredScripts(" + DynamicScriptManager.GetRegisteredScripts().ToJsonFast() + ");");
 }
Пример #20
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();
            }
        }
        public static void RegisterDistinctValueScripts()
        {
            var assemblies = ExtensibilityHelper.SelfAssemblies;
            var list       = new List <DistinctValuesEditorAttribute>();

            foreach (var assembly in assemblies)
            {
                foreach (var type in assembly.GetTypes())
                {
                    bool isRow = type.IsSubclassOf(typeof(Row));

                    if (!isRow &&
                        type.GetCustomAttribute <FormScriptAttribute>() == null &&
                        type.GetCustomAttribute <ColumnsScriptAttribute>() == null)
                    {
                        continue;
                    }

                    if (isRow &&
                        type.IsAbstract)
                    {
                        continue;
                    }

                    foreach (var property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
                    {
                        var attr = property.GetCustomAttribute <DistinctValuesEditorAttribute>();
                        if (attr == null)
                        {
                            continue;
                        }

                        if (attr.RowType != null)
                        {
                            if (attr.RowType.IsInterface ||
                                attr.RowType.IsAbstract ||
                                !attr.RowType.IsSubclassOf(typeof(Row)))
                            {
                                throw new Exception("DistinctValuesEditor can't be used with type: " +
                                                    attr.RowType.FullName + " as it is not a row type. This attribute is specified " +
                                                    "on " + property.Name + " property of " + type.FullName);
                            }

                            attr.PropertyName = attr.PropertyName.IsEmptyOrNull() ? property.Name :
                                                attr.PropertyName;
                        }
                        else
                        {
                            if (!isRow)
                            {
                                var basedOnRowAttr = type.GetCustomAttribute <BasedOnRowAttribute>();
                                if (basedOnRowAttr == null || basedOnRowAttr.RowType == null ||
                                    basedOnRowAttr.RowType.IsAbstract ||
                                    !basedOnRowAttr.RowType.IsSubclassOf(typeof(Row)))
                                {
                                    throw new Exception("Invalid usage of DistinctValuesEditor attribute on " +
                                                        "property " + property.Name + " of " + type.FullName + ". " +
                                                        "RowType has to be specified!");
                                }

                                attr.RowType = basedOnRowAttr.RowType;
                            }
                            else
                            {
                                attr.RowType = type;
                            }

                            attr.PropertyName = attr.PropertyName.IsEmptyOrNull() ? property.Name :
                                                attr.PropertyName;
                        }

                        list.Add(attr);
                    }

                    var byRowProperty = list.ToLookup(x => new Tuple <Type, string>(x.RowType, x.PropertyName));

                    foreach (var key in byRowProperty)
                    {
                        var row = (Row)Activator.CreateInstance(key.Key.Item1);

                        var script = (LookupScript)Activator.CreateInstance(typeof(DistinctValuesScript <>)
                                                                            .MakeGenericType(key.Key.Item1), new object[] { key.Key.Item2 });

                        script.LookupKey = "Distinct." + row.GetFields().LocalTextPrefix + "." +
                                           key.Key.Item2;

                        var withPermission = key.FirstOrDefault(x => !string.IsNullOrEmpty(x.Permission));
                        if (withPermission != null)
                        {
                            script.Permission = withPermission.Permission;
                        }

                        var withExpiration = key.FirstOrDefault(x => x.Expiration != 0);
                        if (withExpiration != null)
                        {
                            script.Expiration = TimeSpan.FromSeconds(withExpiration.Expiration);
                        }

                        DynamicScriptManager.Register(script.ScriptName, script);
                    }
                }
            }
        }
Пример #22
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();
            }
        }
Пример #23
0
        public DbLookupScript(string name, string schema = null, bool authorize = false, string right = null, bool nonCached = false,
                              Func <IDbConnection, IEnumerable <TItem> > getItems = null)
        {
            _lookupParams = new Dictionary <string, object>();

            Row row = null;

            if (typeof(TItem).IsSubclassOf(typeof(Row)))
            {
                row = (Row)(object)(new TItem());
            }

            if (name == null)
            {
                if (row == null)
                {
                    throw new ArgumentNullException("name");
                }

                name = row.Table;
            }

            if (row != null)
            {
                Field field;

                var idRow = row as IIdRow;
                if (idRow != null)
                {
                    field   = ((Field)idRow.IdField);
                    IdField = field.PropertyName ?? field.Name;
                }

                var nameRow = row as INameRow;
                if (nameRow != null)
                {
                    field     = ((Field)nameRow.NameField);
                    TextField = field.PropertyName ?? field.Name;
                }

                var treeRow = row as IParentIdRow;
                if (treeRow != null)
                {
                    field         = ((Field)treeRow.ParentIdField);
                    ParentIdField = field.PropertyName ?? field.Name;
                }
            }

            _scriptName = "Lookup." + name;

            if (schema == null)
            {
                if (row != null)
                {
                    schema = RowRegistry.GetSchemaName(row);
                }
                else
                {
                    schema = RowRegistry.DefaultSchema;
                }
            }

            _schema = schema;

            _lookup    = name;
            _getItems  = getItems;
            _authorize = authorize;
            _right     = right;
            _nonCached = nonCached;

            if (row != null)
            {
                GlobalGenerationKey = row.GetFields().GenerationKey;
            }

            LocalExpiration  = CacheExpiration.Never;
            RemoteExpiration = CacheExpiration.OneDay;

            DynamicScriptManager.Register(this);
        }
Пример #24
0
        public DbLookupScript(string name, string connectionKey = null, bool authorize = false, string right = null, bool nonCached = false,
                              Func <IDbConnection, IEnumerable <TItem> > getItems = null)
        {
            _lookupParams = new Dictionary <string, object>();

            Row row = null;

            if (typeof(TItem).IsSubclassOf(typeof(Row)))
            {
                row = (Row)(object)(new TItem());
            }

            if (name == null)
            {
                if (row == null)
                {
                    throw new ArgumentNullException("name");
                }

                name = row.Table;
            }

            if (row != null)
            {
                Field field;

                var idRow = row as IIdRow;
                if (idRow != null)
                {
                    field   = ((Field)idRow.IdField);
                    IdField = field.PropertyName ?? field.Name;
                }

                var nameField = row.GetNameField();
                if (!ReferenceEquals(null, nameField))
                {
                    TextField = nameField.PropertyName ?? nameField.Name;
                }

                var treeRow = row as IParentIdRow;
                if (treeRow != null)
                {
                    field         = ((Field)treeRow.ParentIdField);
                    ParentIdField = field.PropertyName ?? field.Name;
                }
            }

            _scriptName = "Lookup." + name;

            if (connectionKey == null)
            {
                if (row != null)
                {
                    connectionKey = row.GetFields().ConnectionKey;
                }
                else
                {
                    connectionKey = RowRegistry.DefaultConnectionKey;
                }
            }

            _schema = connectionKey;

            _lookup    = name;
            _getItems  = getItems;
            _authorize = authorize;
            _right     = right;
            _nonCached = nonCached;

            if (row != null)
            {
                GroupKey = row.GetFields().GenerationKey;
            }

            Expiration = _nonCached ? TimeSpan.FromDays(-1) : TimeSpan.Zero;

            DynamicScriptManager.Register(this);
        }
Пример #25
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;
        }
        public static void Initialize(IEnumerable <Assembly> assemblies)
        {
            Check.NotNull(assemblies, "assemblies");

            DataScriptAttribute attr;

            foreach (var assembly in assemblies)
            {
                foreach (var type in assembly.GetTypes())
                {
                    if (type.IsAbstract ||
                        type.IsInterface ||
                        type.IsGenericTypeDefinition ||
                        !type.IsPublic)
                    {
                        continue;
                    }

                    attr = type.GetCustomAttribute <DataScriptAttribute>();
                    if (attr != null)
                    {
                        var script = (INamedDynamicScript)Activator.CreateInstance(type);
                        DynamicScriptManager.Register(script);
                        continue;
                    }

                    if (!type.IsSubclassOf(typeof(Controller)))
                    {
                        continue;
                    }

                    foreach (var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public))
                    {
                        attr = method.GetCustomAttribute <DataScriptAttribute>();
                        if (attr == null)
                        {
                            continue;
                        }

                        if (string.IsNullOrEmpty(attr.Key))
                        {
                            throw new ArgumentNullException("scripKey", String.Format(
                                                                "DataScript attribute on method {1} of type {0} has empty key!",
                                                                type.Name, method.Name));
                        }

                        var parameters = method.GetParameters();
                        if (parameters.Length > 2 ||
                            parameters.Any(x => x.ParameterType != typeof(ServiceRequest) &&
                                           x.ParameterType != typeof(IDbConnection)))
                        {
                            throw new ArgumentOutOfRangeException("parameters", String.Format(
                                                                      "DataScript actions shouldn't have any parameters other " +
                                                                      "than an a base ServiceRequest and optional IDbConnection. Method {0} of type {1} has {2} arguments",
                                                                      type.Name, method.Name, parameters.Length));
                        }

                        string connectionKey = null;

                        if (parameters.Any(x => x.ParameterType == typeof(IDbConnection)))
                        {
                            var connectionKeyAttr = type.GetCustomAttribute <ConnectionKeyAttribute>();
                            if (connectionKeyAttr == null || connectionKeyAttr.Value.IsEmptyOrNull())
                            {
                                throw new ArgumentOutOfRangeException("connectionKey", String.Format(
                                                                          "Cannot determine connection key for DynamicScript defined on type {0}, method {1}",
                                                                          type.Name, method.Name));
                            }

                            connectionKey = connectionKeyAttr.Value;
                        }

                        var returnType = method.ReturnType;

                        if (returnType == typeof(void))
                        {
                            throw new ArgumentOutOfRangeException("returnType", String.Format(
                                                                      "DynamicScript defined on method {1} of type {0} has void return type",
                                                                      type.Name, method.Name));
                        }

                        var isResult = returnType.IsGenericType &&
                                       returnType.GetGenericTypeDefinition() == typeof(Result <>);
                        if (!isResult && typeof(ActionResult).IsAssignableFrom(returnType))
                        {
                            throw new ArgumentOutOfRangeException("returnType", String.Format(
                                                                      "DynamicScript defined on method {1} of type {0} has ActionResult descendant return type. " +
                                                                      "It must be Result<T> or a regular class!",
                                                                      type.Name, method.Name));
                        }

                        var dataScript = new DataScript(attr.Key, delegate()
                        {
                            var controller = Activator.CreateInstance(type);

                            object result;

                            object[] prm;
                            if (parameters.Length == 0)
                            {
                                prm = null;
                            }
                            else
                            {
                                prm = new object[parameters.Length];
                            }

                            IDbConnection connection = null;
                            try
                            {
                                for (var i = 0; i < parameters.Length; i++)
                                {
                                    if (parameters[i].ParameterType == typeof(ServiceRequest))
                                    {
                                        prm[i] = new ServiceRequest();
                                    }
                                    else
                                    {
                                        if (connection == null)
                                        {
                                            connection = SqlConnections.NewByKey(connectionKey);
                                        }

                                        prm[i] = connection;
                                    }
                                }

                                result = method.Invoke(controller, prm);
                            }
                            finally
                            {
                                if (connection != null)
                                {
                                    connection.Dispose();
                                }
                            }

                            if (isResult)
                            {
                                result = ((dynamic)result).Data;
                            }

                            return(result);
                        });

                        dataScript.Expiration = TimeSpan.FromSeconds(attr.CacheDuration);
                        dataScript.GroupKey   = attr.CacheGroupKey;

                        var serviceAuthorize = method.GetCustomAttribute <ServiceAuthorizeAttribute>() ??
                                               type.GetCustomAttribute <ServiceAuthorizeAttribute>();

                        if (serviceAuthorize != null)
                        {
                            dataScript.Permission = serviceAuthorize.Permission ?? "?";
                        }
                        else
                        {
                            var authorize = method.GetCustomAttribute <AuthorizeAttribute>() ??
                                            type.GetCustomAttribute <AuthorizeAttribute>();

                            if (authorize != null)
                            {
                                dataScript.Permission = "?";
                            }
                        }

                        DynamicScriptManager.Register(dataScript.ScriptName, dataScript);
                    }
                }
            }
        }
 public override string GetScript()
 {
     return("Q.ScriptData.setRegisteredScripts(" +
            ToJsonFast(DynamicScriptManager.GetRegisteredScripts()) + ");");
 }