Beispiel #1
0
        /// <summary>
        /// 更新静态文件内容
        /// </summary>
        /// <param name="html"></param>
        /// <param name="adpage"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        private Tuple <string, string> ReplaceHtml(string html, string style, AdPageInfoVO adpage, ArticleInfoVO info, string stylefilename)
        {
            string        nhtml = html;
            StringBuilder sb    = new StringBuilder();

            sb.Append(style);

            //随机插入部分样式
            string rcss = Guid.NewGuid().ToString();

            sb.AppendLine(string.Format(".{0}", rcss));
            sb.Append("{color:red;padding:0px;}");
            string nstyle = sb.ToString();

            //替换CSS名称
            var csslist = GetCssList();

            foreach (var item in csslist)
            {
                nhtml.Replace(item.Key, item.Value);
                nstyle.Replace(item.Key, item.Value);
            }

            Yahoo.Yui.Compressor.CssCompressor css = new Yahoo.Yui.Compressor.CssCompressor();
            string nstylemin = css.Compress(nstyle);

            nhtml = nhtml.Replace("$AdPagetId$", adpage.Id.ToString())
                    .Replace("$ArticleDetail$", DN.Framework.Utility.HtmlHelper.DecodeHtml(info.Content))
                    .Replace("$UserCode$", DN.Framework.Utility.HtmlHelper.DecodeHtml(adpage.StaticContent))
                    .Replace("$Title$", info.Title)
                    .Replace("$version$", DateTime.Now.ToString("yyyyMMddhhmmss"))
                    .Replace("href=\"style.css\"", string.Format("href=\"{0}\"", stylefilename));

            return(new Tuple <string, string>(nhtml, nstylemin));
        }
Beispiel #2
0
        private string CompressedCSS(string InString)
        {
            var compressor = new Yahoo.Yui.Compressor.CssCompressor
            {
                RemoveComments = true
            };

            // Read full script file
            string _Decrypted = new IntellidateR1.EncryptDecrypt().Decrypt(InString.Split('-')[0]);

            string[] _CSSPath = _Decrypted.Split(',');

            string _CssContent = "";
            string _RootFolder = Server.MapPath("~").ToString();

            foreach (var EachCss in _CSSPath)
            {
                _CssContent = _CssContent + "\n" + File.ReadAllText(_RootFolder + "\\" + EachCss + ".css");
            }

            if (ConfigurationManager.AppSettings["StaticDebug"].ToString() == "Y")
            {
                return(_CssContent);
            }

            string _CompleteCss = _CssContent;

            return(compressor.Compress(_CompleteCss));
        }
 public static void CompressFile(string file, string outputDirectory)
 {
     string name = Path.GetFileName(file);
     if (name.Contains(".min."))
         return;
     Console.WriteLine("Compressing file: " + name);
     var cssCompressor = new Yahoo.Yui.Compressor.CssCompressor();
     using (var sw = new StreamWriter(outputDirectory + name.Replace(".css", ".min.css")))
     using (var sr = new StreamReader(file))
         sw.Write(cssCompressor.Compress(sr.ReadToEnd()));
 }
Beispiel #4
0
        private BundledMicroApplicationPart Bundle(JObject part)
        {
            string[] part_css_files    = (from f in part["css_files"] select f).Select((j) => j.ToString()).ToArray();
            string[] part_script_files = (from f in part["scripts"] select f).Select((j) => j.ToString()).ToArray();

            // create the instance that will store the bundled app
            BundledMicroApplicationPart app = new BundledMicroApplicationPart();

            if (part["package_name"] != null)
            {
                app.Name = part["package_name"].ToString();
            }
            if (part["frame_id"] != null)
            {
                app.Name = part["frame_id"].ToString();
            }

            if (part["to"] != null)
            {
                app.To = part["to"].ToString();
            }

            // compress the CSS
            Yahoo.Yui.Compressor.CssCompressor css_compressor = new Yahoo.Yui.Compressor.CssCompressor();

            List <string> css_files = new List <string>();
            List <string> js_files  = new List <string>();

            foreach (string script in part_script_files)
            {
                js_files.Add(File.ReadAllText(base_directory + script));
            }

            foreach (string stylesheet in part_css_files)
            {
                css_files.Add(css_compressor.Compress(File.ReadAllText(base_directory + stylesheet)));
            }

            js_files  = js_files.Select((f) => PackerUtilities.StringToBase64Encoded(f)).ToList();
            css_files = css_files.Select((f) => PackerUtilities.StringToBase64Encoded(f)).ToList();

            // add the bundled app
            app.Scripts = js_files.ToArray();
            app.CSS     = css_files.ToArray();

            return(app);
        }
Beispiel #5
0
        public MinificationResult Get(JObject jsonData)
        {
            dynamic json = jsonData;
            string source = json.source;

            if (string.IsNullOrWhiteSpace(source))
            {
                throw new ArgumentNullException("source");
            }

            var result = new MinificationResult { OriginalSize = new FileSize(source.Length), };

            var ms = new SquishIt.Framework.Minifiers.CSS.MsMinifier();
            var msContent = ms.Minify(source).TrimStart('\n', ' ');

            var msResultType = new MinificationType(result, "MsCompressor")
                                   {
                                       MinifiedContent = msContent,
                                       MinifiedSize =
                                           new FileSize(msContent.Length),
                                   };

            var yui = new Yahoo.Yui.Compressor.CssCompressor
                          {
                              CompressionType =
                                  Yahoo.Yui.Compressor.CompressionType.Standard,
                              RemoveComments = true,
                          };
            var yuiContent = yui.Compress(source).TrimStart('\n', ' ');

            var yuiResultType = new MinificationType(result, "YuiCompressor")
                                    {
                                        MinifiedContent = yuiContent,
                                        MinifiedSize =
                                            new FileSize(yuiContent.Length),
                                    };

            result.Types = new[] { msResultType, yuiResultType, };
            return result;
        }
Beispiel #6
0
        internal void CompressCSS()
        {
            if (string.IsNullOrEmpty(this.IncludeCSSFile) || string.IsNullOrEmpty(this.OutputCSSFile))
            {
                LogWarning("CSS files to include or CSS output is empty.");
                return;
            }
            LogInformation("Compressing CSS files in {0} with {1} compression level to {2}", this.IncludeCSSFile, this.CSSCompressionType, this.OutputCSSFile);
            var           compressor = new Yahoo.Yui.Compressor.CssCompressor();
            StringBuilder finalResult = null;
            int           originalContentLength = 0, inputFiles = 0, outputFiles = 0, outputLength = 0;

            compressor.CompressionType   = (Yahoo.Yui.Compressor.CompressionType)Enum.Parse(typeof(Yahoo.Yui.Compressor.CompressionType), this.CSSCompressionType, true);
            compressor.LineBreakPosition = string.IsNullOrEmpty(this.CSSLineBreakPosition) ? -1 : Convert.ToInt32(this.CSSLineBreakPosition);
            compressor.RemoveComments    = this.RemoveCSSComments;
            var files = FilesToCompress(this.IncludeCSSFile, this.ExcludeCSSPattern, this.CSSRecursive);

            foreach (var d in files)
            {
                foreach (var c in d.Value)
                {
                    if (Verbose)
                    {
                        LogInformation("CompressCSS working on: {0}", c);
                    }
                    if (File.Exists(c))
                    {
                        var originalContent = File.ReadAllText(c);
                        originalContentLength += originalContent.Length;
                        inputFiles++;
                        if (string.IsNullOrEmpty(originalContent))
                        {
                            LogInformation("File {0} is empty.", c);
                        }
                        else
                        {
                            var compressedContent = compressor.Compress(originalContent);
                            if (!string.IsNullOrEmpty(compressedContent))
                            {
                                if (null == finalResult)
                                {
                                    finalResult = new StringBuilder();
                                }
                                finalResult.Append(compressedContent);
                            }
                        }
                        if (this.CSSDeleteOriginal)
                        {
                            File.Delete(c);
                        }
                        if (this.CompressCSSInPlace && (null != finalResult) && (finalResult.Length > 0))
                        {
                            File.WriteAllText(c, finalResult.ToString());
                            outputLength += finalResult.Length;
                            outputFiles++;
                            finalResult = null;
                        }
                    }
                }
                if (this.PreserveCSSSubdirectories && (null != finalResult) && (finalResult.Length > 0))
                {
                    var currentDir = Path.GetDirectoryName(ResolveDirectory(d.Key));
                    if (null != finalResult && finalResult.Length > 0)
                    {
                        File.WriteAllText(Path.Combine(currentDir, this.OutputCSSFile), finalResult.ToString());
                        outputLength += finalResult.Length;
                        outputFiles++;
                    }
                    finalResult = null;
                }
            }
            if (null != finalResult && finalResult.Length > 0)
            {
                File.WriteAllText(ResolveDirectory(this.OutputCSSFile), finalResult.ToString());
                outputLength += finalResult.Length;
                outputFiles++;
            }
            LogInformation("Completed compressing {0} CSS files into {1} files. Original size: {2}, compressed size: {3}", inputFiles, outputFiles, originalContentLength, outputLength);
        }
        private string Merge(IScriptGenerationInfo info, IEnumerable<IScriptInfo> scripts)
        {
            var scriptbody = new StringBuilder();
            scriptbody.AppendFormat("/* Generated: {0} */\n", DateTime.Now.ToString());

            var scriptsToRender = scripts;
            var minify = bool.Parse(ConfigurationManager.AppSettings["SJ.Compress"]);

            foreach (var script in scriptsToRender)
            {
                if (!script.IsInline && !string.IsNullOrWhiteSpace(script.LocalPath))
                {
                    using (var fs = new FileStream(script.LocalPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        using (var file = new StreamReader(fs))
                        {
                            var fileContent = file.ReadToEnd();

                            if (info.Type == ScriptType.Stylesheet)
                            {
                                var fromUri = new Uri(HttpContext.Current.Server.MapPath("~/"));
                                var toUri = new Uri(new FileInfo(script.LocalPath).DirectoryName);

                                string imageUrlRoot = (HttpContext.Current.Request.ApplicationPath.EndsWith("/")) ? HttpContext.Current.Request.ApplicationPath : HttpContext.Current.Request.ApplicationPath + "/";
                                imageUrlRoot += fromUri.MakeRelativeUri(toUri).ToString();
                                fileContent = fileContent.Replace("url(\"images", "url(\"" + imageUrlRoot + "/images");
                            }

                            if (!minify)
                            {
                                scriptbody.AppendLine(String.Format("/* {0} */\n", script.Url));
                            }

                            scriptbody.AppendLine(fileContent);
                            file.Close();
                        }
                    }
                }
                else if (script.IsInline)
                {
                    scriptbody.AppendLine(String.Format("/* {0} */\n", script.UniqueKey));
                    scriptbody.AppendLine(script.Source);
                }
            }

            string scriptOutput = scriptbody.ToString();

            if (minify)
            {
                switch (info.Type)
                {
                    case ScriptType.JavaScript:
                        var jsCompressor = new Yahoo.Yui.Compressor.JavaScriptCompressor();
                        scriptOutput = jsCompressor.Compress(scriptOutput);
                        break;
                    case ScriptType.Stylesheet:
                        var cssCompressor = new Yahoo.Yui.Compressor.CssCompressor();
                        scriptOutput = cssCompressor.Compress(scriptOutput);
                        break;
                }
            }

            return scriptOutput;
        }
Beispiel #8
0
        public virtual string GenerateCssFiles(UrlHelper urlHelper, ResourceLocation location, bool?bundleFiles = null)
        {
            if ((!_cssParts.ContainsKey(location) || _cssParts[location] == null) &&
                (!_inlineCss.ContainsKey(location) || _inlineCss[location] == null))
            {
                return("");
            }

            if (!_cssParts.Any() && !_inlineCss.Any())
            {
                return("");
            }

            if (!bundleFiles.HasValue)
            {
                //use setting if no value is specified
                bundleFiles = _siteSettings.EnableCssBundling && BundleTable.EnableOptimizations;
            }

            if (bundleFiles.Value)
            {
                var partsToBundle           = new List <CssReferenceMeta>();
                var inlinePartsToBundle     = new List <CssReferenceMeta>();
                var partsToDontBundle       = new List <CssReferenceMeta>();
                var inlinePartsToDontBundle = new List <CssReferenceMeta>();

                if (_cssParts.ContainsKey(location))
                {
                    partsToBundle.AddRange(_cssParts[location]
                                           .Where(x => !x.ExcludeFromBundle)
                                           .Distinct());
                    partsToDontBundle.AddRange(_cssParts[location]
                                               .Where(x => x.ExcludeFromBundle)
                                               .Distinct());
                }

                if (_inlineCss.ContainsKey(location))
                {
                    inlinePartsToBundle.AddRange(_inlineCss[location]
                                                 .Where(x => !x.ExcludeFromBundle)
                                                 .Distinct());
                    inlinePartsToDontBundle.AddRange(_inlineCss[location]
                                                     .Where(x => x.ExcludeFromBundle)
                                                     .Distinct());
                }


                var result    = new StringBuilder();
                var allStyles = new List <string>();
                allStyles.AddRange(partsToBundle.Select(x => x.Part));
                allStyles.AddRange(inlinePartsToBundle.Select(x => x.Part));
                if (allStyles.Any())
                {
                    //IMPORTANT: Do not use CSS bundling in virtual directories
                    var    hash = ComputeHash(allStyles.ToArray());
                    string bundleVirtualPath = "~/bundles/styles/" + hash;

                    //create bundle
                    lock (SLock)
                    {
                        var bundleFor = BundleTable.Bundles.GetBundleFor(bundleVirtualPath);
                        if (bundleFor == null)
                        {
                            var bundle = new StyleBundle(bundleVirtualPath);

                            bundle.Include(partsToBundle.Select(x => x.Part).ToArray());

                            if (inlinePartsToBundle.Any())
                            {
                                var inlineStyleFilePath = HttpContext.Current.Server.MapPath($"~/App_Data/{hash}.css");
                                File.WriteAllText(inlineStyleFilePath,
                                                  string.Join(Environment.NewLine, inlinePartsToBundle.Select(x => x.Part)));
                                bundle.Include($"~/App_Data/{hash}.css");
                            }

                            var styleTransformer = new StyleTransformer(new YuiCssMinifier(new YuiSettings()
                            {
                                CssMinifier =
                                {
                                    CompressionType = CompressionType.Standard,
                                    RemoveComments  = true
                                }
                            }))
                            {
                                EnableTracing = false,
                                CombineFilesBeforeMinification = false,
                                UsePreMinifiedFiles            = true
                            };
                            BundleResolver.Current = new CustomBundleResolver();
                            bundle.Builder         = new NullBuilder();
                            bundle.Transforms.Clear();
                            bundle.Transforms.Add(styleTransformer);
                            bundle.Orderer = new NullOrderer();

                            BundleTable.Bundles.Add(bundle);
                        }
                    }

                    //parts to bundle
                    result.AppendLine(Styles.Render(bundleVirtualPath).ToString());
                }

                //parts to do not bundle
                foreach (var item in partsToDontBundle)
                {
                    result.AppendFormat("<link href=\"{0}\" rel=\"stylesheet\" type=\"{1}\" />", urlHelper.Content(item.Part), "text/css");
                    result.Append(Environment.NewLine);
                }

                //inline styles to do not bundle
                if (inlinePartsToDontBundle.Any())
                {
                    string style = "";
                    foreach (var item in inlinePartsToDontBundle.Select(x => new { x.Part }).Distinct())
                    {
                        style += urlHelper.Content(item.Part);
                        style += Environment.NewLine;
                    }

                    if (_siteSettings.EnableInlineCssMinification)
                    {
                        var minifier = new Yahoo.Yui.Compressor.CssCompressor()
                        {
                            RemoveComments = true
                        };
                        minifier.CompressionType = Yahoo.Yui.Compressor.CompressionType.Standard;
                        style = minifier.Compress(style);
                    }

                    result.Append("<style>");
                    result.Append(Environment.NewLine);
                    result.Append(style);
                    result.Append(Environment.NewLine);
                    result.Append("</style>");
                }

                return(result.ToString());
            }
            else
            {
                //bundling is disabled
                var result = new StringBuilder();
                if (_cssParts.ContainsKey(location))
                {
                    foreach (var path in _cssParts[location].Select(x => x.Part).Distinct())
                    {
                        result.AppendFormat("<link href=\"{0}\" rel=\"stylesheet\" type=\"{1}\" />", urlHelper.Content(path), "text/css");
                        result.AppendLine();
                    }
                }

                //inline styles to do not bundle
                if (_inlineCss.ContainsKey(location))
                {
                    string style = "";
                    foreach (var item in _inlineCss[location].Select(x => new { x.Part }).Distinct())
                    {
                        style += urlHelper.Content(item.Part);
                        style += Environment.NewLine;
                    }

                    if (_siteSettings.EnableInlineCssMinification)
                    {
                        var minifier = new Yahoo.Yui.Compressor.CssCompressor()
                        {
                            RemoveComments = true
                        };
                        minifier.CompressionType = Yahoo.Yui.Compressor.CompressionType.Standard;
                        style = minifier.Compress(style);
                    }

                    result.Append("<style>");
                    result.Append(Environment.NewLine);
                    result.Append(style);
                    result.Append(Environment.NewLine);
                    result.Append("</style>");
                }

                return(result.ToString());
            }
        }
Beispiel #9
0
        private BundledMicroApplicationPart Bundle(JObject part)
        {
            string[] part_css_files = (from f in part["css_files"] select f).Select((j) => j.ToString()).ToArray();
            string[] part_script_files = (from f in part["scripts"] select f).Select((j) => j.ToString()).ToArray();

            // create the instance that will store the bundled app
            BundledMicroApplicationPart app = new BundledMicroApplicationPart();

            if (part["package_name"] != null) app.Name = part["package_name"].ToString();
            if (part["frame_id"] != null) app.Name = part["frame_id"].ToString();

            if (part["to"] != null) app.To = part["to"].ToString();

            // compress the CSS
            Yahoo.Yui.Compressor.CssCompressor css_compressor = new Yahoo.Yui.Compressor.CssCompressor();

            List<string> css_files = new List<string>();
            List<string> js_files = new List<string>();

            foreach (string script in part_script_files)
            {
                js_files.Add(File.ReadAllText(base_directory + script));
            }

            foreach (string stylesheet in part_css_files)
            {
                css_files.Add(css_compressor.Compress(File.ReadAllText(base_directory + stylesheet)));
            }

            js_files = js_files.Select((f) => PackerUtilities.StringToBase64Encoded(f)).ToList();
            css_files = css_files.Select((f) => PackerUtilities.StringToBase64Encoded(f)).ToList();

            // add the bundled app
            app.Scripts = js_files.ToArray();
            app.CSS = css_files.ToArray();

            return app;
        }
Beispiel #10
0
        /// <summary><![CDATA[
        /// Compile a SCSS file or files into CSS.
        /// ]]></summary>
        /// <param name="scssInputPath">Web path to the scss input file (e.g. "/scss/application.scss").</param>
        /// <param name="outputPath">Web path to the CSS output file (e.g. "/stylesheets/application.css").</param>
        /// <param name="debugMode">Set to true for expanded output with source maps, false for compressed production CSS only</param>
        /// <param name="force">Force a rebuild</param>
        /// <returns>True if successful, false if an error occurred</returns>
        public static void BuildScss(this string scssInputPath, string outputPath, bool debugMode = false, bool force = false)
        {
            var process = force;

            Debug.WriteLine("");
            Debug.WriteLine("LibSass result (" + (debugMode ? "debug" : "release") + " mode):");
            Debug.WriteLine("------------------------------");

            #region Determine if at least one file has been modified

            if (force)
            {
                Debug.WriteLine("FORCED REBUILD MODE");
            }

            else
            {
                if (!FileExists(outputPath))
                {
                    Debug.WriteLine("CSS file is missing, will recompile...");
                    process = true;
                }

                else
                {
                    if (debugMode && !FileExists(outputPath + ".map"))
                    {
                        Debug.WriteLine("Debug mode and CSS Map file is missing, will recompile...");
                        process = true;
                    }

                    else
                    {
                        if (HttpContext.Current.Application.KeyExists(ConvertFilePathToKey(scssInputPath)))
                        {
                            var files = (ArrayList)HttpContext.Current.Application[ConvertFilePathToKey(scssInputPath)];

                            if (files.Count > 0)
                            {
                                foreach (string file in files)
                                {
                                    var segments = file.Split('|');

                                    Debug.Write(GetFilename(segments[0]) + "... ");

                                    if (segments.Length == 2)
                                    {
                                        FileInfo fileInfo     = new FileInfo(MapPath(segments[0]));
                                        DateTime lastModified = fileInfo.LastWriteTime;

                                        if (segments[1] != lastModified.DateFormat(DateFormats.Utc))
                                        {
                                            process = true;
                                            Debug.WriteLine(" modified, will recompile...");
                                            break;
                                        }

                                        else
                                        {
                                            Debug.WriteLine(" unchanged");
                                        }
                                    }

                                    else
                                    {
                                        process = true;
                                        Debug.WriteLine(" has no previous timestamp, will recompile...");
                                        break;
                                    }
                                }
                            }

                            else
                            {
                                process = true;
                                Debug.WriteLine("No files list is present, will recompile...");
                            }
                        }

                        else
                        {
                            process = true;
                            Debug.WriteLine("Cannot determine prior build timestamps, will recompile...");
                        }
                    }
                }
            }

            #endregion

            #region No state or file(s) modified, process...

            if (process == true)
            {
                var debugOptions = new LibSass.Compiler.Options.SassOptions
                {
                    OutputStyle              = LibSass.Compiler.Options.SassOutputStyle.Compact,
                    IncludeSourceComments    = false,
                    IncludeSourceMapContents = true,
                    OutputPath    = MapPath(outputPath),
                    SourceMapFile = outputPath + ".map",
                    InputPath     = MapPath(scssInputPath)
                };

                var releaseOptions = new LibSass.Compiler.Options.SassOptions
                {
                    OutputStyle              = LibSass.Compiler.Options.SassOutputStyle.Compact,
                    IncludeSourceComments    = false,
                    IncludeSourceMapContents = false,
                    OutputPath = MapPath(outputPath),
                    InputPath  = MapPath(scssInputPath)
                };

                try
                {
                    var cssResult = new LibSass.Compiler.SassResult();
                    var css       = "";
                    var map       = "";

                    if (debugMode == false)
                    {
                        var sassCompiler = new LibSass.Compiler.SassCompiler(releaseOptions);
                        var cssc         = new Yahoo.Yui.Compressor.CssCompressor();

                        cssResult = sassCompiler.Compile();
                        css       = cssc.Compress(cssResult.Output);
                    }

                    else
                    {
                        var sassCompiler = new LibSass.Compiler.SassCompiler(debugOptions);

                        cssResult = sassCompiler.Compile();
                        css       = cssResult.Output;
                        map       = cssResult.SourceMap;
                    }

                    if (outputPath.FileExists())
                    {
                        DeleteFiles(outputPath);
                        Debug.WriteLine("Deleted " + outputPath);
                    }

                    if ((outputPath + ".map").FileExists())
                    {
                        DeleteFiles(outputPath + ".map");
                        Debug.WriteLine("Deleted " + outputPath + ".map");
                    }

                    WriteFile(outputPath, css);
                    Debug.WriteLine("Generated " + outputPath);

                    if (debugMode == true)
                    {
                        WriteFile(outputPath + ".map", map);
                        Debug.WriteLine("Generated " + outputPath + ".map");
                    }

                    if (cssResult.IncludedFiles.Length > 0)
                    {
                        ArrayList fileList = new ArrayList();

                        foreach (var file in cssResult.IncludedFiles)
                        {
                            FileInfo fileInfo     = new FileInfo(MapPath(file));
                            DateTime lastModified = fileInfo.LastWriteTime;
                            var      item         = file + "|" + lastModified.DateFormat(DateFormats.Utc);

                            fileList.Add(item);
                            Debug.WriteLine(item);
                        }

                        HttpContext.Current.Application[ConvertFilePathToKey(scssInputPath)] = fileList;
                        Debug.WriteLine("Saved state for " + fileList.Count + " files");
                        Debug.WriteLine("");
                    }

                    else
                    {
                        Debug.WriteLine("No files to process, aborting");
                        Debug.WriteLine("");
                    }
                }

                catch (Exception e)
                {
                    Debug.WriteLine("LibSass error: " + e.Message);
                    Debug.WriteLine("");
                }
            }

            else
            {
                Debug.WriteLine("File(s) not modified, aborting");
                Debug.WriteLine("");
            }

            #endregion
        }