public void Process(BundleContext context, BundleResponse response)
 {
     var config = new DotlessConfiguration();
     // config.Plugins.Add(new BuildNumberPluginConfigurator());
     response.Content = Less.Parse(response.Content, config);
     response.ContentType = "text/css";
 }
        public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<BundleFile> files)
        {
            if (files == null)
            {
                return string.Empty;
            }

            var buffer = new StringBuilder();

            foreach (var current in files)
            {
                buffer.AppendLine();

                var extension = Path.GetExtension(current.VirtualFile.Name) ?? "";
                var fileContent = RetrieveFileContent(current);

                if (extension.Equals(".html", StringComparison.OrdinalIgnoreCase)
                    || extension.Equals(".htm", StringComparison.OrdinalIgnoreCase))
                {

                    var templateName = Path.GetFileNameWithoutExtension(current.VirtualFile.Name);

                    var compiler = new UnderscoreTemplateCompiler();

                    buffer.AppendLine("var " + templateName + "Tpl = " + compiler.Compile(fileContent));
                }
                else
                {
                    buffer.AppendLine(fileContent);
                }
            }
            return buffer.ToString();
        }
 public void Process(BundleContext context, BundleResponse response)
 {
     string content = response.get_Content();
     StringBuilder stringBuilder = new StringBuilder();
     char[] chrArray = new char[1];
     chrArray[0] = '\n';
     string[] strArrays = content.Split(chrArray);
     for (int i = 0; i < (int)strArrays.Length; i++)
     {
         string str = strArrays[i];
         Match match = Regex.Match(str, "url\\([\\\"\\'](.*)\\?embed[\\\"\\']\\)");
         if (match.Success)
         {
             string str1 = match.Result("$1");
             str1 = ConvertCssUrlsToDataUris.CleanPath(str1);
             try
             {
                 str1 = HttpContext.Current.Server.MapPath(str1);
             }
             catch (ArgumentException argumentException)
             {
                 throw new Exception(string.Concat("Illegal Characters : ", str1));
             }
             stringBuilder.AppendLine(str.Replace(match.Result("$0"), this.GetDataUri(str1)));
             stringBuilder.AppendLine(str.Replace("background", "*background"));
         }
         else
         {
             stringBuilder.Append(str);
         }
     }
     response.set_ContentType("text/css");
     response.set_Content(stringBuilder.ToString());
 }
        public void Process(BundleContext context, BundleResponse response)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

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

            // Grab all of the content.
            var rawContent = new StringBuilder();
            foreach (var fileInfo in response.Files)
            {
                using (var stream = fileInfo.VirtualFile.Open())
                {
                    using (var streamReader = new StreamReader(stream))
                    {
                        rawContent.Append(streamReader.ReadToEnd());
                    }
                }
            }

            // Now lets compress.
            var compressor = DetermineCompressor(_compressorConfig);
            var output = compressor.Compress(rawContent.ToString());
            context.HttpContext.Response.Cache.SetLastModifiedFromFileDependencies();
            response.Content = output;
            response.ContentType = compressor.ContentType;
        }
Beispiel #5
0
        /// <summary>
        /// Ordena os scripts por funcao: Modules, Services e Controllers
        /// </summary>
        /// <param name="context"></param>
        /// <param name="files"></param>
        /// <returns></returns>
        public IEnumerable<BundleFile> OrderFiles(BundleContext context, IEnumerable<BundleFile> files)
        {
            var modules = new List<BundleFile>();
            var services = new List<BundleFile>();
            var controllers = new List<BundleFile>();

            foreach (var item in files)
            {
                if (item.VirtualFile.Name.Contains("service"))
                {
                    services.Add(item);
                }
                else if (item.VirtualFile.Name.Contains("controller"))
                {
                    controllers.Add(item);
                }
                else
                {
                    modules.Add(item);
                }
            }

            var allFiles = new List<BundleFile>();

            allFiles.AddRange(modules);
            allFiles.AddRange(services);
            allFiles.AddRange(controllers);

            return allFiles;
        }
        public void Process(BundleContext context, BundleResponse response)
        {
            var coffeeScriptPath =
                Path.Combine(
                    HttpRuntime.AppDomainAppPath,
                    "Scripts",
                    "coffee-script.js");

            if (!File.Exists(coffeeScriptPath))
            {
                throw new FileNotFoundException(
                    "Could not find coffee-script.js beneath the ~/Scripts directory.");
            }

            var coffeeScriptCompiler =
                File.ReadAllText(coffeeScriptPath, Encoding.UTF8);

            var engine = new ScriptEngine();
            engine.Execute(coffeeScriptCompiler);

            // Initializes a wrapper function for the CoffeeScript compiler.
            var wrapperFunction =
                string.Format(
                    "var compile = function (src) {{ return CoffeeScript.compile(src, {{ bare: {0} }}); }};",
                    _bare.ToString(CultureInfo.InvariantCulture).ToLower());
            
            engine.Execute(wrapperFunction);
            
            var js = engine.CallGlobalFunction("compile", response.Content);
                
            response.ContentType = ContentTypes.JavaScript;
            response.Content = js.ToString();
        }
        public void GivenAJavascriptFile_Process_ReturnsABundledResponse()
        {
            // Arrange.
            var compressorConfig = new JavaScriptCompressorConfig();
            var transform = new YuiCompressorTransform(compressorConfig);
            var contextBase = A.Fake<HttpContextBase>();
            var bundles = new BundleCollection();
            var javascriptContent = File.ReadAllText("Javascript Files\\jquery-1.10.2.js");
            var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(javascriptContent));
            var fakeStream = A.Fake<Stream>(x => x.Wrapping(memoryStream));
            var fakeVirtualFile = A.Fake<VirtualFile>(x => x.WithArgumentsForConstructor(new[] { "/Scripts/jquery-1.10.2.js" }));
            fakeVirtualFile.CallsTo(x => x.Open()).Returns(fakeStream);

            
            var bundleFiles = new List<BundleFile>
            {
                new BundleFile("/Scripts/jquery-1.10.2.js", fakeVirtualFile)
            };
            var bundleContext = new BundleContext(contextBase, bundles, "~/bundles/jquery");
            var bundleResponse = new BundleResponse(null, bundleFiles);

            // Act.
            transform.Process(bundleContext, bundleResponse);

            // Assert.
            bundleResponse.ShouldNotBe(null);
            bundleResponse.Content.Substring(0, 300).ShouldBe("/*\n * jQuery JavaScript Library v1.10.2\n * http://jquery.com/\n *\n * Includes Sizzle.js\n * http://sizzlejs.com/\n *\n * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors\n * Released under the MIT license\n * http://jquery.org/license\n *\n * Date: 2013-07-03T13:48Z\n */\n(function(bW,bU){v");
            bundleResponse.Content.Length.ShouldBe(105397);

            memoryStream.Dispose();
        }
        public override void Process(BundleContext context, BundleResponse response)
        {
            var compressor = new CssCompressor();

            response.Content = compressor.Compress(response.Content);
            response.ContentType = ContentTypes.Css;
        }    
Beispiel #9
0
          private async static void GenerateBundleJS(ScriptBundle scriptBundle, BundleCollection bundles)
        {
            string bundleOutputPath = Path.Combine(HttpRuntime.AppDomainAppPath, BundleOutputFile);
            BundleContext context = new BundleContext(new HttpContextWrapper(HttpContext.Current), bundles, ScriptsBundleVirtualPath);
            System.Text.StringBuilder fileSpacer = new System.Text.StringBuilder();

            try
            {
                using (StreamWriter outputStream = new StreamWriter(bundleOutputPath))
                {
                    outputStream.BaseStream.Seek(0, SeekOrigin.End);
                    System.Collections.Generic.List<string> filePaths = PrepareFileList(scriptBundle.EnumerateFiles(context));

                    foreach (string filePath in filePaths)
                    {
                        string fileSpacerText = BuildFileSpacer(fileSpacer, filePath);

                        await outputStream.WriteAsync(fileSpacerText);

                        using (StreamReader jsFileStream = new StreamReader(filePath))
                        {
                            await outputStream.WriteAsync(await jsFileStream.ReadToEndAsync());
                        }
                    }
                }
            }
            catch (System.NullReferenceException nullEx)
            {
                string error = nullEx.Message;
            }
        }
 public void Process(BundleContext context, BundleResponse response)
 {
     if (!response.Files.Any(f => f.VirtualFile.VirtualPath.ToLowerInvariant().Contains("jquery")))
     {
         response.Content = CopyrigthText + response.Content;
     }
 }
        public void Process(BundleContext context, BundleResponse bundle)
        {
            context.HttpContext.Response.Cache.SetLastModifiedFromFileDependencies();

            var lessParser = new Parser();
            ILessEngine lessEngine = CreateLessEngine(lessParser);

            var content = new StringBuilder();

            var bundleFiles = new List<BundleFile>();

            foreach (var bundleFile in bundle.Files)
            {
                bundleFiles.Add(bundleFile);

                SetCurrentFilePath(lessParser, bundleFile.VirtualFile.VirtualPath);

                using (var reader = new StreamReader(VirtualPathProvider.OpenFile(bundleFile.VirtualFile.VirtualPath)))
                {
                    content.Append(lessEngine.TransformToCss(reader.ReadToEnd(), bundleFile.VirtualFile.VirtualPath));
                    content.AppendLine();

                    bundleFiles.AddRange(GetFileDependencies(lessParser));
                }
            }

            if (BundleTable.EnableOptimizations)
            {
                // include imports in bundle files to register cache dependencies
                bundle.Files = bundleFiles.Distinct().ToList();
            }

            bundle.ContentType = "text/css";
            bundle.Content = content.ToString();
        }
        /// <summary>
        /// The implementation of the <see cref="IBundleTransform"/> interface
        /// </summary>
        /// <param name="context"></param>
        /// <param name="response"></param>
        public void Process(BundleContext context, BundleResponse response)
        {
            if (null == context)
            {
                throw new ArgumentNullException("context");
            }
            if (null == response)
            {
                throw new ArgumentNullException("response");
            }

            var urlMatcher = new Regex(@"url\((['""]?)(.+?)\1\)", RegexOptions.IgnoreCase);

            var content = new StringBuilder();
            foreach (var fileInfo in response.Files)
            {
                if (fileInfo.Directory == null)
                {
                    continue;
                }
                var fileContent = _fileProvider.ReadAllText(fileInfo.FullName);
                var directory = fileInfo.Directory.FullName;
                content.Append(urlMatcher.Replace(fileContent, match => ProcessMatch(match, directory)));
            }
            
            context.HttpContext.Response.Cache.SetLastModifiedFromFileDependencies();
            response.Content = content.ToString();
            response.ContentType = CssContentType;
        }
		public void Process(BundleContext context, BundleResponse response)
		{
			Assert.ArgumentNotNull(response, "response");

			response.Content = new CssCompressor().Compress(response.Content);
			response.ContentType = "text/css";
		}
Beispiel #14
0
		public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<BundleFile> files)
		{
			var rewriteTransform = new CssRewriteUrlTransform();
			var bundleFiles = files as IList<BundleFile> ?? files.ToList();
			bundleFiles.ForEach(x => x.Transforms.Add(rewriteTransform));
			return new DefaultBundleBuilder().BuildBundleContent(bundle, context, bundleFiles);
		}
		private void SetBundleHeaders(BundleResponse bundleResponse, BundleContext context)
		{
			if (context.HttpContext.Response == null)
			{
				return;
			}

			if (bundleResponse.ContentType != null)
			{
				context.HttpContext.Response.ContentType = bundleResponse.ContentType;
			}

			if (context.EnableInstrumentation || context.HttpContext.Response.Cache == null)
			{
				return;
			}

			HttpCachePolicyBase cache = context.HttpContext.Response.Cache;
			cache.SetCacheability(bundleResponse.Cacheability);
			cache.SetOmitVaryStar(true);
			cache.SetExpires(DateTime.Now.AddYears(1));
			cache.SetValidUntilExpires(true);
			cache.SetLastModified(DateTime.Now);
			cache.VaryByHeaders["User-Agent"] = true;
		}
Beispiel #16
0
        public void Process(BundleContext context, BundleResponse response)
        {
            var strBundleResponse = new StringBuilder();
            // Javascript module for Angular that uses templateCache
            strBundleResponse.AppendFormat(
                @"angular.module('{0}').run(['$templateCache',function(t){{",
                _moduleName);

            foreach (var file in response.Files)
            {
                string content;

                //Get content
                using (var stream = new StreamReader(file.VirtualFile.Open()))
                {
                    content = stream.ReadToEnd();
                }

                //Remove breaks and escape qoutes
                content = Regex.Replace(content, @"\r\n?|\n", "");
                content = content.Replace("'", "\\'");

                // Create insert statement with template
                strBundleResponse.AppendFormat(
                    @"t.put('{0}','{1}');", file.VirtualFile.VirtualPath.Substring(1), content);
            }
            strBundleResponse.Append(@"}]);");

            response.Files = new BundleFile[] {};
            response.Content = strBundleResponse.ToString();
            response.ContentType = "text/javascript";
        }
Beispiel #17
0
        public void Process(BundleContext context, BundleResponse response)
        {
            Directory.SetCurrentDirectory(path);

            response.Content = Less.Parse(response.Content);
            response.ContentType = "text/css";
        }
    public void Process(BundleContext context, BundleResponse bundle)
    {
        if (bundle == null)
        {
            throw new ArgumentNullException("bundle");
        }

        context.HttpContext.Response.Cache.SetLastModifiedFromFileDependencies();

        var lessParser = new Parser();
        ILessEngine lessEngine = CreateLessEngine(lessParser);

        var content = new StringBuilder(bundle.Content.Length);

        foreach (FileInfo file in bundle.Files)
        {
            SetCurrentFilePath(lessParser, file.FullName);
            string source = File.ReadAllText(file.FullName);
            content.Append(lessEngine.TransformToCss(source, file.FullName));
            content.AppendLine();

            AddFileDependencies(lessParser);
        }

        bundle.ContentType = "text/css";
        bundle.Content = content.ToString();
    }
        public void Process(BundleContext context, BundleResponse response)
        {
            var builder = new StringBuilder();

            foreach (var file in response.Files)
            {
                IBundleTransform transform = null;

                if (file.Extension.Equals(
                    ".coffee",
                    StringComparison.OrdinalIgnoreCase))
                {
                    transform = new CoffeeScriptTransform(_bare);
                }
                else if (file.Extension.Equals(
                    ".js",
                    StringComparison.OrdinalIgnoreCase))
                {
                    transform = new CommonNoTransform(ContentTypes.JavaScript);
                }

                if (transform == null || !File.Exists(file.FullName))
                    continue;

                response.Content = 
                    File.ReadAllText(file.FullName, Encoding.UTF8);

                transform.Process(context, response);

                builder.AppendLine(response.Content);
            }

            response.ContentType = ContentTypes.JavaScript;
            response.Content = builder.ToString();
        }
		private void TransformUrls(BundleContext context, BundleResponse response)
		{
			response.Content = String.Empty;

			var builder = new StringBuilder();

			foreach (var cssFileInfo in response.Files)
			{
				if (cssFileInfo.VirtualFile == null) continue;

				string content;
				using (var streamReader = new StreamReader(cssFileInfo.VirtualFile.Open())) { content = streamReader.ReadToEnd(); }
				if (content.IsNullOrWhiteSpace()) continue;

				var matches = _pattern.Matches(content);
				if (matches.Count > 0)
				{
					foreach (Match match in matches)
					{
						var cssRelativeUrl = match.Groups[2].Value;
						var rootRelativeUrl = TransformUrl(context, cssRelativeUrl, cssFileInfo);

						var quote = match.Groups[1].Value;
						var replace = String.Format("url({0}{1}{0})", quote, rootRelativeUrl);
						content = content.Replace(match.Groups[0].Value, replace);
					}
				}

				builder.AppendLine(content);
			}

			response.ContentType = "text/css";
			response.Content = builder.ToString();
		}
        public IEnumerable<FileInfo> OrderFiles(BundleContext context, IEnumerable<FileInfo> files)
        {
            var workingItems = files.AsParallel().Select(i => new _WorkingItem {
                Path = i.FullName,
                FileInfo = i,
                Dependencies = this._GetDependencies(i.FullName),
            });

            var fileDependencies = new Dictionary<string, _WorkingItem>(_DependencyNameComparer);
            foreach (var item in workingItems) {
                _WorkingItem duplicate;
                if (fileDependencies.TryGetValue(item.Path, out duplicate))
                    throw new ArgumentException(string.Format("During dependency resolution, a collision between '{0}' and '{1}' was detected. Files in a bundle must not collide with respect to the dependency name comparer.", Path.GetFileName(item.Path), Path.GetFileName(duplicate.Path)));

                fileDependencies.Add(item.Path, item);
            }

            foreach (var item in fileDependencies.Values) {
                foreach (var dependency in item.Dependencies) {
                    if (!fileDependencies.ContainsKey(dependency))
                        throw new ArgumentException(string.Format("Dependency '{0}' referenced by '{1}' could not found. Ensure the dependency is part of the bundle and its name can be detected by the dependency name comparer. If the dependency is not supposed to be in the bundle, add it to the list of excluded dependencies.", Path.GetFileName(dependency), Path.GetFileName(item.Path)));
                }
            }

            while (fileDependencies.Count > 0) {
                var result = fileDependencies.Values.FirstOrDefault(f => f.Dependencies.All(d => !fileDependencies.ContainsKey(d)));
                if (result == null)
                    throw new ArgumentException(string.Format("During dependency resolution, a cyclic dependency was detected among the remaining dependencies {0}.", string.Join(", ", fileDependencies.Select(d => "'" + Path.GetFileName(d.Value.Path) + "'"))));
                yield return result.FileInfo;
                fileDependencies.Remove(result.Path);
            }
        }
        /// <summary>
        ///     The process.
        /// </summary>
        /// <param name="context">
        ///     The context.
        /// </param>
        /// <param name="bundleResponse">
        ///     The bundle response.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     Argument NULL Exception
        /// </exception>
        public void Process(BundleContext context, BundleResponse bundleResponse)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

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

            context.HttpContext.Response.Cache.SetLastModifiedFromFileDependencies();

            IEnumerable<BundleFile> bundleFiles = bundleResponse.Files;
            bundleResponse.Content = Process(ref bundleFiles);

            // set bundle response files back (with imported ones)
            if (context.EnableOptimizations)
            {
                bundleResponse.Files = bundleFiles;
            }

            bundleResponse.ContentType = "text/css";
        }
        /// <summary>
        ///     Returns virtual paths of included files in <paramref name="virtualPath" />  file, according to
        ///     <paramref name="context" />.
        ///     If not added yet and <see cref="LessTransform" /> included in bundle transforms, executes
        ///     <see cref="LessTransform" /> transformation for the specified <paramref name="bundle" />
        ///     and ensures the dependencies are saved.
        /// </summary>
        /// <param name="bundle">Bundle to process, if not yet</param>
        /// <param name="virtualPath">Root  file to get dependencies for.</param>
        /// <param name="context">Current context.</param>
        /// <returns>Virtual paths of included files.</returns>
        private static IEnumerable<string> GetFileDependencies(Bundle bundle, string virtualPath, BundleContext context)
        {
            string key = BundleTable.VirtualPathProvider.GetCacheKey(virtualPath) ?? virtualPath;

            Func<string, IList<string>> process;

            if (bundle.Transforms.Any(transform => transform is LessTransform))
            {
                process = s =>
                {
                    IEnumerable<BundleFile> files = bundle.EnumerateFiles(context);
                    LessTransform.Process(ref files);
                    return files.Select(file => file.IncludedVirtualPath).ToArray();
                };
            }
            else
            {
                process = s => new string[0];
            }

            _fileDependencies.GetOrAdd(key, process);

            // returns more specific dependencies by the key containing transient file paths
            return _fileDependencies.GetOrAdd(GetTransientFileKey(virtualPath), process);
        }
        public override BundleResponse GenerateBundleResponse(BundleContext context)
        {
            // This is overridden, because BudleTransformer adds LESS @imports
            // to the Bundle.Files collection. This is bad as we allow switching
            // Optimization mode per UI. Switching from true to false would also include
            // ALL LESS imports in the generated output ('link' tags)

            // get all ORIGINAL bundle parts (including LESS parents, no @imports)
            var files = this.EnumerateFiles(context);

            // replace file pattern like {version} and let Bundler resolve min/debug extensions.
            files = context.BundleCollection.FileExtensionReplacementList.ReplaceFileExtensions(context, files);
            // save originals for later use
            _originalBundleFilePathes = files.Select(x => x.IncludedVirtualPath.TrimStart('~')).ToArray();

            var response = base.GenerateBundleResponse(context);
            // at this stage, BundleTransformer pushed ALL LESS @imports to Bundle.Files, which is bad...

            _transformedBundleFiles = response.Files;

            if (!CacheIsEnabled(context))
            {
                // ...so we must clean the file list immediately when caching is disabled ('cause UpdateCache() will not run)
                CleanBundleFiles(response);
            }

            return response;
        }
		public void Process(BundleContext context, BundleResponse response)
		{
			var pathsAllowed = new[]
				                   {
					                   context.HttpContext.Server.MapPath("~/Content/css/"),
					                   context.HttpContext.Server.MapPath(BundleConfig.AdminThemeDirectory)
				                   };

			var builder = new StringBuilder();
			foreach (var bundleFile in response.Files)
			{
				string normalizeFile = context.HttpContext.Server.MapPath(bundleFile.IncludedVirtualPath);
				if (pathsAllowed.Any(normalizeFile.StartsWith) == false)
					throw new Exception("Path not allowed");

				if (File.Exists(normalizeFile) == false)
					continue;

				var content = File.ReadAllText(normalizeFile);
				string path;
				if (FilesToNormalize.TryGetValue(bundleFile.VirtualFile.Name, out path))
					content = NormalizeImports(content, context.HttpContext.Server.MapPath(path));

				builder.AppendLine(content);
			}

			response.Content = Less.Parse(builder.ToString(), new DotlessConfiguration { DisableUrlRewriting = true });
			response.ContentType = "text/css";
		}
        public void Process(BundleContext context, BundleResponse response)
        {
            var compiler = new HandlebarsCompiler();
            var templates = new Dictionary<string, string>();
            var server = context.HttpContext.Server;

            foreach (var bundleFile in response.Files)
            {
                var filePath = server.MapPath(bundleFile.VirtualFile.VirtualPath);
                var bundleRelativePath = GetRelativePath(server, bundleFile, filePath);
                var templateName = namer.GenerateName(bundleRelativePath, bundleFile.VirtualFile.Name);
                var template = File.ReadAllText(filePath);
                var compiled = compiler.Precompile(template, false);

                templates[templateName] = compiled;
            }
            StringBuilder javascript = new StringBuilder();
            foreach (var templateName in templates.Keys)
            {
                javascript.AppendFormat("Ember.TEMPLATES['{0}']=", templateName);
                javascript.AppendFormat("Ember.Handlebars.template({0});", templates[templateName]);
            }

            var Compressor = new JavaScriptCompressor();
            var compressed = Compressor.Compress(javascript.ToString());

            response.ContentType = "text/javascript";
            response.Cacheability = HttpCacheability.Public;
            response.Content = compressed;
        }
 /// <summary>
 ///     Returns cache key for <paramref name="bundle" />.
 /// </summary>
 /// <param name="bundle"><see cref="Bundle" /> to get cache for.</param>
 /// <param name="context">Current <see cref="BundleContext" /></param>
 /// <returns>Cache key string.</returns>
 internal static string GetTransientBundleFilesKey(this Bundle bundle, BundleContext context)
 {
     return ComposeTransientFilesKey(bundle
         .EnumerateFiles(context)
         .SelectMany(file => new[] {file.IncludedVirtualPath}.Concat(
             GetFileDependencies(bundle, file.IncludedVirtualPath, context))));
 }
 public override IEnumerable<BundleFile> OrderFiles(BundleContext context, IEnumerable<BundleFile> files)
 {
     var result = base.OrderFiles(context, files);
     return result.Where(f => f.VirtualFile.Name.Equals(_filename, StringComparison.OrdinalIgnoreCase))
         .Concat(
             result.Where(f => !f.VirtualFile.Name.Equals(_filename, StringComparison.OrdinalIgnoreCase)));
 }
Beispiel #29
0
        public virtual void Process(BundleContext context, BundleResponse response)
        {
            var file = VirtualPathUtility.GetFileName(context.BundleVirtualPath);

            if (!context.BundleCollection.UseCdn)
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(ContainerName))
            {
                throw new Exception("ContainerName Not Set");
            }

            var connectionString = CloudConfigurationManager.GetSetting("StorageConnectionString");

            var conn = CloudStorageAccount.Parse(connectionString);
            var cont = conn.CreateCloudBlobClient().GetContainerReference(ContainerName);
            cont.CreateIfNotExists(BlobContainerPublicAccessType.Blob);
            var blob = cont.GetBlockBlobReference(file);

            blob.Properties.ContentType = response.ContentType;
            blob.UploadText(response.Content);

            var uri = string.IsNullOrWhiteSpace(CdnHost) ? blob.Uri.AbsoluteUri.Replace("http:", "").Replace("https:", "") : string.Format("{0}/{1}/{2}", CdnHost, ContainerName, file);

            using (var hashAlgorithm = CreateHashAlgorithm())
            {
                var hash = HttpServerUtility.UrlTokenEncode(hashAlgorithm.ComputeHash(Encoding.Unicode.GetBytes(response.Content)));
                context.BundleCollection.GetBundleFor(context.BundleVirtualPath).CdnPath = string.Format("{0}?v={1}", uri, hash);
            }
        }
Beispiel #30
0
        public void Process(BundleContext context, BundleResponse response)
        {
            var isDebug = context.HttpContext.IsDebuggingEnabled;

            if (isDebug && !Directory.Exists(GeneratedTemplatesPath)) Directory.CreateDirectory(GeneratedTemplatesPath);

            var str = new StringBuilder();
            str.Append(BeginScript);

            var results = new List<FileInfo>();
            foreach (var file in response.Files.Select(o => new { Name = o.Name, Value = EncodeItem(o) }))
            {
                str.Append(PushScript);
                str.Append(file.Value);
                str.Append(EndScript);

                if (!isDebug) continue;

                var fileName = GenerateTemplate(file.Name, file.Value);
                results.Add(new FileInfo(fileName));
            }

            response.Files = results;
            response.Content = str.ToString();
            response.ContentType = ContentType;
        }
Beispiel #31
0
 public void AddScripts(BundleContext context)
 {
     context.Add("_content/Blazorise/blazorise.js");
     context.Add("_content/Blazorise.Bootstrap/blazorise.bootstrap.js");
 }
Beispiel #32
0
        private async Task ProcessFileImpl(IWebFile file, BundleOptions bundleOptions, BundleContext bundleContext)
        {
            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }

            var extension = Path.GetExtension(file.FilePath);

            var fileWatchEnabled = bundleOptions?.FileWatchOptions.Enabled ?? false;

            Lazy <IFileInfo> fileInfo;
            var cacheBuster = bundleOptions != null
                ? _cacheBusterResolver.GetCacheBuster(bundleOptions.GetCacheBusterType())
                : _cacheBusterResolver.GetCacheBuster(_bundleManager.GetDefaultBundleOptions(false).GetCacheBusterType()); //the default for any dynamically (non bundle) file is the default bundle options in production

            var cacheFile = _fileSystemHelper.GetCacheFilePath(file, fileWatchEnabled, extension, cacheBuster, out fileInfo);

            var exists = File.Exists(cacheFile);

            //check if it's in cache
            if (exists)
            {
                _logger.LogDebug($"File already in cache '{file.FilePath}', type: {file.DependencyType}, cacheFile: {cacheFile}, watching? {fileWatchEnabled}");
            }
            else
            {
                if (file.Pipeline.Processors.Count > 0)
                {
                    _logger.LogDebug($"Processing file '{file.FilePath}', type: {file.DependencyType}, cacheFile: {cacheFile}, watching? {fileWatchEnabled} ...");
                    var contents = await _fileSystemHelper.ReadContentsAsync(fileInfo.Value);

                    var watch = new Stopwatch();
                    watch.Start();
                    //process the file
                    var processed = await file.Pipeline.ProcessAsync(new FileProcessContext(contents, file, bundleContext));

                    watch.Stop();
                    _logger.LogDebug($"Processed file '{file.FilePath}' in {watch.ElapsedMilliseconds}ms");
                    //save it to the cache path
                    await _fileSystemHelper.WriteContentsAsync(cacheFile, processed);
                }
                else
                {
                    // we can just copy the the file as-is to the cache file
                    _fileSystemHelper.CopyFile(fileInfo.Value.PhysicalPath, cacheFile);
                }
            }

            //If file watching is enabled, then watch it - this is regardless of whether the cache file exists or not
            // since after app restart if there's already a cache file, we still want to watch the file set
            if (fileWatchEnabled)
            {
                // watch this file for changes, if the file is already watched this will do nothing
                _fileSystemHelper.Watch(file, fileInfo.Value, bundleOptions, FileModified);
            }
        }
Beispiel #33
0
        // Para obtener más información sobre las uniones, visite https://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            BundleTable.Bundles.ResetAll();

            /// Bundles config JS
            /// Declaration Script Bundle : 01/07/2017

            ScriptBundle scriptJquery    = new ScriptBundle("~/bundles/jquery");
            ScriptBundle scriptLibrary   = new ScriptBundle("~/bundles/library");
            ScriptBundle scriptBootstrap = new ScriptBundle("~/bundles/bootstrap");
            ScriptBundle scriptCustom    = new ScriptBundle("~/bundles/custom");

            //ScriptBundle ScriptCurrencyHelp = new ScriptBundle("~/bundles/cleave");

            ScriptBundle scriptKeyboard      = new ScriptBundle("~/bundles/keyboard");
            ScriptBundle scriptMaterialize   = new ScriptBundle("~/bundles/materialize");
            ScriptBundle scriptKeyboardClave = new ScriptBundle("~/bundles/keyboardClave");
            StyleBundle  styleGeneralPage    = new StyleBundle("~/Resources/Static/Css/General/style");

            StyleBundle styleSteptwo = new StyleBundle("~/Resources/css/styleLogin2");

            styleSteptwo.Include(
                "~/Resources/css/login/styleLogin2.css"
                );

            //ScriptCurrencyHelp.Include("~/Content/js/CurrencyHelp/cleave.min.js");

            scriptJquery.Include(
                "~/Resources/Static/Scripts/jQuery/*.js"
                );

            scriptBootstrap.Include(
                "~/Resources/Static/Scripts/Bootstrap/*.js"
                );

            scriptLibrary.Include(
                "~/Resources/Static/Scripts/Library/*.js"
                );


            scriptCustom.Include(
                "~/Resources/Static/Scripts/Custom/*.js"
                );

            scriptKeyboard.Include(
                "~/Resources/Static/Scripts/Keyboard/*.js"
                );
            scriptKeyboardClave.Include(
                "~/Resources/Static/Scripts/KeyboardClave/*.js"
                );

            scriptMaterialize.Include(
                "~/Resources/Static/Scripts/Materialize/*.js"
                );

            styleGeneralPage.Include(
                "~/Resources/Static/Css/General/style.css"
                );

            //Add SignalR Js
            //scriptJquery.Include("~/Scripts/jquery.signalR-2.4.1.min.js");

            bundles.Add(scriptJquery);
            bundles.Add(scriptBootstrap);
            bundles.Add(scriptMaterialize);
            bundles.Add(scriptLibrary);
            bundles.Add(scriptCustom);
            bundles.Add(scriptKeyboard);
            bundles.Add(scriptKeyboardClave);
            bundles.Add(styleGeneralPage);
            bundles.Add(styleSteptwo);
            //bundles.Add(ScriptCurrencyHelp);


            ///Individual


            /// Bundles Js
            /// Declaration JS Blunde : 01/07/2017
            /// Layers

            bundles.Add(new ScriptBundle("~/bundles/Jquery_BoostStrap").Include(
                            "~/Resources/Static/Scripts/jQuery/jquery.js",
                            "~/Resources/Static/Scripts/Bootstrap/bootstrap.min.js"));


            bundles.Add(new ScriptBundle("~/bundles/ForgetCreate1").Include(
                            "~/Resources/Static/Scripts/Library/creditcard.min.js",
                            "~/Content/js/keyboard/keyboard2.js"));

            bundles.Add(new ScriptBundle("~/bundles/ForgetCreate1_Mobile").Include(
                            "~/Resources/Static/Scripts/Library/creditcard.min.js",
                            "~/Content/js/keyboard/keyboard2_mobile.js"));

            bundles.Add(new ScriptBundle("~/bundles/ForgetCreate2").Include(
                            "~/Resources/Static/Scripts/Custom/library.js",
                            "~/Resources/Static/Scripts/Library/image-picker.min.js",
                            "~/Content/js/keyboard/keyboard3.js"));

            bundles.Add(new ScriptBundle("~/bundles/ForgetCreate2_Mobile").Include(
                            "~/Resources/Static/Scripts/Custom/library.js",
                            "~/Resources/Static/Scripts/Library/image-picker.min.js",
                            "~/Content/js/keyboard/keyboard3_mobile.js"));


            ////
            bundles.Add(new ScriptBundle("~/bundles/LayoutApp").Include("~/Resources/Static/Scripts/Layers/Layout.app.js"));
            bundles.Add(new ScriptBundle("~/bundles/LayerMain").Include("~/Resources/Static/Scripts/Layers/Layout.main.js"));

            /// Views
            bundles.Add(new ScriptBundle("~/bundles/Login").Include("~/Resources/Static/Scripts/Layers/Views/login.app.js"));
            bundles.Add(new ScriptBundle("~/bundles/Messages").Include("~/Resources/Static/Scripts/Layers/Views/messages.app.js"));
            bundles.Add(new ScriptBundle("~/bundles/Transaction").Include("~/Resources/Static/Scripts/Layers/Views/transaction.app.js"));
            bundles.Add(new ScriptBundle("~/bundles/Material").Include("~/Resources/Static/Scripts/Layers/materialize.app.js"));

            // General
            bundles.Add(new ScriptBundle("~/bundles/Layout").Include("~/Resources/Static/Scripts/Layers/General.js"));

            // Styles
            bundles.Add(new StyleBundle("~/Resources/Static/Css/General/custom").Include("~/Resources/Static/Css/General/custom.css"));
            bundles.Add(new StyleBundle("~/Resources/Static/Css/General/mCustomScrollbar").Include("~/Resources/Static/Css/Extras/jquery.mCustomScrollbar.css"));
            bundles.Add(new StyleBundle("~/Resources/Static/Css/General/flipclock").Include("~/Resources/Static/Css/Extras/flipclock.css"));

            //Login styles

            bundles.Add(new StyleBundle("~/Resources/css/login/styleLogin").Include("~/Resources/css/login/styleLogin.css"));

            bundles.Add(new StyleBundle("~/Resources/css/login/styleLoginMinified").Include("~/Resources/css/login/styleLoginMinified.css"));

            foreach (var b in bundles)
            {
                var context = new BundleContext(new HttpContextWrapper(HttpContext.Current), BundleTable.Bundles, b.Path);
                b.UpdateCache(context, b.GenerateBundleResponse(context));
            }

            BundleTable.EnableOptimizations = true;
        }
Beispiel #34
0
 public override BundleResponse CacheLookup(BundleContext context)
 {
     return(UseCache ? base.CacheLookup(context) : null);
 }
Beispiel #35
0
 /// <summary>Starts a processing of assets</summary>
 /// <param name="bundleContext">Object BundleContext</param>
 /// <param name="bundleResponse">Object BundleResponse</param>
 public void Process(BundleContext bundleContext, BundleResponse bundleResponse) => this.Process(bundleContext, bundleResponse, BundleTransformerContext.Current.IsDebugMode);
Beispiel #36
0
 public override BundleResponse CacheLookup(BundleContext context)
 {
     return(BundleResponse);
 }
 public void AddScripts(BundleContext context)
 {
     context.Add("_content/BootstrapBlazor/js/bootstrap.blazor.bundle.min.js");
     context.Add("_content/Abp.AspNetCore.Components.WebAssembly.BootstrapTheme/scripts/global.js");
     context.Add("_content/Abp.AspNetCore.Components.WebAssembly.BootstrapTheme/scripts/common.js");
 }
 public CombineModuleAssembly(BundleContext context, string uniquireId, bool combine)
     : base(uniquireId, context, combine)
 {
 }
 /// <inheritdoc />
 public override string GetCacheKey(BundleContext context)
 {
     return(_cacheKeyGenerator.GetCacheKey(base.GetCacheKey(context)));
 }
 public void AddStyles(BundleContext context)
 {
     context.Add("_content/Volo.Abp.AspNetCore.Components.WebAssembly.BasicTheme/libs/abp/css/theme.css");
 }
Beispiel #41
0
        public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable <BundleFile> files)
        {
            if (files == null)
            {
                return(string.Empty);
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (bundle == null)
            {
                throw new ArgumentNullException("bundle");
            }

            // Generates source map using an approach documented here: http://ajaxmin.codeplex.com/discussions/446616
            var sourcePath     = VirtualPathUtility.ToAbsolute(bundle.Path);
            var mapVirtualPath = string.Concat(bundle.Path, "map"); // don't use .map so it's picked up by the bundle module
            var mapPath        = VirtualPathUtility.ToAbsolute(mapVirtualPath);

            // Concatenate file contents to be minified, including the sourcemap hints
            var contentConcatedString = GetContentConcated(context, files);

            // Try minify (+ source map) using AjaxMin dll
            try
            {
                var contentBuilder = new StringBuilder();
                var mapBuilder     = new StringBuilder();
                using (var contentWriter = new StringWriter(contentBuilder))
                    using (var mapWriter = new StringWriter(mapBuilder))
                        using (var sourceMap = new V3SourceMap(mapWriter))
                        {
                            var settings = new CodeSettings()
                            {
                                EvalTreatment             = EvalTreatment.MakeImmediateSafe,
                                PreserveImportantComments = false,
                                SymbolsMap     = sourceMap,
                                TermSemicolons = true,
                                MinifyCode     = minifyCode
                            };

                            sourceMap.StartPackage(sourcePath, mapPath);

                            var    minifier        = new Minifier();
                            string contentMinified = minifier.MinifyJavaScript(contentConcatedString, settings);
                            if (minifier.ErrorList.Count > 0)
                            {
                                return(GenerateMinifierErrorsContent(contentConcatedString, minifier));
                            }

                            contentWriter.Write(contentMinified);
                        }

                // Write the SourceMap to another Bundle
                AddContentToAdHocBundle(context, mapVirtualPath, mapBuilder.ToString());

                // Note: A current bug in AjaxMin reported by @LodewijkSioen here https://ajaxmin.codeplex.com/workitem/21834,
                // causes the MinifyJavascript method call to hang when debugger is attached if the following line is included.
                // To avoid more harm than good, don't support source mapping in this scenario until AjaxMin fixes it's bug.
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    contentBuilder.Insert(0, sourceMappingDisabledMsg + "\r\n\r\n\r\n");
                }

                return(contentBuilder.ToString());
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("An exception occurred trying to build bundle contents for bundle with virtual path: " + bundle.Path + ". See Exception details.", ex, typeof(ScriptWithSourceMapBundleBuilder));
                return(GenerateGenericErrorsContent(contentConcatedString));
            }
        }
Beispiel #42
0
        /// <summary>
        /// Generates the URLs for a dynamically registered set of files (non pre-defined bundle)
        /// </summary>
        /// <param name="files"></param>
        /// <param name="fileType"></param>
        /// <param name="pipeline"></param>
        /// <param name="debug"></param>
        /// <returns></returns>
        private async Task <IEnumerable <string> > GenerateUrlsAsync(
            IEnumerable <IWebFile> files,
            WebFileType fileType,
            PreProcessPipeline pipeline = null,
            bool debug = false)
        {
            var result = new List <string>();

            var orderedFiles = _fileSetGenerator.GetOrderedFileSet(files, pipeline ?? _processorFactory.CreateDefault(fileType));

            if (debug)
            {
                return(orderedFiles.Select(x => x.FilePath));
            }

            var compression = _requestHelper.GetClientCompression(_httpContextAccessor.HttpContext.Request.Headers);

            //Get the file collection used to create the composite URLs and the external requests
            var fileBatches = _fileBatcher.GetCompositeFileCollectionForUrlGeneration(orderedFiles);

            var cacheBuster = _cacheBusterResolver.GetCacheBuster(_bundleManager.GetDefaultBundleOptions(debug).GetCacheBusterType());

            foreach (var batch in fileBatches)
            {
                //if it's external, the rule is that a WebFileBatch can only contain a single external file
                // it's path will be normalized as an external url so we just use it
                if (batch.IsExternal)
                {
                    result.Add(batch.Single().Original.FilePath);
                }
                else
                {
                    //Get the URLs for the batch, this could be more than one resulting URL depending on how many
                    // files are in the batch and the max url length
                    var compositeUrls = _urlManager.GetUrls(
                        batch.Select(x => x.Hashed),
                        fileType == WebFileType.Css ? ".css" : ".js",
                        cacheBuster);

                    foreach (var u in compositeUrls)
                    {
                        //now we need to determine if these files have already been minified
                        var compositeFilePath = _fileSystemHelper.GetCurrentCompositeFilePath(cacheBuster, compression, u.Key);
                        if (!File.Exists(compositeFilePath))
                        {
                            using (var bundleContext = BundleContext.CreateEmpty())
                            {
                                //need to process/minify these files - need to use their original paths of course
                                foreach (var file in batch.Select(x => x.Original))
                                {
                                    await _preProcessManager.ProcessAndCacheFileAsync(file, null, bundleContext);
                                }
                            }
                        }
                        result.Add(u.Url);
                    }
                }
            }

            return(result);
        }
Beispiel #43
0
        public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable <BundleFile> files)
        {
            if (files == null)
            {
                return(string.Empty);
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (bundle == null)
            {
                throw new ArgumentNullException("bundle");
            }

            // Generates source map using an approach documented here: http://ajaxmin.codeplex.com/discussions/446616

            // Get paths and create any directories required
            var mapVirtualPath = bundle.Path + ".map";
            var sourcePath     = HostingEnvironment.MapPath(bundle.Path);
            var mapPath        = HostingEnvironment.MapPath(mapVirtualPath);
            var directoryPath  = Path.GetDirectoryName(mapPath);

            if (directoryPath == null)
            {
                throw new InvalidOperationException("directoryPath was invalid.");
            }

            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            // Concatenate file contents to be minified, including the sourcemap hints
            var contentConcated = new StringBuilder();

            foreach (var file in files)
            {
                var filePath = HostingEnvironment.MapPath(file.VirtualFile.VirtualPath);
                if (bundleFileType == BundleFileTypes.JavaScript)
                {
                    contentConcated.AppendLine(";///#SOURCE 1 1 " + filePath);
                }
                contentConcated.AppendLine(file.ApplyTransforms());
            }
            var contentConcatedString = contentConcated.ToString();

            // Try minify (+ source map) using AjaxMin dll
            try
            {
                var contentBuilder = new StringBuilder();
                using (var contentWriter = new StringWriter(contentBuilder))
                    using (var mapWriter = new StreamWriter(mapPath, false, new UTF8Encoding(false)))
                        using (var sourceMap = new V3SourceMap(mapWriter))
                        {
                            sourceMap.StartPackage(sourcePath, mapPath);

                            var settings = new CodeSettings()
                            {
                                EvalTreatment             = EvalTreatment.MakeImmediateSafe,
                                PreserveImportantComments = false,
                                SymbolsMap     = sourceMap,
                                TermSemicolons = true
                            };

                            var    minifier = new Minifier();
                            string contentMinified;
                            switch (bundleFileType)
                            {
                            case BundleFileTypes.JavaScript:
                                contentMinified = minifier.MinifyJavaScript(contentConcatedString, settings);
                                break;

                            case BundleFileTypes.StyleSheet:
                                var cssSettings = new CssSettings
                                {
                                    TermSemicolons = true
                                };
                                contentMinified = minifier.MinifyStyleSheet(contentConcatedString, cssSettings, settings);
                                break;

                            default:
                                throw new ArgumentOutOfRangeException("Unrecognised BundleFileTypes enum value. Could not find minifier method to handle.");
                            }
                            if (minifier.ErrorList.Count > 0)
                            {
                                return(GenerateMinifierErrorsContent(contentConcatedString, minifier));
                            }

                            contentWriter.Write(contentMinified);

                            sourceMap.EndPackage();
                            sourceMap.EndFile(contentWriter, "\r\n");
                        }

                return(contentBuilder.ToString());
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("An exception occurred trying to build bundle contents for bundle with virtual path: " + bundle.Path + ". See Exception details.", ex, typeof(AjaxMinBundleBuilder));
                return(GenerateGenericErrorsContent(contentConcatedString));
            }
        }
 public TemplateCacheBundleItemTransform(BundleContext context, TemplateCacheBundle bundle)
 {
     Bundle  = bundle;
     Context = context;
 }
 public void Process(BundleContext context, BundleResponse response)
 {
     response.ContentType = "application/javascript";
 }
        public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable <BundleFile> files)
        {
            if (files == null)
            {
                return(string.Empty);
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (bundle == null)
            {
                throw new ArgumentNullException("bundle");
            }

            // Generates source map using an approach documented here: http://ajaxmin.codeplex.com/discussions/446616
            var sourcePath     = VirtualPathUtility.ToAbsolute(bundle.Path);
            var mapVirtualPath = string.Concat(bundle.Path, "map"); // don't use .map so it's picked up by the bundle module
            var mapPath        = VirtualPathUtility.ToAbsolute(mapVirtualPath);

            // Concatenate file contents to be minified, including the sourcemap hints
            var contentConcatedString = GetContentConcated(context, files);

            // Try minify (+ source map) using AjaxMin dll
            try
            {
                var contentBuilder = new StringBuilder();
                var mapBuilder     = new StringBuilder();
                using (var contentWriter = new StringWriter(contentBuilder))
                    using (var mapWriter = new StringWriter(mapBuilder))
                        using (var sourceMap = new V3SourceMap(mapWriter))
                        {
                            var settings = new CodeSettings()
                            {
                                EvalTreatment             = EvalTreatment.MakeImmediateSafe,
                                PreserveImportantComments = preserveImportantComments,
                                SymbolsMap     = sourceMap,
                                TermSemicolons = true,
                                MinifyCode     = minifyCode
                            };

                            sourceMap.StartPackage(sourcePath, mapPath);

                            var    result          = Uglify.Js(contentConcatedString, settings);
                            string contentMinified = result.Code;
                            if (result.Errors.Count > 0)
                            {
                                return(GenerateMinifierErrorsContent(contentConcatedString, result));
                            }

                            contentWriter.Write(contentMinified);
                        }

                // Write the SourceMap to another Bundle
                AddContentToAdHocBundle(context, mapVirtualPath, mapBuilder.ToString());

                return(contentBuilder.ToString());
            }
            catch (Exception ex)
            {
                // only Trace the fact that an exception occurred to the Warning output, but use Informational tracing for added detail for diagnosis
                Trace.TraceWarning("An exception occurred trying to build bundle contents for bundle with virtual path: " + bundle.Path + ". See Exception details in Information.");

                string bundlePrefix = "[Bundle '" + bundle.Path + "']";
                Trace.TraceInformation(bundlePrefix + " exception message: " + ex.Message);

                if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message))
                {
                    Trace.TraceInformation(bundlePrefix + " inner exception message: " + ex.InnerException.Message);
                }

                Trace.TraceInformation(bundlePrefix + " source: " + ex.Source);
                Trace.TraceInformation(bundlePrefix + " stack trace: " + ex.StackTrace);

                return(GenerateGenericErrorsContent(contentConcatedString));
            }
        }
Beispiel #47
0
        public override System.Collections.Generic.IEnumerable <System.IO.FileInfo> EnumerateFiles(BundleContext context)
        {
            foreach (var file in _wrapped.EnumerateFiles(context))
            {
                if (IncludeFilename(file.Name))
                {
                    yield return(file);
                }
            }

            foreach (var file in base.EnumerateFiles(context))
            {
                yield return(file);
            }
        }
Beispiel #48
0
 public virtual Bundle Include(params string[] virtualPaths)
 {
     BundleContext.AddInputFiles(virtualPaths);
     return(this);
 }
Beispiel #49
0
 public void Process(BundleContext context, BundleResponse response)
 {
     response.Content     = dotless.Core.Less.Parse(response.Content);
     response.ContentType = "text/css";
 }
 public void AddScripts(BundleContext context)
 {
 }
Beispiel #51
0
 public void Process(BundleContext context, BundleResponse response)
 {
     context.UseServerCache = false;
     response.Cacheability  = HttpCacheability.NoCache;
 }
        public void AddStyles(BundleContext context)
        {
            context.Add("_content/Volo.Abp.AspNetCore.Components.Web.BasicTheme/libs/abp/css/theme.css");

            context.Add("_content/MudBlazor/MudBlazor.min.css");
        }
 public void AddStyles(BundleContext context)
 {
     context.Add("main.css", true);
 }
Beispiel #54
0
        /// <summary>
        /// This will first check if the file is in cache and if not it will
        /// run all pre-processors assigned to the file and store the output in a persisted file cache.
        /// </summary>
        /// <param name="file"></param>
        /// <param name="bundleOptions"></param>
        /// <param name="bundleContext"></param>
        /// <returns></returns>
        public async Task ProcessAndCacheFileAsync(IWebFile file, BundleOptions bundleOptions, BundleContext bundleContext)
        {
            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }
            if (file.Pipeline == null)
            {
                throw new ArgumentNullException(string.Format("{0}.Pipeline", nameof(file)));
            }

            await ProcessFile(file, bundleOptions, bundleContext);
        }
 public IEnumerable <BundleFile> OrderFiles(BundleContext context, IEnumerable <BundleFile> files)
 {
     return(files);
 }
Beispiel #56
0
        public void Process(BundleContext context, BundleResponse response)
        {
            var p = new ECMAScriptPacker(ECMAScriptPacker.PackerEncoding.Normal, true, false);

            response.Content = p.Pack(response.Content);
        }
 public void AddScripts(BundleContext context)
 {
     context.Add("_content/MudBlazor/MudBlazor.min.js");
 }
        public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable <BundleFile> files)
        {
            string concatenationToken = null;

            if (files != null)
            {
                if (context != null)
                {
                    if (bundle != null)
                    {
                        string appPath            = GetAppPath(context);
                        var    stringBuilder      = new StringBuilder();
                        string boundaryIdentifier = "";

                        if (context.EnableInstrumentation)
                        {
                            boundaryIdentifier = GetBoundaryIdentifier(bundle);
                            stringBuilder.AppendLine(GenerateBundlePreamble(boundaryIdentifier));
                        }

                        if (string.IsNullOrEmpty(bundle.ConcatenationToken))
                        {
                            if (bundle.Transforms.Any(transform => transform is JsMinify))
                            {
                                concatenationToken = ";";
                            }
                        }
                        else
                        {
                            concatenationToken = bundle.ConcatenationToken;
                        }

                        if (concatenationToken == null || context.EnableInstrumentation)
                        {
                            concatenationToken = Environment.NewLine;
                        }

                        foreach (BundleFile file in files)
                        {
                            if (context.EnableInstrumentation)
                            {
                                stringBuilder.Append(GetFileHeader(appPath, file, GetInstrumentedFileHeaderFormat(boundaryIdentifier)));
                            }

                            string content = ProcessImageReferences(file, context);

                            stringBuilder.Append(content);
                            stringBuilder.Append(concatenationToken);
                        }

                        return(stringBuilder.ToString());
                    }

                    throw new ArgumentNullException("bundle");
                }

                throw new ArgumentNullException("context");
            }

            return(string.Empty);
        }
 public virtual IEnumerable <FileInfo> OrderFiles(BundleContext context, IEnumerable <FileInfo> files)
 {
     return(files);
 }
Beispiel #60
0
 public void AddStyles(BundleContext context)
 {
     context.Add("_content/Blazorise/blazorise.css");
     context.Add("_content/Blazorise.Bootstrap/blazorise.bootstrap.css");
     context.Add("_content/Blazorise.Snackbar/blazorise.snackbar.css");
 }