public string Minify(string content, bool enableOptimizations = false, bool obfuscate = false, CultureInfo culture = null)
 {
     JavaScriptCompressor javaScriptCompressor = new JavaScriptCompressor();
     javaScriptCompressor.CompressionType = CompressionType.Standard;
     javaScriptCompressor.ThreadCulture = culture ?? CultureInfo.InvariantCulture;
     javaScriptCompressor.Encoding = Encoding.UTF8;
     javaScriptCompressor.DisableOptimizations = !enableOptimizations;
     javaScriptCompressor.IgnoreEval = true;
     javaScriptCompressor.LineBreakPosition = -1;
     javaScriptCompressor.ObfuscateJavascript = obfuscate;
     javaScriptCompressor.PreserveAllSemicolons = false;
     return javaScriptCompressor.Compress(content);
 }
Esempio n. 2
0
 protected override void Minify(string fileName, string outputFileName)
 {
     Log(Level.Info, "Minifying JavaScript {0} -> {1}", fileName, outputFileName);
     var compressor = new JavaScriptCompressor(File.ReadAllText(fileName));
     string output = compressor.Compress();
     File.WriteAllText(outputFileName, output);
 }
        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;
        }
Esempio n. 4
0
        public static string Minify(string fullFileName, string text, EnvDTE.ProjectItem projectItem,Yui.JsSettings jsSettings)
        {
            string returnScript = string.Empty;
            var reporter = new EcmaScriptErrorReporter(fullFileName, projectItem);
            try
            {
                // http://chirpy.codeplex.com/workitem/133
                int lineBreakPosition = jsSettings.LineBreakPosition;
                if (lineBreakPosition == 0)
                {
                    lineBreakPosition = -1;
                }

                // http://chirpy.codeplex.com/workitem/54
                // http://chirpy.codeplex.com/workitem/60
                var compressor = new JavaScriptCompressor(text, true, System.Text.Encoding.UTF8, System.Globalization.CultureInfo.InvariantCulture, false, reporter);
                returnScript = compressor.Compress(jsSettings.IsObfuscateJavascript, jsSettings.PreserveAllSemiColons, jsSettings.DisableOptimizations, lineBreakPosition);
            }
            catch (System.Exception eError)
            {
                returnScript= string.Format("/* error = {0} */",eError.Message);
            }

            return returnScript;
        }
        public static string GetScript(ScriptIds ids, string token)
        {
            var script = @"(function (v, t) {
                if (!t) t = 'hidden';
                var chk = function () {
                    var elem = document.getElementById('" + ids.ScriptId + @"');
                    document.getElementById('" + ids.HoneyPotContainerId + @"').style.display = 'none';
                    if (elem) {
                        var newElem = document.createElement('div');
                        newElem.innerHTML = '<input type=""' + t + '"" name=""" + ids.TokenId + @""" value=""' + v + '"" />';
                        elem.parentNode.appendChild(newElem);
                        elem.parentNode.removeChild(elem);
                    } else {
                        window.setTimeout(chk, 500);
                    }
                };
                window.setTimeout(chk, 500);
                document.getElementById('" + ids.HoneyPotContainerId + @"').style.display = 'none';
                }('" + token + @"'));";

            var compressor = new JavaScriptCompressor
            {
                Encoding = Encoding.UTF8,
                DisableOptimizations = false,
                ObfuscateJavascript = true,
                PreserveAllSemicolons = true,
                IgnoreEval = true,
                ThreadCulture = Globalization.CultureInfo.InvariantCulture
            };

            var example = compressor.Compress(script);

            return example;
        }
Esempio n. 6
0
 public override void Process(BundleContext context, BundleResponse response)
 {
     var compressor = new JavaScriptCompressor();
     
     response.Content = compressor.Compress(response.Content);
     response.ContentType = ContentTypes.JavaScript;
 }
Esempio n. 7
0
 static string jsMinify(IEnumerable<string> files) {
   StringBuilder sb = new StringBuilder(); 
   var compr = new JavaScriptCompressor();
   foreach (var fn in files) {
     var file = File.ReadAllText(fn, Encoding.UTF8);
     var res = compr.Compress(file);
     sb.Append(res); 
   }
   return sb.ToString();
 }
Esempio n. 8
0
        public override void Process(BundleContext context, BundleResponse response)
        {
            response.ContentType = ContentTypes.JavaScript;

            if (context.HttpContext.IsDebuggingEnabled)
            {
                return;
            }

            var compressor = new JavaScriptCompressor();
            response.Content = compressor.Compress(response.Content);
        }
Esempio n. 9
0
 public override void Parse(TextReader reader, IProcessorContext context)
 {
     if (AssetPipeline.MinifyJs)
     {
         var compressor = new JavaScriptCompressor(reader.ReadToEnd());
         context.Output.Write(compressor.Compress());
     }
     else
     {
         context.Output.Write(reader.ReadToEnd());
     }
 }
Esempio n. 10
0
 /// <inheritdoc cref="IResourceMinifier.Minify" />
 public string Minify(Settings settings, ResourceSet resourceSet, string combinedContent)
 {
     var compressor = new JavaScriptCompressor();
     compressor.Encoding = Encoding.UTF8;
     compressor.ThreadCulture = CultureInfo.InvariantCulture;
     compressor.LoggingType = IsVerboseLogging == true ? LoggingType.Debug : LoggingType.None;
     compressor.PreserveAllSemicolons = PreserveAllSemicolons == null ? false : PreserveAllSemicolons.Value;
     compressor.DisableOptimizations = DisableOptimizations == null ? false : DisableOptimizations.Value;
     compressor.LineBreakPosition = LineBreakPosition == null ? -1 : LineBreakPosition.Value;
     compressor.IgnoreEval = IgnoreEval == null ? true : IgnoreEval.Value;
     compressor.ObfuscateJavascript = ObfuscateJavascript == null ? true : ObfuscateJavascript.Value;
     return compressor.Compress(combinedContent);
 }
Esempio n. 11
0
 public string Process(string includedVirtualPath, string input)
 {
     if (BundleTable.EnableOptimizations)
     {
         var compressor = new JavaScriptCompressor
         {
             Encoding = Encoding.UTF8,
             ObfuscateJavascript = obfuscate,
             PreserveAllSemicolons = true,
         };
         input = compressor.Compress(input);
     }
     return input;
 }
Esempio n. 12
0
 private static string CompressJS(string content)
 {
     string results = "";
     try
     {
         var jsCompressor = new JavaScriptCompressor();
         results = jsCompressor.Compress(content);
     }
     catch (Exception ex)
     {
         WriteLog(ex);
     }
     return results;
 }
Esempio n. 13
0
 public CompileResults Compile(string inPath, string outPath)
 {
     using (StreamReader sr = new StreamReader(inPath))
     {
         string content = sr.ReadToEnd();
         JavaScriptCompressor x = new JavaScriptCompressor();
         string output = x.Compress(content);
         using (StreamWriter sw = new StreamWriter(outPath))
         {
             sw.Write(output);
         }
     }
     return null;
 }
Esempio n. 14
0
 public string Process(string includedVirtualPath, string input)
 {
     if (BundleTable.EnableOptimizations)
     {
         var compressor = new JavaScriptCompressor
         {
             CompressionType = CompressionType.Standard,
             Encoding = Encoding.UTF8,
             ObfuscateJavascript = obfuscate,
         };
         input = compressor.Compress(input);
     }
     return input;
 }
 protected override byte[] GenerateCode(string inputFileContent)
 {
     string output = string.Empty;
     try
     {
         var JsCompressor = new JavaScriptCompressor();
         output = JsCompressor.Compress(inputFileContent);
     }
     catch (Exception e)
     {
         throw new COMException(string.Format("{0}: {1}\n{2}",
                 e.GetType().Name, e.Message, e.StackTrace));
     }
     return Encoding.ASCII.GetBytes(output);
 }
Esempio n. 16
0
        public static MvcHtmlString MinifyInlineScript(this HtmlHelper html, Func <object, object> markup)
        {
            string notMinifiedJs = (markup.Invoke(html.ViewContext)?.ToString() ?? "").TrimStart("<script>")
                                   .TrimStart("<text>").TrimEnd("</script>").TrimEnd("</text>");

            var minifier = new Yahoo.Yui.Compressor.JavaScriptCompressor()
            {
                CompressionType       = CompressionType.Standard,
                Encoding              = Encoding.UTF8,
                ObfuscateJavascript   = true,
                PreserveAllSemicolons = true,
            };
            var minifiedJs = minifier.Compress(notMinifiedJs);

            return(new MvcHtmlString("<script type='text/javascript'>" + minifiedJs + "</script>"));
        }
Esempio n. 17
0
        /// <summary>
        /// Process the request
        /// </summary>
        public void ProcessRequest(HttpContext context)
        {
            DateTime mod = new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime ;
            var compressor = new JavaScriptCompressor() ;

            if (!ClientCache.HandleClientCache(context, resource, mod)) {
                StreamReader io = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(resource)) ;
                context.Response.ContentType = "text/javascript" ;
            #if DEBUG
                context.Response.Write(io.ReadToEnd()) ;
            #else
                context.Response.Write(compressor.Compress(io.ReadToEnd())) ;
            #endif
                io.Close() ;
            }
        }
 /// <summary>
 /// Filters the assets
 /// </summary>
 /// <param name="Assets">Assets to filter</param>
 /// <returns>The filtered assets</returns>
 public IList<IAsset> Filter(IList<IAsset> Assets)
 {
     if (Assets == null || Assets.Count == 0)
         return new List<IAsset>();
     if (Assets.FirstOrDefault().Type != AssetType.Javascript)
         return Assets;
     IEnumerable<IAsset> Processable = Assets.Where(x => !x.Minified);
     if (Processable.FirstOrDefault() == null)
         return Assets;
     var Minifier = new JavaScriptCompressor();
     foreach (IAsset Asset in Processable.Where(x => x != null))
     {
         try
         {
             Asset.Content = Minifier.Compress(Asset.Content);
             Asset.Minified = true;
         }
         catch { }
     }
     return Assets;
 }
Esempio n. 19
0
        static void Main(string[] args)
        {
            foreach (var arg in args)
                Console.WriteLine(arg);

            List<string> cssFiles = new List<string>();
            List<string> jsFiles = new List<string>();

            foreach (var file in args)
            {
                if (file.EndsWith(".css"))
                    cssFiles.Add(file);
                else if (file.EndsWith(".js"))
                    jsFiles.Add(file);
            }

            var cssCompressor = new CssCompressor();
            var jsCompressor = new JavaScriptCompressor();

            foreach(var jsFile in jsFiles){
                var compress = jsCompressor.Compress(File.ReadAllText(jsFile));
                var newPath = jsFile.Replace(".js", "") + ".min.js";
                using (StreamWriter swr = new StreamWriter(newPath,false))
                {
                    swr.Write(compress);
                    swr.Close();
                }
            }

            foreach (var cssFile in cssFiles)
            {
                var compress = cssCompressor.Compress(File.ReadAllText(cssFile));
                var newPath = cssFile.Replace(".css", "") + ".min.css";
                using (StreamWriter swr = new StreamWriter(newPath, false))
                {
                    swr.Write(compress);
                    swr.Close();
                }
            }
        }
 private static string CompressJs(string path)
 {
     var rawjs = File.ReadAllText(path);
     var jsCompressor = new JavaScriptCompressor();
     var compressed = jsCompressor.Compress(rawjs);
     return compressed;
 }
        private string TransformContent(BundleResource bundleResource, HttpContext context)
        {
            var bundleType = bundleResource.Type;
            var content = bundleResource.Content;
            var serverpath = bundleResource.ServerPath;

            try
            {
                if (bundleType == BundleResourceType.EmbeddedScript || bundleType == BundleResourceType.ScriptFile)
                {
                    var compressor = new JavaScriptCompressor
                    {
                        CompressionType = CompressionType.Standard,
                        Encoding = Encoding.UTF8,
                        ObfuscateJavascript = bundleResource.ObfuscateJs
                    };


                    //Minimize
                    var contentOut = compressor.Compress(content.Trim()) + ";";

                    //Return deffered execution
                    if (ClientSettings.IsJavascriptDefferingEnabled)
                    {
                        return string.Format(ClientSettings.JavascriptDefferingScript,
                                      JsonConvert.SerializeObject(contentOut));
                    }
                    return contentOut;
                }
                if (!string.IsNullOrEmpty(serverpath))
                {
                    string directoryName = Path.GetDirectoryName(serverpath);
                    if (directoryName != null)
                        serverpath = directoryName.Replace('\\', '/');
                }
                if (bundleType == BundleResourceType.EmbeddedStyle || bundleType == BundleResourceType.StyleFile)
                {
                    var compressor = new CssCompressor
                                         {
                                             CompressionType = CompressionType.Standard,
                                             RemoveComments = true
                                         };

                    return ReplaceUrls(compressor.Compress(content), serverpath, context);
                }
                if (bundleType == BundleResourceType.LessFile)
                {
                    DotlessConfiguration cfg = DotlessConfiguration.GetDefaultWeb();
                    cfg.Web = true;
                    cfg.MinifyOutput = true;
                    cfg.MapPathsToWeb = true;
                    cfg.CacheEnabled = false;

                    //Prefilter
                    content = ReplaceImportRegex.Replace(content, match => ReplaceImports(match, serverpath));
                    string processed = ReplaceUrls(LessWeb.Parse(content, cfg), serverpath, context);
                    return processed;
                }
            }
            catch (EcmaScript.NET.EcmaScriptException e)
            {
                _log.ErrorFormat("EcmaScriptException: {0} in {1} at {2} ({3}, {4}) at ", e.Message, serverpath, e.LineSource, e.LineNumber, e.ColumnNumber, e.ScriptStackTrace);
            }
            catch (Exception e)
            {
                _log.Error(e);
            }
            return content;
        }
Esempio n. 22
0
        string YUI_JS(string filesource, ConfigSettings.YUICompressionSettings.Js JsSettings)
        {
            try
            {
                var jscompressor = new JavaScriptCompressor();
                jscompressor.CompressionType = JsSettings.CompressionType;
                jscompressor.DisableOptimizations = JsSettings.DisableOptimizations;
                jscompressor.Encoding = JsSettings.Encoding;
                jscompressor.IgnoreEval = JsSettings.IgnoreEval;
                jscompressor.LineBreakPosition = JsSettings.LineBreakPosition;
                jscompressor.ObfuscateJavascript = JsSettings.ObfuscateJavascript;
                jscompressor.PreserveAllSemicolons = JsSettings.PreserveAllSemicolons;
                jscompressor.ThreadCulture = JsSettings.ThreadCulture;

                return jscompressor.Compress(filesource);
            }
            catch(Exception ex)
            {
                var msg = ex.Message;
                return filesource;
            }
        }
Esempio n. 23
0
        internal static string JS(string strContent)
        {
            var jsCom = new JavaScriptCompressor();

            return jsCom.Compress(strContent);
        }
Esempio n. 24
0
        public bool Minimize()
        {
            if (String.IsNullOrEmpty(Input)) {
                throw new Exception("Input must be specified.:");
            }
            if (CompressorType == 0)
            {
                throw new Exception("No compressor type specified.");
            }
            string compressedYui = String.Empty;
            string compressedPacker = String.Empty;
            string header = String.Empty;
            string javascript = Input;
            //string javascript = File.ReadAllText(path);
            if (KeepHeader)
            {
                int pos = javascript.IndexOf("/*");
                int endPos = -1;
                string leadin = String.Empty;
                if (pos >= 0)
                {
                    leadin = javascript.Substring(0, pos);
                    if (leadin.Trim() == string.Empty)
                    {
                        endPos = javascript.IndexOf("*/", pos + 1);
                        header = javascript.Substring(pos, endPos + 2) + Environment.NewLine;
                        javascript = javascript.Substring(endPos + 2);

                    }
                }
            }

            if (CompressorType == CompressorType.yui || CompressorType == CompressorType.best)
            {

                var reporter = new LinterECMAErrorReporter();
                Yahoo.Yui.Compressor.JavaScriptCompressor compressor;
                compressor = new JavaScriptCompressor(javascript, true, Encoding.UTF8,
                System.Globalization.CultureInfo.CurrentCulture,
                    true,
                    reporter);
                compressedYui = compressor.Compress(true, true, false, 80);
            }
            if (CompressorType == CompressorType.packer || CompressorType == CompressorType.best)
            {
                JavascriptPacker jsPacker = new JavascriptPacker(JavascriptPacker.PackerEncoding.None, false, false);
                compressedPacker = jsPacker.Pack(javascript);
            }
            CompressorType finalPacker = CompressorType != CompressorType.best ? CompressorType :
                    (compressedYui.Length < compressedPacker.Length ? CompressorType.yui : CompressorType.packer);

            Output = header + (finalPacker == CompressorType.yui ? compressedYui : compressedPacker);

            Statistics = finalPacker.ToString() + ": " + javascript.Length + "/" + Output.Length + ", " + Math.Round(100 * ((decimal)Output.Length / (decimal)javascript.Length), 0) + "%";
            return Success;
        }
Esempio n. 25
0
 /// <summary>
 ///     Minimizes the js code.
 /// </summary>
 /// <param name="inputJsFile">The input js file.</param>
 /// <returns></returns>
 public string MinimizeJsCode(string inputJsFile)
 {
     var jsContents = File.ReadAllText(this.RapContext.MapPath(inputJsFile));
     var jsCompressor = new JavaScriptCompressor();
     return jsCompressor.Compress(jsContents);
 }
Esempio n. 26
0
        static void Main(string[] args)
        {
            // Loads the build list
            ReadBuildList();

            // Collect all files in this directory
            var dir    = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var target = Path.Combine(dir, "UltimateLib.js");

            if (File.Exists(target))
            {
                File.Delete(target);
            }

            var files = new List <string>();


            foreach (var item in BuildList.Core.Items)
            {
                files.Add(Path.Combine(dir, "core\\" + item + ".js"));
            }

            foreach (var item in BuildList.Libraries3rd.Items)
            {
                files.Add(Path.Combine(dir, "3rd\\" + item + ".js"));
            }

            foreach (var item in BuildList.Libraries.Items)
            {
                files.Add(Path.Combine(dir, "libs\\" + item + ".js"));
            }

            files.Add(Path.Combine(dir, "GDT.Hook.js"));


            if (BuildList.Optimizations.Enabled)
            {
                var yuc = new Yahoo.Yui.Compressor.JavaScriptCompressor();
                var sb  = new StringBuilder();

                yuc.DisableOptimizations  = BuildList.Optimizations.DisableOptimizations;
                yuc.LoggingType           = LoggingType.None;
                yuc.LineBreakPosition     = 1;
                yuc.CompressionType       = BuildList.Optimizations.Compression? CompressionType.Standard : CompressionType.None;
                yuc.ObfuscateJavascript   = BuildList.Optimizations.Obfuscation;
                yuc.PreserveAllSemicolons = BuildList.Optimizations.PreserveAllSemicolons;
                yuc.IgnoreEval            = BuildList.Optimizations.IgnoreEval;

                try
                {
                    foreach (var file in files)
                    {
                        if (!File.Exists(file))
                        {
                            continue;
                        }


                        sb.Append(yuc.Compress(File.ReadAllText(file)));
                    }



                    using (var output = File.CreateText(target))
                    {
                        output.Write(sb.ToString());
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error " + ex.Message);
                }
            }
            else
            {
                const int chunkSize = 2 * 1024; // 2KB
                using (var output = File.Create(target))
                {
                    foreach (var file in files)
                    {
                        if (!File.Exists(file))
                        {
                            continue;
                        }
                        using (var input = File.OpenRead(file))
                        {
                            var buffer = new byte[chunkSize];
                            int bytesRead;
                            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                output.Write(buffer, 0, bytesRead);
                            }
                        }
                    }
                }
            }
        }
Esempio n. 27
0
        public bool YUITest(string javascript)
        {
            Clear();
            Yahoo.Yui.Compressor.JavaScriptCompressor compressor;

            try
            {
                compressor = new JavaScriptCompressor(javascript, true, Encoding.UTF8,
                System.Globalization.CultureInfo.CurrentCulture,
                AllowEval, Reporter);

                string compressed = compressor.Compress(true,true,false,80);
            }
            catch
            {
            }
            return Reporter.Errors.Count==0;
        }
        public static string Compact(string virtalPath, string source, List<ParseException> errors)
        {
            BuildErrorReporter errorReporter = null;
            if (errors != null)
            {
                errorReporter = new BuildErrorReporter(virtalPath, errors);
            }

            ScriptCompactionSection config = ScriptCompactionSection.GetSettings();

            StringBuilder builder = new StringBuilder(source.Length);
            try
            {
                JavaScriptCompressor compressor = new JavaScriptCompressor(
                    source,
                    config.Verbose,						// verbose logging
                    Encoding.UTF8,
                    CultureInfo.InvariantCulture,
                    config.IgnoreEval,					// ignore eval
                    errorReporter);

                string compacted = compressor.Compress(
                    config.Obfuscate,					// obfuscate
                    config.PreserveSemicolons,			// preserve unneccessary semicolons
                    config.DisableMicroOptimizations,	// disable micro-optimizations
                    config.WordWrapWidth);				// word wrap width

                builder.Append(compacted);
            }
            catch (EcmaScriptRuntimeException ex)
            {
                if (errors.Count > 0 && String.IsNullOrEmpty(ex.SourceName))
                {
                    // EcmaScript.NET provides an extra error which is a summary count of other errors
                    errors.Add(new ParseWarning(ex.Message, virtalPath, ex.LineNumber, ex.ColumnNumber, ex));
                }
                else
                {
                    errors.Add(new ParseError(ex.Message, ex.SourceName, ex.LineNumber, ex.ColumnNumber, ex));
                }
            }
            catch (Exception ex)
            {
                errors.Add(new ParseError(ex.Message, virtalPath, -1, -1, ex));
            }

            return builder.ToString();
        }
Esempio n. 29
0
        protected bool compressYUI(string input, out string output)
        {
            bool success;
            try
            {
                var reporter = new LinterECMAErrorReporter();
                Yahoo.Yui.Compressor.JavaScriptCompressor compressor;
                compressor = new JavaScriptCompressor(input, true, Encoding.UTF8,
                System.Globalization.CultureInfo.CurrentCulture,
                    AllowEval,
                    reporter);
                output = compressor.Compress(true, true,false, 80);
                success = Reporter.Errors.Count == 0;
            }
            catch
            {
                output = "";
                success = false;
            }

            return success;
        }
        public static string Compress(string javaScript,
                                      bool isVerboseLogging,
                                      bool isObfuscateJavascript,
                                      bool preserveAllSemicolons,
                                      bool disableOptimizations,
                                      int lineBreakPosition,
                                      Encoding encoding,
                                      CultureInfo threadCulture,
                                      bool isEvalIgnored)
        {
            if (string.IsNullOrEmpty(javaScript))
            {
                throw new ArgumentNullException("javaScript");
            }

            var javaScriptCompressor = new JavaScriptCompressor(javaScript,
                                                                isVerboseLogging,
                                                                encoding,
                                                                threadCulture,
                                                                isEvalIgnored,
                                                                null);

            return javaScriptCompressor.Compress(isObfuscateJavascript,
                                                 preserveAllSemicolons,
                                                 disableOptimizations,
                                                 lineBreakPosition);
        }
Esempio n. 31
0
 public string Compress(string contents)
 {
     var jsCompressor = new JavaScriptCompressor { Encoding = Encoding.UTF8, ThreadCulture = CultureInfo.InvariantCulture };
     return jsCompressor.Compress(contents);
 }
Esempio n. 32
0
        /// <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;
        }