/// <summary> /// /// </summary> /// <param name="compressor"></param> /// <returns></returns> public CssCompressor LoadCss(CssCompressor compressor) { foreach (string urlToAdd in this.CssToLoad) { compressor.AddUrl(urlToAdd); } return compressor; }
async static public Task<string> CompressCssAsync(string CssString) { return await TaskEx.RunPropagatingExceptionsAsync(() => { var CssWriter = new StringWriter(); var CssCompressor = new CssCompressor(new StringReader(CssString).GetJavaReader()); CssCompressor.compress(CssWriter.GetJavaWriter(), 1024); return CssWriter.ToString(); }); }
/// <summary> /// Process the request /// </summary> public void ProcessRequest(HttpContext context) { DateTime mod = new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime; if (File.Exists(context.Server.MapPath("~/Areas/Manager/Content/Css/Style.css"))) { FileInfo file = new FileInfo(context.Server.MapPath("~/Areas/Manager/Content/Css/Style.css")); mod = file.LastWriteTime > mod ? file.LastWriteTime : mod; } if (!ClientCache.HandleClientCache(context, resource, mod)) { StreamReader io = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(resource)); context.Response.ContentType = "text/css"; #if DEBUG context.Response.Write(io.ReadToEnd()); #else context.Response.Write(CssCompressor.Compress(io.ReadToEnd()).Replace("\n", "")); #endif io.Close(); // Now apply standard theme if (ConfigurationManager.AppSettings["disable_manager_theme"] != "1") { io = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(theme)); #if DEBUG context.Response.Write(io.ReadToEnd()); #else context.Response.Write(CssCompressor.Compress(io.ReadToEnd()).Replace("\n", "")); #endif io.Close(); } // Now check for application specific styles if (File.Exists(context.Server.MapPath("~/Areas/Manager/Content/Css/Style.css"))) { io = new StreamReader(context.Server.MapPath("~/Areas/Manager/Content/Css/Style.css")); #if DEBUG context.Response.Write(io.ReadToEnd()); #else context.Response.Write(CssCompressor.Compress(io.ReadToEnd()).Replace("\n", "")); #endif io.Close(); } } }
string YUI_CSS(string filesource, ConfigSettings.YUICompressionSettings.CSS CssSettings) { try { var csscompressor = new CssCompressor(); csscompressor.CompressionType = CssSettings.CompressionType; csscompressor.LineBreakPosition = CssSettings.LineBreakPosition; csscompressor.RemoveComments = CssSettings.RemoveComments; return(csscompressor.Compress(filesource)); } catch (Exception ex) { var msg = ex.Message; return(filesource); } }
/// <summary> /// 压缩 /// </summary> /// <param name="path"></param> public static void Compress(string path) { if (!Directory.Exists(path)) { return; } var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories); foreach (var file in files) { var finfo = new FileInfo(file); if (finfo.Attributes == FileAttributes.Compressed) { continue; } string strContent = File.ReadAllText(file, Encoding.UTF8); try { File.SetAttributes(file, FileAttributes.Compressed); if (!file.Contains(".min.")) { if (finfo.Extension.ToLower() == ".js") { var js = new JavaScriptCompressor { CompressionType = CompressionType.Standard, Encoding = Encoding.UTF8, IgnoreEval = false, ThreadCulture = System.Globalization.CultureInfo.CurrentCulture }; strContent = js.Compress(strContent); File.WriteAllText(file, strContent, Encoding.UTF8); } else if (finfo.Extension.ToLower() == ".css") { var css = new CssCompressor(); strContent = css.Compress(strContent); File.WriteAllText(file, strContent, Encoding.UTF8); } } } catch (Exception ex) { } } }
private ICompressor DetermineCompressor(CompressorConfig compressorConfig) { if (compressorConfig == null) { throw new ArgumentNullException("compressorConfig"); } // Define the compressor we wish to use. ICompressor compressor; var config = _compressorConfig as CssCompressorConfig; if (config != null) { var cssCompressorConfig = config; compressor = new CssCompressor { CompressionType = cssCompressorConfig.CompressionType, LineBreakPosition = cssCompressorConfig.LineBreakPosition, RemoveComments = cssCompressorConfig.RemoveComments }; } else if (_compressorConfig is JavaScriptCompressorConfig) { var jsCompressorConfig = (JavaScriptCompressorConfig)_compressorConfig; compressor = new JavaScriptCompressor { CompressionType = jsCompressorConfig.CompressionType, DisableOptimizations = jsCompressorConfig.DisableOptimizations, Encoding = jsCompressorConfig.Encoding, ErrorReporter = jsCompressorConfig.ErrorReporter, IgnoreEval = jsCompressorConfig.IgnoreEval, LineBreakPosition = jsCompressorConfig.LineBreakPosition, LoggingType = jsCompressorConfig.LoggingType, ObfuscateJavascript = jsCompressorConfig.ObfuscateJavascript, PreserveAllSemicolons = jsCompressorConfig.PreserveAllSemicolons, ThreadCulture = jsCompressorConfig.ThreadCulture }; } else { throw new InvalidOperationException("Unhandled CompressorConfig instance while trying to initialize internal compressor properties."); } return(compressor); }
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) { CssCompressor compressor = new CssCompressor(); string str = compressor.Compress(response.Content); response.Content = str; } response.ContentType = CssContentType; }
private ICompressor DetermineCompressor(CompressorConfig compressorConfig) { if (compressorConfig == null) { throw new ArgumentNullException("compressorConfig"); } // Define the compressor we wish to use. ICompressor compressor; var config = _compressorConfig as CssCompressorConfig; if (config != null) { var cssCompressorConfig = config; compressor = new CssCompressor { CompressionType = cssCompressorConfig.CompressionType, LineBreakPosition = cssCompressorConfig.LineBreakPosition, RemoveComments = cssCompressorConfig.RemoveComments }; } else if (_compressorConfig is JavaScriptCompressorConfig) { var jsCompressorConfig = (JavaScriptCompressorConfig)_compressorConfig; compressor = new JavaScriptCompressor { CompressionType = jsCompressorConfig.CompressionType, DisableOptimizations = jsCompressorConfig.DisableOptimizations, Encoding = jsCompressorConfig.Encoding, ErrorReporter = jsCompressorConfig.ErrorReporter, IgnoreEval = jsCompressorConfig.IgnoreEval, LineBreakPosition = jsCompressorConfig.LineBreakPosition, LoggingType = jsCompressorConfig.LoggingType, ObfuscateJavascript = jsCompressorConfig.ObfuscateJavascript, PreserveAllSemicolons = jsCompressorConfig.PreserveAllSemicolons, ThreadCulture = jsCompressorConfig.ThreadCulture }; } else { throw new InvalidOperationException("Unhandled CompressorConfig instance while trying to initialize internal compressor properties."); } return compressor; }
/// <summary> /// Builds the plugins CSS pack. /// </summary> /// <param name="corePlugins">The core widgets.</param> /// <param name="applicationServerPath">The application server path.</param> /// <param name="cssServerPath">The CSS server path.</param> /// <param name="fileName">Name of the file.</param> /// <returns>Return Html CSS links.</returns> public static String BuildPluginsCssPack(IEnumerable<ICorePlugin> corePlugins, String applicationServerPath, String cssServerPath, String fileName) { var packageFileName = fileName; var packagePath = Path.Combine(cssServerPath, packageFileName); if (!File.Exists(packagePath)) { if (!Directory.Exists(cssServerPath)) { Directory.CreateDirectory(cssServerPath); } var output = new StringBuilder(); foreach (var plugin in corePlugins) { if (String.IsNullOrEmpty(plugin.CssJsConfigPath) || String.IsNullOrEmpty(plugin.CssPath) || String.IsNullOrEmpty(plugin.CssPack)) { continue; } var pluginPackageCssServerPath = Path.Combine(plugin.PluginDirectory, plugin.CssPath, Constants.PluginCssPackage); var configPath = Path.Combine(plugin.PluginDirectory, plugin.CssJsConfigPath); var files = GetPluginCssPackFiles(plugin.CssPack, configPath); if (!File.Exists(pluginPackageCssServerPath) || File.GetLastWriteTimeUtc(pluginPackageCssServerPath) < GetMaxLastModifyDate(Path.Combine(plugin.PluginDirectory, plugin.CssPath), files)) { BuildPluginCssPack(plugin, applicationServerPath); } using (var reader = new StreamReader(pluginPackageCssServerPath)) { var temp = reader.ReadToEnd(); if (!String.IsNullOrEmpty(temp)) { output.Append(CssCompressor.Compress(temp)); } } } using (var writer = new StreamWriter(File.Create(packagePath))) { writer.Write(output.ToString()); } } return packagePath; }
//js,css合并 public static string ToCompressor(string type, string files) { List <string> list = files.Split(',').ToList(); Compressor compressor = new JavaScriptCompressor(); bool canCompressor = (type == "js" || type == "css"); if (type == "css") { compressor = new CssCompressor(); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.Count; i++) { if (string.IsNullOrWhiteSpace(list[i])) { continue; } var li = list[i].Split('|'); string lipath = HttpContext.Current.Server.MapPath(li[0]); if (!File.Exists(lipath)) { continue; } string readstr = File.ReadAllText(lipath, Encoding.UTF8); try { if (canCompressor && li.Length == 2 && li[1] == "1") { readstr = compressor.Compress(readstr); } } catch (Exception ex) { throw new Exception("压缩出错:" + li[0]); } sb.AppendLine(readstr); } return(sb.ToString()); }
public ActionResult Css(string keys) { var cssFiles = keys.Split('|').ToList(); string result = _provider.GetFromCache("resources.css." + Request.Url.PathAndQuery, () => { var sb = new StringBuilder(); string stylos; if (_provider.Enable.CssPreprocessing) { foreach (var f in cssFiles) { CSSDocument doc; var definition = GenerateSpriteDefinition(f); sb.AppendLine(definition.Document.ToOutput()); } stylos = sb.ToString(); } else { stylos = MothScriptHelper.GetFileContent(cssFiles, HttpContext).ToString(); } if (_provider.Enable.ScriptMinification) { // minification stylos = CssCompressor.Compress(stylos); } return(stylos); }, _provider.CacheDurations.ExternalScript); return(new ContentResult() { Content = result, ContentType = "text/css" }); }
private ICompressor CreateCompressor(FileType fileType) { ICompressor comp; switch (fileType) { case FileType.CSS: comp = new CssCompressor(); break; case FileType.JavaScript: comp = new JavaScriptCompressor(); break; default: throw new InvalidOperationException("Unrecognised file type for compressing: " + fileType); } ConfigureCompressor(comp); return(comp); }
public MainForm( ) { InitializeComponent( ); label5.Text = ""; cssCompressor = new CssCompressor { RemoveComments = true, LineBreakPosition = 8000, CompressionType = CompressionType.Standard }; jsCompressor = new JavaScriptCompressor { CompressionType = CompressionType.Standard, Encoding = System.Text.Encoding.UTF8, DisableOptimizations = false, LineBreakPosition = 8000 }; // Styling stuff this.FormatStyles( ); }
void ITemplate.Transform(Engine engine, Package package) { TemplatingLogger logger = TemplatingLogger.GetLogger(this.GetType()); Item item = package.GetByType(ContentType.Component); if (item.Properties.ContainsKey(Item.ItemPropertyTcmUri)) { Component component = (Component)engine.GetObject(item.Properties[Item.ItemPropertyTcmUri].ToString()); if (component.ComponentType == ComponentType.Multimedia) { if (string.Compare(component.BinaryContent.MultimediaType.MimeType, "text/css", true) == 0) { StructureGroup structureGroup = (StructureGroup)engine.GetObject(STRUCTURE_GROUP_FOR_CSS); string[] filenameParts = component.BinaryContent.Filename.Split(new char[] { '\\' }); string filename = filenameParts[filenameParts.GetUpperBound(0)]; string unMinifiedString = Encoding.Default.GetString(component.BinaryContent.GetByteArray()); string minifiedString = CssCompressor.Compress(unMinifiedString, 0, CssCompressionType.Hybrid); using (MemoryStream memoryStream = new MemoryStream(Encoding.Default.GetBytes(minifiedString))) { engine.PublishingContext.RenderedItem.AddBinary( memoryStream, filename, structureGroup, "mmbyname", component, component.BinaryContent.MultimediaType.MimeType ); } } } } }
private void Minify(FileInfo source, FileInfo file) { if (Options.IsDebugLoggingEnabled) { Logger.Log("Generating minified css file."); } try { var css = File.ReadAllText(source.FullName); string minified = ""; if (!string.IsNullOrEmpty(css)) { var compressor = new CssCompressor { RemoveComments = true }; minified = compressor.Compress(css); } InteropHelper.CheckOut(file.FullName); File.WriteAllText(file.FullName, minified, UTF8_ENCODING); // nest if (Options.IncludeCssInProject) { AddFileToProject(source, file, Options); } } catch (Exception ex) { Logger.Log(ex, "Failed to generate minified css file."); if (Options.ReplaceCssWithException) { SaveExceptionToFile(ex, file); } } }
/// <summary> /// set some default settings for the desired behaviour. /// </summary> /// <param name="comp"></param> private void ConfigureCompressor(ICompressor comp) { if (comp is IJavaScriptCompressor) { IJavaScriptCompressor jsComp = comp as IJavaScriptCompressor; jsComp.CompressionType = CompressionType.Standard; jsComp.DisableOptimizations = true; //TODO output errors - jsComp.ErrorReporter jsComp.IgnoreEval = false; //allow eval to pass through jsComp.ObfuscateJavascript = false; jsComp.PreserveAllSemicolons = true; //TODO would be nice to keep comments! } else if (comp is ICssCompressor) { CssCompressor cssComp = comp as CssCompressor; cssComp.CompressionType = CompressionType.Standard; cssComp.RemoveComments = false; } else { throw new ArgumentException("Unrecognised Compressor"); } }
public ActionResult GetStyle(string arquivo, string token) { arquivo = arquivo.Split('/')[0]; if (Styles == null) { Styles = new Hashtable(); } if (Styles[arquivo] == null) { var c = new GoogleClosure(); //string JSOriginal = System.IO.File.ReadAllText(Server.MapPath("/Scripts/")+id); string CSSComprimido = string.Empty; var diretorio = new DirectoryInfo(Server.MapPath("/Content/")); foreach (var i in diretorio.GetFiles().Where(a => a.Extension == ".css" && a.Name.Split('$')[0] == arquivo).OrderBy(a => a.Name.Split('$')[1])) { string CSSOriginal = System.IO.File.ReadAllText(i.FullName); CSSComprimido += CssCompressor.Compress(CSSOriginal); } Styles.Add(arquivo, CSSComprimido); } //Response.ContentType = "text/css"; //Response.CacheControl = "public"; //Response.Write(); return(new CSSResult { Style = Styles[arquivo].ToString() }); }
/// <summary> /// Include a URL asset into a web page using relative paths. Optionally add dynamic cachebuster and minify JS and CSS files. /// </summary> /// <param name="url">UrlHelper object</param> /// <param name="contentPath">Relative path to the asset</param> /// <param name="addCacheBuster">If true, appends a cachebuster to the generated URL from the file modification date</param> /// <param name="minify">If true minifies CSS and JS assets as new files and points the URL to them instead</param> /// <param name="fallback">If cachebuster fails, use this fallback value</param> /// <returns></returns> public static string Content(this UrlHelper url, string contentPath, bool addCacheBuster = false, bool minify = false, string fallback = "") { var queryString = contentPath.QueryString(); var filePath = contentPath.RemoveQueryString(); if (minify && !filePath.StartsWith("_halide.generated.")) { if (filePath.EndsWith(".js") || filePath.EndsWith(".css")) { bool proceed = true; var newContentpath = ""; if (filePath.Contains("/")) { newContentpath = filePath.Substring(0, filePath.LastIndexOf("/") + 1) + "_halide.generated." + filePath.Substring(filePath.LastIndexOf("/") + 1); } else { newContentpath = "_halide.generated." + filePath; } if (HttpContext.Current.Application.KeyExists(Storage.ConvertFilePathToKey(filePath) + "_MINIFY")) { if (Storage.FileExists(filePath)) { if (HttpContext.Current.Application[Storage.ConvertFilePathToKey(filePath) + "_MINIFY"].ToString() == Storage.MakeCacheBuster(filePath)) { filePath = newContentpath; proceed = false; } } } if (proceed) { if (Storage.FileExists(newContentpath)) { Storage.DeleteFiles(newContentpath); } var minified = ""; if (filePath.EndsWith(".js")) { var jsc = new JavaScriptCompressor(); minified = jsc.Compress(Storage.ReadFile(filePath)); } if (filePath.EndsWith(".css")) { var cssc = new CssCompressor(); minified = cssc.Compress(Storage.ReadFile(filePath)); } Storage.WriteFile(newContentpath, minified); HttpContext.Current.Application[Storage.ConvertFilePathToKey(filePath) + "_MINIFY"] = Storage.MakeCacheBuster(filePath); filePath = newContentpath; Debug.WriteLine("MINIFIED TO " + filePath); } else { Debug.WriteLine("SKIPPED MINIFICATION FOR " + filePath); } } } if (addCacheBuster) { queryString += (queryString.Contains("?") ? "&" : "?") + "_cachebuster=" + Storage.MakeCacheBuster(filePath, fallback); } return(url.Content(filePath + queryString)); }
private void btnCompressCss_Click(object sender, EventArgs e) { txtCode.Text = CssCompressor.Compress(txtCode.Text); }
private void btnCompressor_Click(object sender, EventArgs e) { if (this.ListFile.Items.Count == 0) { return; } DirectoryInfo oldDir = new DirectoryInfo(strFilePath); DirectoryInfo newDir = new DirectoryInfo(oldDir.FullName.Substring(0, oldDir.FullName.Length - 1) + "_bak"); if (!newDir.Exists) { newDir.Create(); } Encoding encoder = GetEncoding(); int errorCount = 0; long oldSize = 0; long newSize = 0; for (int i = 0; i < this.fileList.Count; i++) { try { FileInfo file = this.fileList[i]; FileInfo newFile = new FileInfo(file.FullName.Replace(oldDir.FullName, newDir.FullName)); if (!newFile.Directory.Exists) { newFile.Directory.Create(); } string strContent = File.ReadAllText(file.FullName, encoder); if (file.Extension.ToLower() == ".js") { JavaScriptCompressor js = new JavaScriptCompressor(strContent, false, encoder, System.Globalization.CultureInfo.CurrentCulture); strContent = js.Compress(); } else if (file.Extension.ToLower() == ".css") { strContent = CssCompressor.Compress(strContent); } File.WriteAllText(newFile.FullName, strContent); this.ListFile.Items[i].ForeColor = Color.Blue; this.ListFile.Items[i].SubItems[2].Text = FormatSize(strContent.Length); this.ListFile.Items[i].SubItems[3].Text = "完成"; oldSize += file.Length; newSize += strContent.Length; } catch (Exception ex) { this.ListFile.Items[i].ForeColor = Color.Red; this.ListFile.Items[i].SubItems[2].Text = "0"; this.ListFile.Items[i].SubItems[3].Text = "错误:" + ex.Message; errorCount++; } int ii = i + 1; this.txtInfo.Text = "共" + this.fileList.Count.ToString() + "个文件!正处理第" + ii.ToString() + "个文件!"; Application.DoEvents(); } string strInfo = "压缩完成!\r\n"; if (errorCount > 0) { strInfo += errorCount.ToString() + "个文件压缩发生错误!\r\n"; } strInfo += "总体压缩:"; double rate = 1.0 * newSize / oldSize * 100; strInfo += rate.ToString() + "%"; this.txtInfo.Text = strInfo.Replace("\r\n", " "); if (errorCount > 0) { MessageBox.Show(strInfo, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show(strInfo, "成功", MessageBoxButtons.OK, MessageBoxIcon.Information); } System.Diagnostics.Process.Start(newDir.FullName); }
internal YuiMinifier() { compressor = new CssCompressor(); }
public void SetUp() { target = new CssCompressor(); }
/// <summary> /// 压缩 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnCompressor_Click(object sender, EventArgs e) { if (this.ListFile.Items.Count != 0) { progressBar1.Maximum = this.ListFile.Items.Count; progressBar1.Value = 0; DirectoryInfo info = new DirectoryInfo(this.strFilePath); Encoding encoding = this.GetEncoding(); int num = 0; long num2 = 0L; long num3 = 0L; int jswitdh = -1; int.TryParse(txt_HHWZ.Text, out jswitdh); int csswidth = -1; int.TryParse(txt_HCD.Text, out csswidth); bool blRemoveRemark = cb_RemoveRemark.Checked; bool blBackup = rb_bf1.Checked; int iCS = 25; int.TryParse(txt_CS.Text, out csswidth); iCS *= 1000; CssCompressionType ct = CssCompressionType.StockYuiCompressor; switch (cbb_YSLX.SelectedIndex) { case 0: ct = CssCompressionType.StockYuiCompressor; break; case 1: ct = CssCompressionType.Hybrid; break; case 2: ct = CssCompressionType.MichaelAshRegexEnhancements; break; } DirectoryInfo info2 = new DirectoryInfo(info.FullName.Substring(0, info.FullName.Length - 1) + "_bak"); if (blBackup) { if (!info2.Exists) { info2.Create(); } } for (int i = 0; i < this.fileList.Count; i++) { try { FileInfo infoold = this.fileList[i]; if (infoold.Name.Contains(".min.")) { this.ListFile.Items[i].SubItems[3].Text = "跳过"; } else { string strContent = File.ReadAllText(infoold.FullName, encoding); if (blBackup) {//备份 FileInfo infobak = new FileInfo(infoold.FullName.Replace(info.FullName, info2.FullName)); if (!infobak.Directory.Exists) { infobak.Directory.Create(); } //写入 File.WriteAllText(infobak.FullName, strContent); } string strMsg = ""; if (infoold.Extension.ToLower() == ".js") { if (cb_YSJS.Checked) { try { strMsg = new JavaScriptCompressor(strContent, false, encoding, CultureInfo.CurrentCulture).Compress(isObfus.Checked, semi.Checked, opt.Checked, jswitdh); this.ListFile.Items[i].SubItems[3].Text = "完成"; } catch (Exception ex) { if (cb_ZXYSJS.Checked) { //假如压缩失败(error),可进行在线压缩 string strMsg2 = RequestService("https://tool.oschina.net/action/jscompress/js_compress?munge=" + (isObfus.Checked ? "1" : "0") + "&linebreakpos=", RequestMethod.POST, strContent); if (strMsg2.StartsWith("{\"result\":")) { var rspObj = JsonConvert.DeserializeAnonymousType(strMsg2, new { result = "" }); strMsg = rspObj.result; //strMsg = strMsg2.Remove(strMsg2.Length - 2, 2).Remove(0, 10); //strMsg2.TrimStart('{').TrimEnd('}').Remove(0, 9).Trim('\"'); this.ListFile.Items[i].SubItems[3].Text = "完成-在线"; } else { //if (strMsg2.StartsWith("{\"msg\":")) //{ this.ListFile.Items[i].ForeColor = Color.Red; this.ListFile.Items[i].SubItems[2].Text = "0"; this.ListFile.Items[i].SubItems[3].Text = "错误(本地、在线):" + strMsg2; num++; //} } } else { throw ex; } } } } else if (infoold.Extension.ToLower() == ".css") { if (cb_YSCss.Checked) { try { bool ret = false; new System.Threading.Tasks.TaskFactory().StartNew(() => {//异步等待 strMsg = CssCompressor.Compress(strContent, csswidth, ct, blRemoveRemark); ret = true; }).Wait(iCS); if (!ret) { throw new Exception("超时"); } this.ListFile.Items[i].SubItems[3].Text = "完成"; } catch (Exception ex) { if (cb_ZXYSCss.Checked) { //假如压缩失败(error),可进行在线压缩 string strMsg2 = RequestService("https://tool.oschina.net/action/css_compress/js_compress?linebreakpos=", RequestMethod.POST, strContent); if (strMsg2.StartsWith("{\"result\":")) { var rspObj = JsonConvert.DeserializeAnonymousType(strMsg2, new { result = "" }); strMsg = rspObj.result; //strMsg = strMsg2.Remove(strMsg2.Length - 2, 2).Remove(0, 10); //strMsg2.TrimStart('{').TrimEnd('}').Remove(0, 9).Trim('\"'); this.ListFile.Items[i].SubItems[3].Text = "完成-在线:"; } else { //if (strMsg2.StartsWith("{\"msg\":")) //{ this.ListFile.Items[i].ForeColor = Color.Red; this.ListFile.Items[i].SubItems[2].Text = "0"; this.ListFile.Items[i].SubItems[3].Text = "错误(本地、在线):" + strMsg2; num++; //} } } else { throw ex; } } } else { this.ListFile.Items[i].SubItems[3].Text = "跳过"; } } if (this.ListFile.Items[i].SubItems[3].Text.Contains("完成")) { //覆盖 File.WriteAllText(infoold.FullName, strMsg); this.ListFile.Items[i].ForeColor = Color.Blue; this.ListFile.Items[i].SubItems[2].Text = this.FormatSize((long)strMsg.Length); //this.ListFile.Items[i].SubItems[3].Text = "完成"; num2 += strContent.Length; num3 += strMsg.Length; } } } catch (Exception exception) { this.ListFile.Items[i].ForeColor = Color.Red; this.ListFile.Items[i].SubItems[2].Text = "0"; this.ListFile.Items[i].SubItems[3].Text = "错误:" + exception.Message; num++; } progressBar1.PerformStep(); int num5 = i + 1; this.txtInfo.Text = "共" + this.fileList.Count.ToString() + "个文件!正处理第" + num5.ToString() + "个文件!"; Application.DoEvents(); } string text = "压缩完成!\r\n"; if (num > 0) { text = text + num.ToString() + "个文件压缩发生错误!\r\n"; } text = text + "总体压缩:"; text = text + Math.Round((((1.0 * num3) / ((double)num2)) * 100.0), 2) + "%"; this.txtInfo.Text = text.Replace("\r\n", " "); if (num > 0) { MessageBox.Show(text, "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand); } else { MessageBox.Show(text, "成功", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } }
/// <summary> /// Compress the css files and store them in the specified css file. /// </summary> /// <param name="outputPath">The path for the crushed css file.</param> /// <param name="files">The css files to be crushed.</param> private static void ProcessFiles(string outputPath, IEnumerable <CssFile> files) { outputPath = HostingEnvironment.MapPath(outputPath); var uncompressedContents = new StringBuilder(); var toBeStockYuiCompressedContents = new StringBuilder(); var toBeMichaelAshRegexCompressedContents = new StringBuilder(); var toBeHybridCompressedContents = new StringBuilder(); foreach (var file in files) { var fileInfo = new FileInfo(HostingEnvironment.MapPath(file.FilePath)); var fileContents = _retryableFileOpener.ReadAllText(fileInfo); var fileName = fileInfo.Name.ToLower(); if (fileName.EndsWith(".less") || fileName.EndsWith(".less.css")) { fileContents = ProcessDotLess(fileContents); } fileContents = _cssPathRewriter.RewriteCssPaths(outputPath, fileInfo.FullName, fileContents); switch (file.CompressionType) { case CssCompressionType.None: uncompressedContents.AppendLine(fileContents); break; case CssCompressionType.StockYuiCompressor: toBeStockYuiCompressedContents.AppendLine(fileContents); break; case CssCompressionType.MichaelAshRegexEnhancements: toBeMichaelAshRegexCompressedContents.AppendLine(fileContents); break; case CssCompressionType.Hybrid: toBeHybridCompressedContents.AppendLine(fileContents); break; } } var uncompressedContent = uncompressedContents.ToString(); var stockYuiCompressedCompressedContent = toBeStockYuiCompressedContents.ToString(); var michaelAshRegexCompressedContent = toBeMichaelAshRegexCompressedContents.ToString(); var hybridCompressedContent = toBeHybridCompressedContents.ToString(); if (!string.IsNullOrEmpty(stockYuiCompressedCompressedContent)) { stockYuiCompressedCompressedContent = CssCompressor.Compress(stockYuiCompressedCompressedContent, 0, Yahoo.Yui.Compressor.CssCompressionType.StockYuiCompressor); } if (!string.IsNullOrEmpty(michaelAshRegexCompressedContent)) { michaelAshRegexCompressedContent = CssCompressor.Compress(michaelAshRegexCompressedContent, 0, Yahoo.Yui.Compressor.CssCompressionType.MichaelAshRegexEnhancements); } if (!string.IsNullOrEmpty(hybridCompressedContent)) { hybridCompressedContent = CssCompressor.Compress(hybridCompressedContent, 0, Yahoo.Yui.Compressor.CssCompressionType.Hybrid); } using (var writer = new MemoryStream()) { var uniEncoding = Encoding.Default; if (!string.IsNullOrEmpty(uncompressedContent)) { writer.Write(uniEncoding.GetBytes(uncompressedContent), 0, uniEncoding.GetByteCount(uncompressedContent)); } if (!string.IsNullOrEmpty(stockYuiCompressedCompressedContent)) { writer.Write(uniEncoding.GetBytes(stockYuiCompressedCompressedContent), 0, uniEncoding.GetByteCount(stockYuiCompressedCompressedContent)); } if (!string.IsNullOrEmpty(michaelAshRegexCompressedContent)) { writer.Write(uniEncoding.GetBytes(michaelAshRegexCompressedContent), 0, uniEncoding.GetByteCount(michaelAshRegexCompressedContent)); } if (!string.IsNullOrEmpty(hybridCompressedContent)) { writer.Write(uniEncoding.GetBytes(hybridCompressedContent), 0, uniEncoding.GetByteCount(hybridCompressedContent)); } //We might be competing with the web server for the output file, so try to overwrite it at regular intervals using (var outputFile = _retryableFileOpener.OpenFileStream(new FileInfo(outputPath), 5, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) { var overwrite = true; if (outputFile.Length > 0) { var newOutputFileHash = _hasher.CalculateMd5Etag(writer); var outputFileHash = _hasher.CalculateMd5Etag(outputFile); overwrite = (newOutputFileHash != outputFileHash); } if (overwrite) { writer.Seek(0, SeekOrigin.Begin); outputFile.SetLength(writer.Length); //Truncate current file outputFile.Seek(0, SeekOrigin.Begin); var bufferSize = Convert.ToInt32(Math.Min(writer.Length, BufferSize)); var buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = writer.Read(buffer, 0, bufferSize)) > 0) { outputFile.Write(buffer, 0, bytesRead); } outputFile.Flush(); } } } }
/// <summary> /// 获取文件压缩内容 /// </summary> /// <param name="fileName">文件名</param> /// <param name="inputCharset">web服务器编码格式</param> /// <returns>文件压缩内容</returns> private string GetCompressContent(string fileName, string inputCharset) { Encoding encoding = Encoding.UTF8; if (!string.IsNullOrWhiteSpace(inputCharset)) { try { encoding = Encoding.GetEncoding(inputCharset); } catch (Exception ex) { LogUtil.Log("XFramework文件压缩编码转换异常", ex, LogLevel.Warn); } } string rtnRst = string.Empty; try { if (!string.IsNullOrWhiteSpace(DirectoryPath)) { DirectoryPath = "\\" + DirectoryPath + "\\"; } string filePath = HttpContext.Current.Server.MapPath(DirectoryPath + fileName); if (!File.Exists(filePath)) { return(null); } rtnRst = File.ReadAllText(filePath, encoding); if (IsJsFile) { if (filePath.EndsWith(".no.js") && !filePath.EndsWith(".min.js")) { return(rtnRst); } var compressor = new JavaScriptCompressor { Encoding = encoding }; rtnRst = compressor.Compress(rtnRst); } else { if (filePath.EndsWith(".no.css") && !filePath.EndsWith(".min.css")) { return(rtnRst); } var compressor = new CssCompressor(); rtnRst = compressor.Compress(rtnRst); } } catch (Exception ex) { LogUtil.Log("XFramework文件压缩异常", ex, LogLevel.Warn); } return(rtnRst); }
public string Render(string outputFile) { if (Debug) { string output = String.Empty; foreach (string file in webFiles) { string outputPath = (HttpContext.Current.Handler as Page).ResolveUrl(file); if (Type == BundleType.CSS) { output += MakeCSSTag(outputPath) + "\r\n"; } else { output += MakeJSTag(outputPath) + "\r\n"; } } return(output); } else { string fileAges = String.Empty; foreach (string file in files) { fileAges += file + File.GetLastWriteTime(file).ToString(); } fileAges = AppendOptionsAsString(fileAges); //So that file will be regenerated if options are changed string hash = CalculateMD5Hash(fileAges); string fileWithHash = InjectHash(outputFile, hash); string fileOnSystem = HttpContext.Current.Server.MapPath(fileWithHash); string outputWebPath = (HttpContext.Current.Handler as Page).ResolveUrl(fileWithHash); if (!File.Exists(fileOnSystem)) { //Do CSS/JS Compression string totalContents = String.Empty; CssCompressor cssCompressor = null; JavaScriptCompressor jsCompressor = null; if (Type == BundleType.CSS) { cssCompressor = new CssCompressor(); cssCompressor.CompressionType = (UseCompression ? CompressionType.Standard : CompressionType.None); cssCompressor.RemoveComments = RemoveComments; cssCompressor.LineBreakPosition = LineBreakPosition; } else { jsCompressor = new JavaScriptCompressor(); jsCompressor.CompressionType = (UseCompression ? CompressionType.Standard : CompressionType.None); jsCompressor.DisableOptimizations = DisableOptimizations; jsCompressor.IgnoreEval = IgnoreEval; jsCompressor.LineBreakPosition = LineBreakPosition; jsCompressor.ObfuscateJavascript = Obfuscate; jsCompressor.PreserveAllSemicolons = PreserveSemicolons; } foreach (string file in files) { totalContents += File.ReadAllText(file) + "\n"; } totalContents = (Type == BundleType.CSS ? cssCompressor.Compress(totalContents) : jsCompressor.Compress(totalContents)); File.WriteAllText(fileOnSystem, totalContents); } return(MakeTag(outputWebPath) + "\r\n"); } }
public void TestCssFileA() { string min = CssCompressor.Compress(a_chirp_css); Assert.AreEqual(min, a_min_css); }
/// <summary> /// Constructs an instance of the YUI CSS Minifier /// </summary> /// <param name="settings">Settings of YUI CSS Minifier</param> public YuiCssMinifier(YuiCssMinificationSettings settings) { _originalEmbeddedCssMinifier = CreateOriginalCssMinifierInstance(settings, false); _originalInlineCssMinifier = CreateOriginalCssMinifierInstance(settings, true); }
private ResourcePath ProcessGroup(ResourceCollection set, bool minify, bool cacheRefresh) { if (!set.Any()) { throw new ApplicationException("Cannot process empty group"); } var firstElement = set.First(); if (set.Count() == 1 && firstElement.IsExternal) { return new ResourcePath { ContentType = firstElement.ContentType, Url = firstElement.Url } } ; var cacheKey = minify ? set.UnqiueId.ToMinPath() : set.UnqiueId; var upgraded = false; try { cacheLock.EnterUpgradeableReadLock(); var cached = cacheProvider.Get <ResourcePath>(cacheKey); if (cached != null && cacheRefresh) { return(cached); } cacheLock.EnterWriteLock(); upgraded = true; var priorWrite = cacheProvider.Get <ResourcePath>(cacheKey); if (priorWrite != null && cacheRefresh) { return(priorWrite); } // regenerate var result = new ResourcePath(); result.ContentType = firstElement.ContentType; result.Url = Url.Action("fetch", "resource", new { id = cacheKey }); // mash result.Contents = set.Mash(); // minify if (minify) { result.Contents = firstElement.ContentType == "text/javascript" ? JavaScriptCompressor.Compress(result.Contents) : CssCompressor.Compress(result.Contents); } // write backup file var physicalFilePath = GetFilePath(set.UnqiueId, minify); if (!Directory.Exists(Path.GetDirectoryName(physicalFilePath))) { Directory.CreateDirectory(Path.GetDirectoryName(physicalFilePath)); } if (File.Exists(physicalFilePath)) { File.Delete(physicalFilePath); } File.WriteAllText(physicalFilePath, result.Contents); result.FileName = physicalFilePath; cacheProvider.Add(cacheKey, result, set.Files()); return(result); } finally { if (upgraded) { cacheLock.ExitWriteLock(); } cacheLock.ExitUpgradeableReadLock(); } }
/// <summary><![CDATA[ /// Include a URL asset into a web page using relative paths. Optionally add dynamic cachebuster and minify JS and CSS files. /// ]]></summary> /// <param name="url">UrlHelper object</param> /// <param name="contentPath">Relative path to the asset</param> /// <param name="addCacheBuster">If true, appends a cachebuster to the generated URL from the file modification date</param> /// <param name="minify">If true minifies CSS and JS assets as new files and points the URL to them instead</param> /// <param name="fallback">If cachebuster fails, use this fallback value</param> /// <returns></returns> public static string Content(this UrlHelper url, string contentPath, bool addCacheBuster = false, bool minify = false, string fallback = "") { var queryString = contentPath.QueryString(); var filePath = contentPath.RemoveQueryString(); try { if (minify && !filePath.StartsWith("_carbide.generated.")) { if (filePath.EndsWith(".js") || filePath.EndsWith(".css")) { bool proceed = true; var newContentpath = ""; if (filePath.Contains("/")) { newContentpath = filePath.Substring(0, filePath.LastIndexOf("/") + 1) + "_carbide.generated." + filePath.Substring(filePath.LastIndexOf("/") + 1); } else { newContentpath = "_carbide.generated." + filePath; } FileInfo fileInfo = new FileInfo(StorageHelpers.MapPath(filePath)); DateTime lastModified = fileInfo.LastWriteTime; var item = fileInfo.Length + "|" + lastModified.DateFormat(Carbide.Constants.DateFormats.Utc); if (HttpContext.Current.Application.KeyExists(StorageHelpers.ConvertFilePathToKey(filePath))) { if (HttpContext.Current.Application[StorageHelpers.ConvertFilePathToKey(filePath)].ToString() == item) { if (StorageHelpers.FileExists(newContentpath)) { filePath = newContentpath; proceed = false; } } else { if (StorageHelpers.FileExists(filePath) == false) { filePath = newContentpath; proceed = false; } } } else { if (StorageHelpers.FileExists(filePath) == false) { proceed = false; } } if (proceed) { if (StorageHelpers.FileExists(newContentpath)) { StorageHelpers.DeleteFiles(newContentpath); } var minified = ""; if (filePath.EndsWith(".js")) { var jsc = new JavaScriptCompressor(); minified = jsc.Compress(StorageHelpers.ReadFile(filePath)); } if (filePath.EndsWith(".css")) { var cssc = new CssCompressor(); minified = cssc.Compress(StorageHelpers.ReadFile(filePath)); } StorageHelpers.WriteFile(newContentpath, minified); Debug.WriteLine("MINIFIED TO " + newContentpath); fileInfo = new FileInfo(StorageHelpers.MapPath(filePath)); lastModified = fileInfo.LastWriteTime; item = fileInfo.Length + "|" + lastModified.DateFormat(Carbide.Constants.DateFormats.Utc); HttpContext.Current.Application[StorageHelpers.ConvertFilePathToKey(filePath)] = item; filePath = newContentpath; } else { Debug.WriteLine("SKIPPED MINIFICATION FOR " + filePath); } } } if (addCacheBuster) { queryString += (queryString.Contains("?") ? "&" : "?") + "_cachebuster=" + StorageHelpers.MakeCacheBuster(filePath, fallback); } } catch (Exception e) { Debug.WriteLine(e); } return(url.Content(filePath + queryString)); }
public string CompressContent(string content) { return(CssCompressor.Compress(content, columnWidth, compressionType)); }
private byte[] GenerateCode(string InputFileContent, string InputFilePath, IVsGeneratorProgress GenerateProgress) { bool bDo = false; string OutputFileContent = InputFileContent; string[] szFiles; string szInputContent = string.Empty; string szOutputContent = string.Empty; _Ext = Path.GetExtension(InputFilePath); if (_Ext.Equals(Consts.CSSExt)) { _Ext = OptionPage.CSSExt; bDo = true; } if (_Ext.Equals(Consts.JSExt)) { _Ext = OptionPage.JSExt; bDo = true; } if (bDo) { if (InputFileContent.StartsWith("// FILE LIST")) { szFiles = GetFileList(InputFileContent); } else { szFiles = new string[] { string.Empty }; } foreach (string szFile in szFiles) { if (szFile == string.Empty) { szInputContent = InputFileContent; } else { string szPath = Path.Combine(Path.GetDirectoryName(InputFilePath), szFile.Replace("//", string.Empty).Trim( )); szInputContent = File.ReadAllText(szPath); } if (_Ext == OptionPage.JSExt) { switch (OptionPage.JSEngine) { case JSEngineType.MicrosoftAjaxMinifier: { Minifier oMinifier = new Minifier( ); CodeSettings oSettings = new CodeSettings( ); oSettings.LocalRenaming = OptionPage.JSMsLocalRename; oSettings.OutputMode = OptionPage.JSMsOutputMode; oSettings.PreserveImportantComments = OptionPage.JSMsPreserveImportantComments; oSettings.RemoveUnneededCode = OptionPage.JSMsRemoveUnneededCode; oSettings.PreserveFunctionNames = OptionPage.JSMsPreserveFunctionNames; oSettings.RemoveFunctionExpressionNames = OptionPage.JSMsRemoveFunctionExpressionNames; szOutputContent += oMinifier.MinifyJavaScript(szInputContent, oSettings); } break; case JSEngineType.GoogleClosureCompiler: { GoogleClosure oCompiler = new GoogleClosure( ); szOutputContent += oCompiler.Compress(szInputContent, OptionPage.JSGCompilationLevel); } break; case JSEngineType.YUICompressor: { JavaScriptCompressor oCompressor = new JavaScriptCompressor( ); oCompressor.CompressionType = CompressionType.Standard; oCompressor.DisableOptimizations = OptionPage.JSYDisableOptimizations; oCompressor.PreserveAllSemicolons = OptionPage.JSYPreserveAllSemicolons; oCompressor.ObfuscateJavascript = OptionPage.JSYObfuscateJavascript; szOutputContent += oCompressor.Compress(szInputContent); } break; } } if (_Ext == OptionPage.CSSExt) { switch (OptionPage.CSSEngine) { case CSSEngineType.MicrosoftAjaxMinifier: { Minifier oMinifier = new Minifier( ); CssSettings oSettings = new CssSettings( ); oSettings.ColorNames = OptionPage.CSSMsColorNames; oSettings.CommentMode = OptionPage.CSSMsCommentMode; oSettings.CssType = OptionPage.CSSMsCssType; oSettings.MinifyExpressions = OptionPage.CSSMsMinifyExpressions; oSettings.OutputMode = OptionPage.CSSMsOutputMode; szOutputContent += oMinifier.MinifyStyleSheet(szInputContent, oSettings); } break; case CSSEngineType.YUICompressor: { CssCompressor oCompressor = new CssCompressor( ); oCompressor.CompressionType = CompressionType.Standard; oCompressor.RemoveComments = OptionPage.CSSYRemoveComments; szOutputContent += oCompressor.Compress(szInputContent); } break; } } szOutputContent += Environment.NewLine; OutputFileContent = szOutputContent; } return(Encoding.UTF8.GetBytes(OutputFileContent)); } else { GenerateProgress.GeneratorError(1, 1, "VSMinifier can handle only js and css files...", 0, 0); return(null); } }
private ResourcePath ProcessResource(Resource resource, bool minify, bool cacheRefresh) { if (resource == null) { throw new ArgumentNullException("resource"); } if (!(resource is EmbeddedResource) && (resource.IsExternal || !minify)) { return new ResourcePath { ContentType = resource.ContentType, Url = resource.Url } } ; var cacheKey = resource.FileName.ToMinPath(); var upgraded = false; try { cacheLock.EnterUpgradeableReadLock(); var cached = cacheProvider.Get <ResourcePath>(cacheKey); if (cached != null && cacheRefresh) { return(cached); } cacheLock.EnterWriteLock(); upgraded = true; var priorWrite = cacheProvider.Get <ResourcePath>(cacheKey); if (priorWrite != null && cacheRefresh) { return(priorWrite); } // regenerate var result = new ResourcePath(); result.ContentType = resource.ContentType; result.Contents = resource.FileContents(); result.Url = Url.Action("fetch", "resource", new { id = cacheKey }); // minify if (minify) { result.Contents = resource.ContentType == "text/javascript" ? JavaScriptCompressor.Compress(result.Contents) : CssCompressor.Compress(result.Contents); } // write backup file var physicalFilePath = GetFilePath(cacheKey, false); if (!Directory.Exists(Path.GetDirectoryName(physicalFilePath))) { Directory.CreateDirectory(Path.GetDirectoryName(physicalFilePath)); } if (File.Exists(physicalFilePath)) { File.Delete(physicalFilePath); } File.WriteAllText(physicalFilePath, result.Contents); result.FileName = physicalFilePath; cacheProvider.Add(cacheKey, result, resource.DependentFile); return(result); } finally { if (upgraded) { cacheLock.ExitWriteLock(); } cacheLock.ExitUpgradeableReadLock(); } }