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; }
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 override void Process(BundleResponse bundle) { var compiler = new CoffeeScriptEngine(); bundle.Content = compiler.Compile(bundle.Content); base.Process(bundle); }
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; }
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); } }
/// <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"; }
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 override void Process(BundleContext context, BundleResponse response) { var compressor = new CssCompressor(); response.Content = compressor.Compress(response.Content); response.ContentType = ContentTypes.Css; }
public void Process(BundleContext context, BundleResponse response) { var output = new StringBuilder(); var errors = new StringBuilder(); var applicationFolder = context.HttpContext.Server.MapPath(@"~/"); var nodejs = Path.GetFullPath(applicationFolder + @"..\nodejs"); foreach (var file in response.Files) { using (var process = new Process()) { process.StartInfo = new ProcessStartInfo { FileName = Path.Combine(nodejs, "node.exe"), Arguments = Path.Combine(nodejs, @"node_modules\less\bin\lessc") + " " + file.FullName, CreateNoWindow = true, RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false, WorkingDirectory = applicationFolder, }; process.OutputDataReceived += (sender, e) => output.AppendLine(e.Data); process.ErrorDataReceived += (sender, e) => { if (!String.IsNullOrWhiteSpace(e.Data)) errors.AppendLine(e.Data); }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); } } if (!String.IsNullOrEmpty(errors.ToString())) throw new LessParsingException(errors.ToString()); response.ContentType = "text/css"; response.Content = output.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()); }
/// <summary> /// Transforms the content in the <see cref="T:System.Web.Optimization.BundleResponse" /> object. /// </summary> /// <param name="context">The bundle context.</param> /// <param name="response">The bundle response.</param> public void Process(BundleContext context, BundleResponse response) { if (!context.EnableInstrumentation) { Manager.Process(response.Files.Select(x => new Asset(x.IncludedVirtualPath)).ToList<IAsset>(), context, response); } }
public void Process(BundleContext context, BundleResponse response) { var builder = new StringBuilder(); foreach (var file in response.Files) { var path = context.HttpContext.Server.MapPath( file.IncludedVirtualPath); var fileInfo = new FileInfo(path); if (!fileInfo.Exists) { continue; } var content = ResolveImports(fileInfo); builder.AppendLine( _configuration.Web ? dotless.Core.LessWeb.Parse(content, _configuration) : dotless.Core.Less.Parse(content, _configuration)); } response.ContentType = ContentType.Css; response.Content = builder.ToString(); }
public void Process(BundleContext context, BundleResponse response) { var sharedLessFile = CreateSharedLessFile(response.Files); response.Content = GenerateCss(sharedLessFile, context); response.ContentType = "text/css"; }
public virtual void Process(BundleContext context, BundleResponse response) { #if DEBUG // set BundleContext.UseServerCache to false in order to process all bundle request and generate dynamic response context.UseServerCache = false; response.Cacheability = HttpCacheability.NoCache; #endif var contentBuilder = new StringBuilder(); contentBuilder.AppendLine("// Created on: " + DateTime.Now.ToString(CultureInfo.InvariantCulture)); contentBuilder.AppendLine("require(['angular'], function(angular) {"); contentBuilder.AppendLine(" angular.module('bundleTemplateCache', []).run(['$templateCache', function($templateCache) {"); contentBuilder.AppendLine(" $templateCache.removeAll();"); foreach (BundleFile file in response.Files) { string fileId = VirtualPathUtility.ToAbsolute(file.IncludedVirtualPath); string filePath = HttpContext.Current.Server.MapPath(file.IncludedVirtualPath); string fileContent = File.ReadAllText(filePath); contentBuilder.AppendFormat(" $templateCache.put({0},{1});" + Environment.NewLine, JsonConvert.SerializeObject(fileId), JsonConvert.SerializeObject(fileContent)); } contentBuilder.AppendLine(" }]);"); contentBuilder.AppendLine("});"); response.Content = contentBuilder.ToString(); response.ContentType = "text/javascript"; }
/// <summary> /// Processes the specified bundle of LESS files. /// </summary> /// <param name="context"> </param> /// <param name="bundle">The LESS bundle.</param> public void Process(BundleContext context, BundleResponse bundle) { if (bundle == null) throw new ArgumentNullException("bundle"); context.HttpContext.Response.Cache.SetLastModifiedFromFileDependencies(); var parser = new Parser(); var engine = new LessEngine(parser); var content = new StringBuilder(); foreach (var file in bundle.Files) { // set current file path SetCurrentFilePath(parser, file.FullName); var text = File.ReadAllText(file.FullName); var css = engine.TransformToCss(text, file.FullName); content.AppendLine(css); // content.Append(engine.TransformToCss(text, file.FullName)); // content.AppendLine(); AddFileDependencies(parser); } bundle.Content = content.ToString(); bundle.ContentType = "text/css"; }
public void Process(BundleContext context, BundleResponse response) { var exp = new Regex(@"url\([^\)]+\)", RegexOptions.IgnoreCase | RegexOptions.Singleline); var siteRoot = GetSiteRoot(context.HttpContext); response.Content = exp.Replace(response.Content, m => TransformUrl(m, siteRoot)); }
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 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 Process(BundleContext context, BundleResponse response) { Assert.ArgumentNotNull(response, "response"); response.Content = new CssCompressor().Compress(response.Content); response.ContentType = "text/css"; }
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; }
/// <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) { 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"; }
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(); }
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; }
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 response) { Directory.SetCurrentDirectory(path); response.Content = Less.Parse(response.Content); response.ContentType = "text/css"; }
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 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(); }
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 ProcessRequest(HttpContext context) { var filename = context.Request.Path.Substring(0, context.Request.Path.Length - 6) + "js"; string output = GetCachedOutput(context); var file = new FileInfo(HostingEnvironment.MapPath(filename)); if (output == null) { if (file.Exists) { var minifier = new JsMinify(); var bundle = new BundleResponse { Content = File.ReadAllText(file.FullName) }; minifier.Process(bundle); output = bundle.Content; AddCachedOutput(context, output, file.FullName); } else { throw new HttpException(404, "NotFound"); } } context.Response.Write(output); context.Response.ContentType = "text/javascript"; HttpContext.Current.Response.AddFileDependency(file.FullName); HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public); HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddYears(1)); }
public void Process(BundleContext context, BundleResponse response) { response.Content = dotless.Core.Less.Parse(response.Content); response.ContentType = "text/css"; }
public void Process(BundleContext context, BundleResponse response) { response.ContentType = "application/javascript"; }
public void Process(BundleContext context, BundleResponse bundle) { bundle.Content = dotless.Core.Less.Parse(bundle.Content); bundle.ContentType = "text/css"; }