public string CompressContent(string content) { var minifier = new Minifier(); if (settings != null) { return minifier.MinifyStyleSheet(content, settings); } return minifier.MinifyStyleSheet(content); }
public override void Process(BundleContext context, BundleResponse response) { response.ContentType = ContentType.JavaScript; if (context.HttpContext.IsDebuggingEnabled) { return; } var minifier = new Minifier(); response.Content = minifier.MinifyStyleSheet(response.Content); }
public string Minify(string content) { var minifier = new Minifier(); var stylesheet = string.Empty; stylesheet = Settings != null ? minifier.MinifyStyleSheet(content, Settings) : minifier.MinifyStyleSheet(content); return stylesheet; }
public override IEnumerable<PvcCore.PvcStream> Execute(IEnumerable<PvcCore.PvcStream> inputStreams) { var minifyStreams = inputStreams.Where(x => Regex.IsMatch(x.StreamName, @"\.(js|css)$")); var resultStreams = new List<PvcStream>(); foreach (var inputStream in minifyStreams) { var fileContent = new StreamReader(inputStream).ReadToEnd(); var minifier = new Minifier(); var resultContent = inputStream.StreamName.EndsWith(".js") ? minifier.MinifyJavaScript(fileContent) : minifier.MinifyStyleSheet(fileContent); foreach (var error in minifier.ErrorList) { Console.Error.WriteLine(error.ToString()); } var dirName = Path.GetDirectoryName(inputStream.StreamName); var fileName = Path.GetFileNameWithoutExtension(inputStream.StreamName) + ".min" + Path.GetExtension(inputStream.StreamName); var resultStream = PvcUtil.StringToStream(resultContent, Path.Combine(dirName, fileName)); resultStreams.Add(resultStream); } return inputStreams.Where(x => !minifyStreams.Any(y => y.StreamName == x.StreamName)).Concat(resultStreams); }
private static MinificationResult MinifyCss(Config config, string file) { string content = File.ReadAllText(file); var settings = CssOptions.GetSettings(config); if (config.Minify.ContainsKey("enabled") && config.Minify["enabled"].ToString().Equals("false", StringComparison.OrdinalIgnoreCase)) return null; var minifier = new Minifier(); // Remove control characters which AjaxMin can't handle content = Regex.Replace(content, @"[\u0000-\u0009\u000B-\u000C\u000E-\u001F]", string.Empty); string result = minifier.MinifyStyleSheet(content, settings); string minFile = GetMinFileName(file); bool containsChanges = FileHelpers.HasFileContentChanged(minFile, result); OnBeforeWritingMinFile(file, minFile, containsChanges); if (containsChanges) { File.WriteAllText(minFile, result, new UTF8Encoding(true)); } OnAfterWritingMinFile(file, minFile, containsChanges); GzipFile(config, minFile, containsChanges); return new MinificationResult(result, null); }
protected override void BuildResult(Stream fs, List <string> filePaths) { var minifier = new Microsoft.Ajax.Utilities.Minifier(); minifier.WarningLevel = 3; var styleBuilder = new StringBuilder(); foreach (var style in filePaths) { var text = FileOperator.ReadAllText(style); try { var mintext = minifier.MinifyStyleSheet(text); if (minifier.Errors.Count == 0) { text = mintext; } } catch (Exception) { } styleBuilder.AppendLine(text); } var buffer = Encoding.UTF8.GetBytes(styleBuilder.ToString()); fs.Write(buffer, 0, buffer.Length); }
/// <summary> /// Minifies the specified CSS. /// </summary> /// <param name="resource">The CSS to minify.</param> /// <returns>The minified CSS, if minification was successful; otherwise, the original CSS with minification errors appended at the end.</returns> public string Minify(string resource) { if (String.IsNullOrEmpty(resource)) { return resource; } var settings = new CssSettings { AllowEmbeddedAspNetBlocks = false }; var minifier = new Minifier(); try { resource = minifier.MinifyStyleSheet(resource, settings); } catch { var minificationErrors = String.Join(Environment.NewLine, minifier.Errors); resource = AppendMinificationErrors(resource, minificationErrors); if (mLogErrors) { CoreServices.EventLog.LogEvent("W", "Resource minification", "CssMinificationFailed", minificationErrors); } } return resource; }
public static string MinifyString(string extension, string content) { if (extension == ".css") { Minifier minifier = new Minifier(); CssSettings settings = new CssSettings(); settings.CommentMode = CssComment.None; if (WESettings.GetBoolean(WESettings.Keys.KeepImportantComments)) { settings.CommentMode = CssComment.Important; } return minifier.MinifyStyleSheet(content, settings); } else if (extension == ".js") { Minifier minifier = new Minifier(); CodeSettings settings = new CodeSettings() { EvalTreatment = EvalTreatment.MakeImmediateSafe, PreserveImportantComments = WESettings.GetBoolean(WESettings.Keys.KeepImportantComments) }; return minifier.MinifyJavaScript(content, settings); } return null; }
public string Minify(string content) { var minifier = new Minifier(); var stylesheet = string.Empty; if (Settings != null) { stylesheet = minifier.MinifyStyleSheet(content, Settings); } else { stylesheet = minifier.MinifyStyleSheet(content); } return stylesheet; }
/// <summary> /// Minifies the CSS. /// </summary> /// <param name="css">The CSS.</param> /// <returns></returns> public static String MinifyCss(String css) { if (String.IsNullOrWhiteSpace(css)) return css; var min = new Minifier(); return min.MinifyStyleSheet(css); //return Yahoo.Yui.Compressor.CssCompressor.Compress(css); }
public virtual string Minify<T>(string unMinifiedContent) where T : IResourceType { if (typeof(T) == typeof(CssResource)) return minifier.MinifyStyleSheet(unMinifiedContent); if (typeof(T) == typeof(JavaScriptResource)) return minifier.MinifyJavaScript(unMinifiedContent, settings); throw new ArgumentException("Cannot Minify ResourceStrings of unknown type", "unMinifiedContent"); }
public string CompressContent(string content, bool removeComments) { var settings = new CssSettings(); if(removeComments) settings.CommentMode = CssComment.None; var minifier = new Minifier(); return minifier.MinifyStyleSheet(content, settings); }
protected override string Compress(string source) { var minifier = new Minifier(); var minified = minifier.MinifyStyleSheet(source); if (minifier.Errors.Count > 0) { return source; } return minified; }
public void Write(Module module) { var minifier = new Minifier(); textWriter.Write( minifier.MinifyStyleSheet( string.Join( "\r\n", module.Resources.Select(ReadCss) ) ) ); }
public static string MinifiContentToString(string content, ContentType contentType) { Minifier minifier = new Minifier(); if (contentType == ContentType.css) { content = minifier.MinifyStyleSheet(content); } else if (contentType == ContentType.javascript) { content = minifier.MinifyJavaScript(content); } return content; }
public static byte[] MinifyContent(string content, ContentType contentType) { Minifier minifier = new Minifier(); if (contentType == ContentType.css) { content = minifier.MinifyStyleSheet(content); } else if (contentType == ContentType.javascript) { content = minifier.MinifyJavaScript(content); } return Encoding.UTF8.GetBytes(content); }
private static void Minify(HttpResponse response, string file, string ext) { string content = File.ReadAllText(file); Minifier minifier = new Minifier(); if (ext == ".css") { CssSettings settings = new CssSettings() { CommentMode = CssComment.None }; response.Write(minifier.MinifyStyleSheet(content, settings)); } else if (ext == ".js") { CodeSettings settings = new CodeSettings() { PreserveImportantComments = false }; response.Write(minifier.MinifyJavaScript(content, settings)); } }
public void Process(BundleContext context, BundleResponse response) { var pattern = new Regex(@"url\s*\(\s*([""']?)([^:)]+)\1\s*\)", RegexOptions.IgnoreCase); response.Content = string.Empty; // open each of the files foreach (var file in response.Files) { using (var reader = new StreamReader(file.VirtualFile.Open())) { var contents = reader.ReadToEnd(); // apply the RegEx to the file (to change relative paths) var matches = pattern.Matches(contents); if (matches.Count > 0) { var directoryPath = VirtualPathUtility.GetDirectory(file.VirtualFile.VirtualPath); foreach (Match match in matches) { // this is a path that is relative to the CSS file var imageRelativePath = match.Groups[2].Value; // get the image virtual path var imageVirtualPath = VirtualPathUtility.Combine(directoryPath, imageRelativePath); // convert the image virtual path to absolute var quote = match.Groups[1].Value; var replace = String.Format("url({0}{1}{0})", quote, VirtualPathUtility.ToAbsolute(imageVirtualPath)); contents = contents.Replace(match.Groups[0].Value, replace); } } // copy the result into the response. response.Content = String.Format("{0}\r\n{1}", response.Content, contents); } var minifer = new Minifier(); var cs = new CssSettings(); var responseContent = minifer.MinifyStyleSheet(response.Content, cs); response.Content = responseContent; } }
private void minifyCSS(Entity entity, CssSettings settings) { Microsoft.Ajax.Utilities.Minifier minifier = new Microsoft.Ajax.Utilities.Minifier(); string name = entity.GetAttributeValue <string>("displayname"); byte[] cssFileBytes = Convert.FromBase64String(entity.GetAttributeValue <string>("content")); string originalCss = UnicodeEncoding.UTF8.GetString(cssFileBytes); string minifiedCss = minifier.MinifyStyleSheet(originalCss, settings); byte[] minifiedCssBytes = UnicodeEncoding.UTF8.GetBytes(minifiedCss); string minifiedCssBytesString = Convert.ToBase64String(minifiedCssBytes); Entity updatedWebResource = new Entity(entity.LogicalName); updatedWebResource.Attributes.Add("content", minifiedCssBytesString); updatedWebResource.Id = entity.Id; this.service.Update(updatedWebResource); }
private static MinificationResult MinifyCss(Config config, string file) { string content = File.ReadAllText(file); var settings = CssOptions.GetSettings(config); var minifier = new Minifier(); string result = minifier.MinifyStyleSheet(content, settings); if (!string.IsNullOrEmpty(result)) { string minFile = GetMinFileName(file); OnBeforeWritingMinFile(file, minFile); File.WriteAllText(minFile, result, new UTF8Encoding(true)); OnAfterWritingMinFile(file, minFile); GzipFile(config, minFile); } return new MinificationResult(result, null); }
public virtual void Process(BundleContext context, BundleResponse response) { if (context == null) throw new ArgumentNullException("context"); if (response == null) throw new ArgumentNullException("response"); if (!context.EnableInstrumentation) { var minifier = new Minifier(); FixCustomCssErrors(response); string str = minifier.MinifyStyleSheet(response.Content, new CssSettings() { CommentMode = CssComment.None }); if (minifier.ErrorList.Count > 0) GenerateErrorResponse(response, minifier.ErrorList); else response.Content = str; } response.ContentType = CssContentType; }
public virtual string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<BundleFile> files) { CssSettings settings = new CssSettings(); settings.IgnoreAllErrors = true; settings.CommentMode = CssComment.None; var minifier = new Minifier(); var content = new StringBuilder(100000); foreach (var file in files) { FileInfo f = new FileInfo(HttpContext.Current.Server.MapPath(file.VirtualFile.VirtualPath)); string readFile = Read(f); content.Append(minifier.MinifyStyleSheet(readFile, settings)); content.AppendLine(); } return content.ToString(); }
public static string Minify(string fullFileName, string text, EnvDTE.ProjectItem projectItem,CssSettings cssSettings) { Minifier minifier = new Minifier(); string miniCss = minifier.MinifyStyleSheet(text, cssSettings); foreach (var err in minifier.ErrorList) { if (TaskList.Instance == null) { Console.WriteLine(string.Format("{0}({1},{2}){3}", fullFileName, 1, 1, err)); } else { TaskList.Instance.Add(projectItem.ContainingProject, Microsoft.VisualStudio.Shell.TaskErrorCategory.Error, fullFileName, err.StartLine, err.StartColumn, err.Message); } } return miniCss; }
public static string MinifyString(string extension, string content) { if (extension == ".css") { Minifier minifier = new Minifier(); CssSettings settings = new CssSettings(); settings.CommentMode = CssComment.None; if (WESettings.GetBoolean(WESettings.Keys.KeepImportantComments)) { settings.CommentMode = CssComment.Important; } return minifier.MinifyStyleSheet(content, settings); } else if (extension == ".js") { Minifier minifier = new Minifier(); CodeSettings settings = new CodeSettings() { EvalTreatment = EvalTreatment.MakeImmediateSafe, PreserveImportantComments = WESettings.GetBoolean(WESettings.Keys.KeepImportantComments) }; return minifier.MinifyJavaScript(content, settings); } else if (_htmlExt.Contains(extension.ToLowerInvariant())){ var settings = new HtmlMinificationSettings { RemoveOptionalEndTags = false, AttributeQuotesRemovalMode = HtmlAttributeQuotesRemovalMode.KeepQuotes }; var minifier = new HtmlMinifier(settings); MarkupMinificationResult result = minifier.Minify(content, generateStatistics: true); if (result.Errors.Count == 0) { EditorExtensionsPackage.DTE.StatusBar.Text = "Web Essentials: HTML minified by " + result.Statistics.SavedInPercent + "%"; return result.MinifiedContent; } else { EditorExtensionsPackage.DTE.StatusBar.Text = "Web Essentials: Cannot minify the current selection"; return content; } } return null; }
/// <summary> /// CSSs the minify. /// </summary> /// <param name="helper">The helper.</param> /// <param name="markup">The markup.</param> /// <returns></returns> public static MvcHtmlString CssMinify(this HtmlHelper helper, Func<object, object> markup) { if (helper == null || markup == null) { return MvcHtmlString.Empty; } var sourceCss = (markup.DynamicInvoke(helper.ViewContext) ?? String.Empty).ToString(); if (!IsJsMinify) { return new MvcHtmlString(sourceCss); } var minifier = new Minifier(); var minifiedCss = minifier.MinifyStyleSheet(sourceCss, new CssSettings { CommentMode = CssComment.None }); return new MvcHtmlString(minifiedCss); }
private static MinificationResult MinifyCss(Bundle bundle) { string file = bundle.GetAbsoluteOutputFile(); string content = File.ReadAllText(file); var settings = CssOptions.GetSettings(bundle); string minFile = GetMinFileName(file); var minifier = new Minifier(); var result = new MinificationResult(file, null, null); try { result.MinifiedContent = minifier.MinifyStyleSheet(content, settings); if (!minifier.Errors.Any()) { OnBeforeWritingMinFile(file, minFile, bundle); File.WriteAllText(minFile, result.MinifiedContent, new UTF8Encoding(true)); OnAfterWritingMinFile(file, minFile, bundle); GzipFile(minFile, bundle); } else { FileMinifier.AddAjaxminErrors(minifier, result); } } catch (Exception ex) { result.Errors.Add(new MinificationError { FileName = file, Message = ex.Message, LineNumber = 0, ColumnNumber = 0 }); } return result; }
public string CompressContent(string content) { var minifier = new Minifier(); return minifier.MinifyStyleSheet(content); }
private static MinificationResult MinifyCss(Config config, string file) { string content = File.ReadAllText(file); var settings = CssOptions.GetSettings(config); if (config.Minify.ContainsKey("enabled") && config.Minify["enabled"].ToString().Equals("false", StringComparison.OrdinalIgnoreCase)) return null; var minifier = new Minifier(); string result = minifier.MinifyStyleSheet(content, settings); if (!string.IsNullOrEmpty(result)) { string minFile = GetMinFileName(file); bool containsChanges = FileHelpers.HasFileContentChanged(minFile, result); OnBeforeWritingMinFile(file, minFile, containsChanges); if (containsChanges) { File.WriteAllText(minFile, result, new UTF8Encoding(true)); } OnAfterWritingMinFile(file, minFile, containsChanges); GzipFile(config, minFile, containsChanges); } return new MinificationResult(result, null); }
/// <summary> /// Produces a code minifiction of CSS content by using the Microsoft Ajax CSS Minifier /// </summary> /// <param name="content">CSS content</param> /// <param name="isInlineCode">Flag whether the content is inline code</param> /// <param name="encoding">Text encoding</param> /// <returns>Minification result</returns> public CodeMinificationResult Minify(string content, bool isInlineCode, Encoding encoding) { if (string.IsNullOrWhiteSpace(content)) { return new CodeMinificationResult(string.Empty); } CssSettings originalCssSettings = isInlineCode ? _originalInlineCssSettings : _originalEmbeddedCssSettings; var originalMinifier = new Minifier { WarningLevel = 2 }; string newContent = originalMinifier.MinifyStyleSheet(content, originalCssSettings, _originalJsSettings); ICollection<ContextError> originalErrors = originalMinifier.ErrorList; var errors = new List<MinificationErrorInfo>(); var warnings = new List<MinificationErrorInfo>(); MapErrors(originalErrors, errors, warnings); return new CodeMinificationResult(newContent, errors, warnings); }
private static string BundleInlines(MinifyType bundleType, Func<object, object> textFunc) { string notMinified = string.Empty; notMinified = (textFunc.Invoke(new object()) ?? "").ToString(); if (!EnableBundle) { return notMinified; } var minifier = new Minifier(); string minified = string.Empty; minifier.MinifyJavaScript("", new CodeSettings()); switch (bundleType) { case MinifyType.Javascript: minified = minifier.MinifyJavaScript(notMinified, new CodeSettings { EvalTreatment = EvalTreatment.MakeImmediateSafe, PreserveImportantComments = false }); break; case MinifyType.Css: minified = minifier.MinifyStyleSheet(notMinified, new CssSettings { }); break; default: break; } return minified; }
public void ProcessRequest(HttpContext context) { HttpRequest request = context.Request; // Read setName, contentType and version. All are required. They are // used as cache key string setName = request["s"] ?? string.Empty; string contentType = request["t"] ?? string.Empty; string version = request["v"] ?? string.Empty; // Decide if browser supports compressed response bool isCompressed = DO_GZIP && this.CanGZip(context.Request); // Response is written as UTF8 encoding. If you are using languages like // Arabic, you should change this to proper encoding UTF8Encoding encoding = new UTF8Encoding(false); // If the set has already been cached, write the response directly from // cache. Otherwise generate the response and cache it if (!this.WriteFromCache(context, setName, version, isCompressed, contentType)) { using (MemoryStream memoryStream = new MemoryStream(5000)) { // Decide regular stream or GZipStream based on whether the response // can be cached or not using (Stream writer = isCompressed ? (Stream)(new GZipStream(memoryStream, CompressionMode.Compress)) : memoryStream) { // Load the files defined in and process each file string setDefinition = GetFilelist(setName) ?? ""; string[] fileNames = setDefinition.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); string minifiedString = string.Empty; var minifier = new Minifier(); StringBuilder allScripts = new StringBuilder(); if (contentType == JS_TYPE) { foreach (string fileName in fileNames) { byte[] fileBytes = this.GetFileBytes(context, fileName.Trim(), encoding); allScripts.Append(Encoding.UTF8.GetString(fileBytes)); //writer.Write(fileBytes, 0, fileBytes.Length); } var codeSettings = new CodeSettings(); codeSettings.MinifyCode = true; codeSettings.OutputMode = OutputMode.SingleLine; //codeSettings.OutputMode = OutputMode.MultipleLines; codeSettings.InlineSafeStrings = true; codeSettings.MacSafariQuirks = true; codeSettings.RemoveUnneededCode = true; codeSettings.LocalRenaming = LocalRenaming.CrunchAll; codeSettings.EvalTreatment = EvalTreatment.MakeAllSafe; //codeSettings.CombineDuplicateLiterals = true; codeSettings.PreserveFunctionNames = false; minifiedString = minifier.MinifyJavaScript(allScripts.ToString(), codeSettings); } if (contentType == CSS_TYPE) { CssParser parser = new CssParser(); foreach (string fileName in fileNames) { byte[] fileBytes = this.GetFileBytes(context, fileName.Trim(), encoding); string crunchedStyles = parser.Parse(Encoding.UTF8.GetString(fileBytes)); allScripts.Append(crunchedStyles); } var cssSettings = new CssSettings(); cssSettings.CommentMode = CssComment.None; cssSettings.ColorNames = CssColor.Strict; //cssSettings.ExpandOutput = true; cssSettings.TermSemicolons = true; minifiedString = minifier.MinifyStyleSheet(allScripts.ToString(), cssSettings); } byte[] rikiki = Encoding.UTF8.GetBytes(minifiedString); writer.Write(rikiki, 0, rikiki.Length); writer.Close(); } // Cache the combined response so that it can be directly written // in subsequent calls byte[] responseBytes = memoryStream.ToArray(); context.Cache.Insert( GetCacheKey(setName, version, isCompressed), responseBytes, null, Cache.NoAbsoluteExpiration, CACHE_DURATION); // Generate the response this.WriteBytes(responseBytes, context, isCompressed, contentType); } } }
private static string MinifyStyleSheet(string input) { Minifier minifier = new Minifier(); return minifier.MinifyStyleSheet(input); }
private string GetMinifiedStylesheets() { Minifier minifier = new Minifier(); StringBuilder roll = new StringBuilder(); string appPath = GetAppPath(); foreach (string item in GetList()) { string fileName = appPath + item; roll.AppendFormat("/* ===== {0} ===== */\n", item); roll.Append(minifier.MinifyStyleSheet(File.ReadAllText(fileName)) + "\n\n"); } return roll.ToString(); }