/// <summary>
    /// Minifies the specified CSS.
    /// </summary>
    /// <param name="resource">The CSS to minify.</param>
    /// <returns>The minified CSS, if minification was successful; otherwise, the original CSS with minification errors appended at the end.</returns>
    public string Minify(string resource)
    {
        if (String.IsNullOrEmpty(resource))
        {
            return resource;
        }

        var settings = new CssSettings
        {
            AllowEmbeddedAspNetBlocks = false
        };
        var minifier = new Minifier();
        try
        {
            resource = minifier.MinifyStyleSheet(resource, settings);
        }
        catch
        {
            var minificationErrors = String.Join(Environment.NewLine, minifier.Errors);
            resource = AppendMinificationErrors(resource, minificationErrors);

            if (mLogErrors)
            {
                CoreServices.EventLog.LogEvent("W", "Resource minification", "CssMinificationFailed", minificationErrors);
            }
        }

        return resource;
    }
Esempio n. 2
0
        /// <summary>
        /// Minifies the CSS stylesheet passes to it using the given settings, returning the minified results
        /// The Errors property will be set with any errors found during the minification process.
        /// </summary>
        /// <param name="source">CSS Source</param>
        /// <param name="settings">CSS minification settings</param>
        /// <returns>Minified StyleSheet</returns>
        public string MinifyStyleSheet(string source, CssSettings settings, CodeSettings codeSettings)
        {
            // initialize some values, including the error list (which shoudl start off empty)
            string minifiedResults = string.Empty;

            m_errors = new List <string>();

            // create the parser object and if we specified some settings,
            // use it to set the Parser's settings object
            CssParser parser = new CssParser();

            if (settings != null)
            {
                parser.Settings     = settings;
                parser.CodeSettings = codeSettings;
            }
            // hook the error handler
            parser.CssError += new EventHandler <CssErrorEventArgs>(OnCssError);

            // try parsing the source and return the results
            try
            {
                minifiedResults = parser.Parse(source);
            }
            catch (Exception e)
            {
                m_errors.Add(e.ToString());
            }
            return(minifiedResults);
        }
        public static string MinifyString(string extension, string content)
        {
            if (extension == ".css")
            {
                Minifier minifier = new Minifier();
                CssSettings settings = new CssSettings();
                settings.CommentMode = CssComment.None;

                if (WESettings.GetBoolean(WESettings.Keys.KeepImportantComments))
                {
                    settings.CommentMode = CssComment.Important;
                }

                return minifier.MinifyStyleSheet(content, settings);
            }
            else if (extension == ".js")
            {
                Minifier minifier = new Minifier();
                CodeSettings settings = new CodeSettings()
                {
                    EvalTreatment = EvalTreatment.MakeImmediateSafe,
                    PreserveImportantComments = WESettings.GetBoolean(WESettings.Keys.KeepImportantComments)
                };

                return minifier.MinifyJavaScript(content, settings);
            }

            return null;
        }
Esempio n. 4
0
        public CssSettings Clone()
        {
            // create the new settings object and copy all the properties from
            // the current settings
            var newSettings = new CssSettings()
            {
                AllowEmbeddedAspNetBlocks = this.AllowEmbeddedAspNetBlocks,
                ColorNames             = this.ColorNames,
                CommentMode            = this.CommentMode,
                IgnoreAllErrors        = this.IgnoreAllErrors,
                IgnoreErrorList        = this.IgnoreErrorList,
                IndentSize             = this.IndentSize,
                KillSwitch             = this.KillSwitch,
                LineBreakThreshold     = this.LineBreakThreshold,
                MinifyExpressions      = this.MinifyExpressions,
                OutputMode             = this.OutputMode,
                PreprocessorDefineList = this.PreprocessorDefineList,
                TermSemicolons         = this.TermSemicolons,
                CssType = this.CssType,
                BlocksStartOnSameLine = this.BlocksStartOnSameLine,
            };

            // add the resource strings (if any)
            newSettings.AddResourceStrings(this.ResourceStrings);

            return(newSettings);
        }
Esempio n. 5
0
        public string CompressContent(string content, bool removeComments)
        {
            var settings = new CssSettings();
            if(removeComments)
                settings.CommentMode = CssComment.None;

            var minifier = new Minifier();
            return minifier.MinifyStyleSheet(content, settings);
        }
        public string Compress(string content)
        {
            var cssSettings = new CssSettings();
            cssSettings.ColorNames = CssColor.Hex;
            cssSettings.ExpandOutput = false;

            var value = new Minifier().MinifyStyleSheet(content, cssSettings);
            return value;
        }
Esempio n. 7
0
 /// <inheritdoc cref="IResourceMinifier.Minify" />
 public string Minify(Settings settings, ResourceSet resourceSet, string combinedContent)
 {
     var outputMode = (OutputMode)OutputMode.ConvertToType(
         typeof(OutputMode), Microsoft.Ajax.Utilities.OutputMode.SingleLine);
     var codeSettings = new CssSettings()
     {
         OutputMode = outputMode,
         MinifyExpressions = MinifyExpressions == null ? true : MinifyExpressions.Value,
     };
     return new Minifier().MinifyStyleSheet(combinedContent, codeSettings);
 }
Esempio n. 8
0
        public override string MinifyString(string source)
        {
            Minifier minifier = new Minifier();

            var settings = new Microsoft.Ajax.Utilities.CssSettings
            {
                CommentMode = WESettings.Instance.General.KeepImportantComments ? CssComment.Hacks : CssComment.Important
            };

            return(minifier.MinifyStyleSheet(source, settings));
        }
Esempio n. 9
0
        public static string MinifyString(string extension, string content)
        {
            if (extension == ".css")
            {
                Minifier minifier = new Minifier();
                CssSettings settings = new CssSettings();
                settings.CommentMode = CssComment.None;

                if (WESettings.GetBoolean(WESettings.Keys.KeepImportantComments))
                {
                    settings.CommentMode = CssComment.Important;
                }

                return minifier.MinifyStyleSheet(content, settings);
            }
            else if (extension == ".js")
            {
                Minifier minifier = new Minifier();
                CodeSettings settings = new CodeSettings()
                {
                    EvalTreatment = EvalTreatment.MakeImmediateSafe,
                    PreserveImportantComments = WESettings.GetBoolean(WESettings.Keys.KeepImportantComments)
                };

                return minifier.MinifyJavaScript(content, settings);
            }
            else if (_htmlExt.Contains(extension.ToLowerInvariant())){
                var settings = new HtmlMinificationSettings
                {
                    RemoveOptionalEndTags = false,
                    AttributeQuotesRemovalMode = HtmlAttributeQuotesRemovalMode.KeepQuotes
                };

                var minifier = new HtmlMinifier(settings);
                MarkupMinificationResult result = minifier.Minify(content, generateStatistics: true);

                if (result.Errors.Count == 0)
                {
                    EditorExtensionsPackage.DTE.StatusBar.Text = "Web Essentials: HTML minified by " + result.Statistics.SavedInPercent + "%";
                    return result.MinifiedContent;
                }
                else
                {
                    EditorExtensionsPackage.DTE.StatusBar.Text = "Web Essentials: Cannot minify the current selection";
                    return content;
                }
            }

            return null;
        }
Esempio n. 10
0
        /// <summary>
        /// Minifies the CSS stylesheet passes to it using the given settings, returning the minified results
        /// The ErrorList property will be set with any errors found during the minification process.
        /// </summary>
        /// <param name="source">CSS Source</param>
        /// <param name="settings">CSS minification settings</param>
        /// <param name="scriptSettings">JS minification settings to use for expression-minification</param>
        /// <returns>Minified StyleSheet</returns>
        public string MinifyStyleSheet(string source, CssSettings settings, CodeSettings scriptSettings)
        {
            // initialize some values, including the error list (which shoudl start off empty)
            string minifiedResults = string.Empty;

            m_errorList = new List <ContextError>();

            // create the parser object and if we specified some settings,
            // use it to set the Parser's settings object
            CssParser parser = new CssParser();

            parser.FileContext = FileName;

            if (settings != null)
            {
                parser.Settings = settings;
            }

            if (scriptSettings != null)
            {
                parser.JSSettings = scriptSettings;
            }

            // hook the error handler
            parser.CssError += new EventHandler <CssErrorEventArgs>(OnCssError);

            // try parsing the source and return the results
            try
            {
                minifiedResults = parser.Parse(source);
            }
            catch (Exception e)
            {
                m_errorList.Add(new ContextError(
                                    true,
                                    0,
                                    null,
                                    null,
                                    null,
                                    this.FileName,
                                    0,
                                    0,
                                    0,
                                    0,
                                    e.Message));
                throw;
            }
            return(minifiedResults);
        }
Esempio n. 11
0
    private static void Minify(HttpResponse response, string file, string ext)
    {
        string content = File.ReadAllText(file);
        Minifier minifier = new Minifier();

        if (ext == ".css")
        {
            CssSettings settings = new CssSettings() { CommentMode = CssComment.None };
            response.Write(minifier.MinifyStyleSheet(content, settings));
        }
        else if (ext == ".js")
        {
            CodeSettings settings = new CodeSettings() { PreserveImportantComments = false };
            response.Write(minifier.MinifyJavaScript(content, settings));
        }
    }
Esempio n. 12
0
        public void Process(BundleContext context, BundleResponse response)
        {
            var pattern = new Regex(@"url\s*\(\s*([""']?)([^:)]+)\1\s*\)", RegexOptions.IgnoreCase);

            response.Content = string.Empty;

            // open each of the files
            foreach (var file in response.Files)
            {
                using (var reader = new StreamReader(file.VirtualFile.Open()))
                {
                    var contents = reader.ReadToEnd();

                    // apply the RegEx to the file (to change relative paths)
                    var matches = pattern.Matches(contents);

                    if (matches.Count > 0)
                    {
                        var directoryPath = VirtualPathUtility.GetDirectory(file.VirtualFile.VirtualPath);

                        foreach (Match match in matches)
                        {
                            // this is a path that is relative to the CSS file
                            var imageRelativePath = match.Groups[2].Value;

                            // get the image virtual path
                            var imageVirtualPath = VirtualPathUtility.Combine(directoryPath, imageRelativePath);

                            // convert the image virtual path to absolute
                            var quote = match.Groups[1].Value;
                            var replace = String.Format("url({0}{1}{0})", quote, VirtualPathUtility.ToAbsolute(imageVirtualPath));
                            contents = contents.Replace(match.Groups[0].Value, replace);
                        }

                    }
                    // copy the result into the response.
                    response.Content = String.Format("{0}\r\n{1}", response.Content, contents);
                }

                var minifer = new Minifier();
                var cs = new CssSettings();
                var responseContent = minifer.MinifyStyleSheet(response.Content, cs);
                response.Content = responseContent;

            }
        }
Esempio n. 13
0
        /// <summary>
        /// Get settings for the minification
        /// </summary>
        /// <param name="config"></param>
        /// <returns>CssSettings based on the config file.</returns>
        public static CssSettings GetSettings(Config config)
        {
            LoadDefaultSettings(config, "css");

            CssSettings settings = new CssSettings();
            settings.TermSemicolons = GetValue(config, "termSemicolons") == "True";

            string cssComment = GetValue(config, "commentMode");

            if (cssComment == "hacks")
                settings.CommentMode = CssComment.Hacks;
            else if (cssComment == "important")
                settings.CommentMode = CssComment.Important;
            else if (cssComment == "none")
                settings.CommentMode = CssComment.None;
            else if (cssComment == "all")
                settings.CommentMode = CssComment.All;

            string colorNames = GetValue(config, "colorNames");

            if (colorNames == "hex")
                settings.ColorNames = CssColor.Hex;
            else if (colorNames == "major")
                settings.ColorNames = CssColor.Major;
            else if (colorNames == "noSwap")
                settings.ColorNames = CssColor.NoSwap;
            else if (colorNames == "strict")
                settings.ColorNames = CssColor.Strict;

            string outputMode = GetValue(config, "outputMode", "singleLine");

            if (outputMode == "multipleLines")
                settings.OutputMode = OutputMode.MultipleLines;
            else if (outputMode == "singleLine")
                settings.OutputMode = OutputMode.SingleLine;
            else if (outputMode == "none")
                settings.OutputMode = OutputMode.None;

            string indentSize = GetValue(config, "indentSize", 2);
            int size;
            if (int.TryParse(indentSize, out size))
                settings.IndentSize = size;

            return settings;
        }
Esempio n. 14
0
        public CssSettings Clone()
        {
            // create the new settings object and copy all the properties from
            // the current settings
            var newSettings = new CssSettings()
            {
                AllowEmbeddedAspNetBlocks = this.AllowEmbeddedAspNetBlocks,
                ColorNames             = this.ColorNames,
                CommentMode            = this.CommentMode,
                FixIE8Fonts            = this.FixIE8Fonts,
                IgnoreAllErrors        = this.IgnoreAllErrors,
                IgnoreErrorList        = this.IgnoreErrorList,
                IndentSize             = this.IndentSize,
                KillSwitch             = this.KillSwitch,
                LineBreakThreshold     = this.LineBreakThreshold,
                MinifyExpressions      = this.MinifyExpressions,
                OutputMode             = this.OutputMode,
                PreprocessorDefineList = this.PreprocessorDefineList,
                TermSemicolons         = this.TermSemicolons,
                CssType = this.CssType,
                BlocksStartOnSameLine = this.BlocksStartOnSameLine,
                RemoveEmptyBlocks     = this.RemoveEmptyBlocks,
            };

            // add the resource strings (if any)
            newSettings.AddResourceStrings(this.ResourceStrings);

            foreach (var item in this.ReplacementTokens)
            {
                newSettings.ReplacementTokens.Add(item);
            }

            foreach (var item in this.ReplacementFallbacks)
            {
                newSettings.ReplacementTokens.Add(item);
            }

            foreach (var item in this.ExcludeVendorPrefixes)
            {
                newSettings.ExcludeVendorPrefixes.Add(item);
            }

            return(newSettings);
        }
        public virtual string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<BundleFile> files)
        {
            CssSettings settings = new CssSettings();
            settings.IgnoreAllErrors = true;
            settings.CommentMode = CssComment.None;
            var minifier = new Minifier();
            var content = new StringBuilder(100000);


            foreach (var file in files)
            {
                FileInfo f = new FileInfo(HttpContext.Current.Server.MapPath(file.VirtualFile.VirtualPath));

                string readFile = Read(f);

                content.Append(minifier.MinifyStyleSheet(readFile, settings));
                content.AppendLine();
            }

            return content.ToString();
        }
Esempio n. 16
0
        public static string Minify(string fullFileName, string text, EnvDTE.ProjectItem projectItem,CssSettings cssSettings)
        {
            Minifier minifier = new Minifier();
            string miniCss = minifier.MinifyStyleSheet(text, cssSettings);

            foreach (var err in minifier.ErrorList)
            {

                if (TaskList.Instance == null)
                {
                    Console.WriteLine(string.Format("{0}({1},{2}){3}", fullFileName, 1, 1, err));
                }
                else
                {
                    TaskList.Instance.Add(projectItem.ContainingProject, Microsoft.VisualStudio.Shell.TaskErrorCategory.Error, fullFileName, err.StartLine, err.StartColumn, err.Message);

                }
            }

            return miniCss;
        }
Esempio n. 17
0
        public CssParser()
        {
            // default settings
            Settings = new CssSettings();

            // create a list of strings that represent the namespaces declared
            // in a @namespace statement. We will clear this every time we parse a new source string.
            m_namespaces = new List<string>();
        }
Esempio n. 18
0
 /// <summary>
 /// Constructs an instance of the Microsoft Ajax CSS Minifier
 /// </summary>
 /// <param name="settings">Microsoft Ajax CSS Minifier settings</param>
 public MsAjaxCssMinifier(MsAjaxCssMinificationSettings settings)
 {
     _originalEmbeddedCssSettings = CreateOriginalCssMinifierSettings(settings, false);
     _originalInlineCssSettings = CreateOriginalCssMinifierSettings(settings, true);
     _originalJsSettings = new CodeSettings();
 }
Esempio n. 19
0
        /// <summary>
        /// Maps a CSS minifier settings
        /// </summary>
        /// <param name="originalSettings">Original CSS minifier settings</param>
        /// <param name="settings">CSS minifier settings</param>
        private static void MapCssSettings(CssSettings originalSettings, MsAjaxCssMinificationSettings settings)
        {
            MapCommonSettings(originalSettings, settings);

            originalSettings.ColorNames = Utils.GetEnumFromOtherEnum<WmmCssColor, MsCssColor>(
                settings.ColorNames);
            originalSettings.CommentMode = Utils.GetEnumFromOtherEnum<WmmCssComment, MsCssComment>(
                settings.CommentMode);
            originalSettings.MinifyExpressions = settings.MinifyExpressions;
            originalSettings.RemoveEmptyBlocks = settings.RemoveEmptyBlocks;
        }
Esempio n. 20
0
        /// <summary>
        /// Creates a original CSS minifier settings
        /// </summary>
        /// <param name="settings">CSS minifier settings</param>
        /// <param name="isInlineCode">Flag for whether to create a settings for inline code</param>
        /// <returns>Original CSS minifier settings</returns>
        private static CssSettings CreateOriginalCssMinifierSettings(MsAjaxCssMinificationSettings settings,
			bool isInlineCode)
        {
            var originalSettings = new CssSettings();
            MapCssSettings(originalSettings, settings);
            originalSettings.CssType = isInlineCode ? CssType.DeclarationList : CssType.FullStyleSheet;

            return originalSettings;
        }
        /// <summary>
        /// Minifies the CSS stylesheet passes to it using the given settings, returning the minified results
        /// The ErrorList property will be set with any errors found during the minification process.
        /// </summary>
        /// <param name="source">CSS Source</param>
        /// <param name="settings">CSS minification settings</param>
        /// <param name="scriptSettings">JS minification settings to use for expression-minification</param>
        /// <returns>Minified StyleSheet</returns>
        public string MinifyStyleSheet(string source, CssSettings settings, CodeSettings scriptSettings)
        {
            // initialize some values, including the error list (which shoudl start off empty)
            string minifiedResults = string.Empty;
            m_errorList = new List<ContextError>();

            // create the parser object and if we specified some settings,
            // use it to set the Parser's settings object
            CssParser parser = new CssParser();
            parser.FileContext = FileName;

            if (settings != null)
            {
                parser.Settings = settings;
            }

            if (scriptSettings != null)
            {
                parser.JSSettings = scriptSettings;
            }

            // hook the error handler
            parser.CssError += new EventHandler<CssErrorEventArgs>(OnCssError);

            // try parsing the source and return the results
            try
            {
                minifiedResults = parser.Parse(source);
            }
            catch (Exception e)
            {
                m_errorList.Add(new ContextError(
                    true,
                    0,
                    null,
                    null,
                    null,
                    this.FileName,
                    0,
                    0,
                    0,
                    0,
                    e.Message));
                throw;
            }
            return minifiedResults;
        }
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;

            // Read setName, contentType and version. All are required. They are
            // used as cache key
            string setName = request["s"] ?? string.Empty;
            string contentType = request["t"] ?? string.Empty;
            string version = request["v"] ?? string.Empty;

            // Decide if browser supports compressed response
            bool isCompressed = DO_GZIP && this.CanGZip(context.Request);

            // Response is written as UTF8 encoding. If you are using languages like
            // Arabic, you should change this to proper encoding
            UTF8Encoding encoding = new UTF8Encoding(false);

            // If the set has already been cached, write the response directly from
            // cache. Otherwise generate the response and cache it
            if (!this.WriteFromCache(context, setName, version, isCompressed, contentType)) {

                using (MemoryStream memoryStream = new MemoryStream(5000)) {

                    // Decide regular stream or GZipStream based on whether the response
                    // can be cached or not
                    using (Stream writer = isCompressed ?
                        (Stream)(new GZipStream(memoryStream, CompressionMode.Compress)) : memoryStream) {

                        // Load the files defined in and process each file
                        string setDefinition = GetFilelist(setName) ?? "";

                        string[] fileNames = setDefinition.Split(new char[] { ',' },
                            StringSplitOptions.RemoveEmptyEntries);

                        string minifiedString = string.Empty;
                        var minifier = new Minifier();
                        StringBuilder allScripts = new StringBuilder();

                        if (contentType == JS_TYPE) {
                            foreach (string fileName in fileNames) {
                                byte[] fileBytes = this.GetFileBytes(context, fileName.Trim(), encoding);
                                allScripts.Append(Encoding.UTF8.GetString(fileBytes));
                                //writer.Write(fileBytes, 0, fileBytes.Length);
                            }

                            var codeSettings = new CodeSettings();
                            codeSettings.MinifyCode = true;
                            codeSettings.OutputMode = OutputMode.SingleLine;
                            //codeSettings.OutputMode = OutputMode.MultipleLines;
                            codeSettings.InlineSafeStrings = true;
                            codeSettings.MacSafariQuirks = true;
                            codeSettings.RemoveUnneededCode = true;
                            codeSettings.LocalRenaming = LocalRenaming.CrunchAll;
                            codeSettings.EvalTreatment = EvalTreatment.MakeAllSafe;
                            //codeSettings.CombineDuplicateLiterals = true;
                            codeSettings.PreserveFunctionNames = false;
                            minifiedString = minifier.MinifyJavaScript(allScripts.ToString(), codeSettings);
                        }

                        if (contentType == CSS_TYPE) {
                            CssParser parser = new CssParser();
                            foreach (string fileName in fileNames) {
                                byte[] fileBytes = this.GetFileBytes(context, fileName.Trim(), encoding);
                                string crunchedStyles = parser.Parse(Encoding.UTF8.GetString(fileBytes));
                                allScripts.Append(crunchedStyles);
                            }

                            var cssSettings = new CssSettings();
                            cssSettings.CommentMode = CssComment.None;
                            cssSettings.ColorNames = CssColor.Strict;
                            //cssSettings.ExpandOutput = true;
                            cssSettings.TermSemicolons = true;
                            minifiedString = minifier.MinifyStyleSheet(allScripts.ToString(), cssSettings);
                        }

                        byte[] rikiki = Encoding.UTF8.GetBytes(minifiedString);
                        writer.Write(rikiki, 0, rikiki.Length);
                        writer.Close();
                    }

                    // Cache the combined response so that it can be directly written
                    // in subsequent calls
                    byte[] responseBytes = memoryStream.ToArray();
                    context.Cache.Insert(
                        GetCacheKey(setName, version, isCompressed),
                        responseBytes,
                        null,
                        Cache.NoAbsoluteExpiration,
                        CACHE_DURATION);

                    // Generate the response
                    this.WriteBytes(responseBytes, context, isCompressed, contentType);
                }
            }
        }
        public CssSettings Clone()
        {
            // create the new settings object and copy all the properties from
            // the current settings
            var newSettings = new CssSettings()
            {
                AllowEmbeddedAspNetBlocks = this.AllowEmbeddedAspNetBlocks,
                ColorNames = this.ColorNames,
                CommentMode = this.CommentMode,
                IgnoreAllErrors = this.IgnoreAllErrors,
                IgnoreErrorList = this.IgnoreErrorList,
                IndentSize = this.IndentSize,
                KillSwitch = this.KillSwitch,
                LineBreakThreshold = this.LineBreakThreshold,
                MinifyExpressions = this.MinifyExpressions,
                OutputMode = this.OutputMode,
                PreprocessorDefineList = this.PreprocessorDefineList,
                TermSemicolons = this.TermSemicolons,
                CssType = this.CssType,
                BlocksStartOnSameLine = this.BlocksStartOnSameLine,
            };

            // add the resource strings (if any)
            newSettings.AddResourceStrings(this.ResourceStrings);

            return newSettings;
        }
Esempio n. 24
0
        public override IEnumerable<PvcCore.PvcStream> Execute(IEnumerable<PvcCore.PvcStream> inputStreams)
        {
            var resultStreams = new List<PvcStream>();
            SwitchParser switchParser = null;

            if (!String.IsNullOrEmpty(this.commandLineSwitches))
            {
                switchParser = new SwitchParser();
                switchParser.Parse(this.commandLineSwitches);
            }

            foreach (var inputStream in inputStreams)
            {
                var dirName = Path.GetDirectoryName(inputStream.StreamName);
                var fileName = Path.GetFileNameWithoutExtension(inputStream.StreamName) + ".min" + Path.GetExtension(inputStream.StreamName);
                var resultName = Path.Combine(dirName, fileName);
                var fileContent = new StreamReader(inputStream).ReadToEnd();
                var minifier = new Minifier();
                var sourceStream = new MemoryStream();
                var outputWriter = new StreamWriter(sourceStream);

                if (inputStream.StreamName.EndsWith(".js"))
                {
                    // Currently AjaxMin only supports JS source maps
                    if (this.generateSourceMaps)
                    {
                        var resultMapName = resultName + ".map";
                        var utf8 = new UTF8Encoding(false);
                        var mapStream = new MemoryStream();
                        var mapWriter = new SourcemapStreamWriter(mapStream, utf8);
                        var sourceMap = new V3SourceMap(mapWriter);

                        if (sourceMap != null)
                        {
                            if (switchParser == null)
                            {
                                switchParser = new SwitchParser();
                            }

                            switchParser.JSSettings.SymbolsMap = sourceMap;
                            switchParser.JSSettings.TermSemicolons = true;

                            sourceMap.StartPackage(resultName, resultMapName);

                            outputWriter.Write(minifier.MinifyJavaScript(fileContent, switchParser.JSSettings));

                            sourceMap.EndPackage();
                            sourceMap.EndFile(outputWriter, "\r\n");

                            sourceMap.Dispose();
                            mapWriter.Flush();

                            resultStreams.Add(new PvcStream(() => mapStream).As(resultMapName));
                        }
                    }
                    else
                    {
                        CodeSettings settings = new CodeSettings();
                        if (switchParser != null)   settings = switchParser.JSSettings;
                        outputWriter.Write(minifier.MinifyJavaScript(fileContent, settings));
                    }
                }
                else
                {
                    CssSettings settings = new CssSettings();
                    if (switchParser != null) settings = switchParser.CssSettings;
                    outputWriter.Write(minifier.MinifyStyleSheet(fileContent, settings));
                }

                foreach (var error in minifier.ErrorList)
                {
                    Console.Error.WriteLine(error.ToString());
                }

                outputWriter.Flush();
                resultStreams.Add(new PvcStream(() => sourceStream).As(resultName));
            }

            return resultStreams;
        }
Esempio n. 25
0
 public MsCompressor(CssSettings settings)
 {
     Settings = settings;
 }
 /// <summary>
 /// Minifies the CSS stylesheet passes to it using the given settings, returning the minified results
 /// The ErrorList property will be set with any errors found during the minification process.
 /// </summary>
 /// <param name="source">CSS Source</param>
 /// <param name="settings">CSS minification settings</param>
 /// <returns>Minified StyleSheet</returns>
 public string MinifyStyleSheet(string source, CssSettings settings)
 {
     // just pass in default settings
     return MinifyStyleSheet(source, settings, new CodeSettings());
 }
        /// <summary>
        /// Gets a inline CSS-code parser settings
        /// </summary>
        /// <returns>Inline CSS-code parser settings</returns>
        private CssSettings GetInlineCssParserSettings()
        {
            var inlineCssParserSettings = new CssSettings();
            MapCssSettings(inlineCssParserSettings, _settings);
            inlineCssParserSettings.CssType = CssType.DeclarationList;

            return inlineCssParserSettings;
        }
Esempio n. 28
0
        public SwitchParser()
        {
            // initialize with default values
            JSSettings = new CodeSettings();
            CssSettings = new CssSettings();

            // see if this is running under the Mono runtime (on UNIX)
            m_isMono = Type.GetType("Mono.Runtime") != null;
        }
        public CssParser()
        {
            // default settings
            Settings = new CssSettings();

            // create the default settings we'll use for JS expression minification
            // use the defaults, other than to set the kill switch so that it leaves
            // string literals alone (so we don't inadvertently change any delimiter chars)
            JSSettings = null;

            // create a list of strings that represent the namespaces declared
            // in a @namespace statement. We will clear this every time we parse a new source string.
            m_namespaces = new HashSet<string>();
        }
 public MicrosoftStylesheetMinifier(CssSettings cssSettings)
 {
     this.cssSettings = cssSettings;
 }
Esempio n. 31
0
 public SwitchParser(CodeSettings scriptSettings, CssSettings cssSettings)
 {
     // apply the switches to these two settings objects
     JSSettings = scriptSettings ?? new CodeSettings();
     CssSettings = cssSettings ?? new CssSettings();
 }
Esempio n. 32
0
        public override string MinifyString(string source)
        {
            Minifier minifier = new Minifier();

            var settings = new Microsoft.Ajax.Utilities.CssSettings
            {
                CommentMode = WESettings.Instance.General.KeepImportantComments ? CssComment.Hacks : CssComment.Important
            };

            return minifier.MinifyStyleSheet(source, settings);
        }
Esempio n. 33
0
 /// <summary>
 /// Minifies the CSS stylesheet passes to it using the given settings, returning the minified results
 /// The ErrorList property will be set with any errors found during the minification process.
 /// </summary>
 /// <param name="source">CSS Source</param>
 /// <param name="settings">CSS minification settings</param>
 /// <returns>Minified StyleSheet</returns>
 public string MinifyStyleSheet(string source, CssSettings settings)
 {
     // just pass in default settings
     return(MinifyStyleSheet(source, settings, new CodeSettings()));
 }
Esempio n. 34
0
 public MsMinifier(CssSettings settings)
 {
     Settings = settings;
 }
Esempio n. 35
0
        private void minifyButton_Click(object sender, EventArgs e)
        {
            this.ccsb.SetMessage("Minify in progress...");
            this.Refresh();

            foreach (var item in webResourceListView.CheckedItems)
            {
                var entity = (Entity)((ListViewItem)item).Tag;
                if(entity.GetAttributeValue<OptionSetValue>("webresourcetype").Value == 3)
                {

                    CodeSettings cs = new CodeSettings()
                    {
                        //common
                        AllowEmbeddedAspNetBlocks = aspnetCheckBox.Checked,
                        BlocksStartOnSameLine = (BlockStart)((ComboBoxItem)bracesComboBox.SelectedItem).Value,
                        IgnoreAllErrors = IgnoreAllErrorsCheckBox.Checked,

                        //js specific
                        AlwaysEscapeNonAscii = asciiCheckBox.Checked,
                        CollapseToLiteral = collapseCheckBox.Checked,
                        ConstStatementsMozilla = ConstStatementsMozillaCheckBox.Checked,
                        ErrorIfNotInlineSafe = ErrorIfNotInlineSafeCheckBox.Checked,
                        EvalLiteralExpressions = EvalLiteralExpressionsCheckBox.Checked,
                        EvalTreatment = (EvalTreatment)((ComboBoxItem)EvalTreatmentComboBox.SelectedItem).Value,
                        Format = (JavaScriptFormat)((ComboBoxItem)FormatComboBox.SelectedItem).Value,
                        LocalRenaming = (LocalRenaming)((ComboBoxItem)LocalRenamingComboBox.SelectedItem).Value,
                        MacSafariQuirks = MacSafariQuirksCheckBox.Checked,
                        PreserveFunctionNames = PreserveFunctionNamesCheckBox.Checked,
                        PreserveImportantComments = PreserveImportantCommentsCheckBox.Checked,
                        QuoteObjectLiteralProperties = QuoteObjectLiteralPropertiesCheckBox.Checked,
                        RemoveFunctionExpressionNames = RemoveFunctionExpressionNamesCheckBox.Checked,
                        StripDebugStatements = StripDebugStatementsCheckBox.Checked
                    };

                    minifyJS(entity, cs);
                }
                else if(entity.GetAttributeValue<OptionSetValue>("webresourcetype").Value == 2)
                {
                    CssSettings settings = new CssSettings()
                    {
                        //common
                        AllowEmbeddedAspNetBlocks = aspnetCheckBox.Checked,
                        BlocksStartOnSameLine = (BlockStart)((ComboBoxItem)bracesComboBox.SelectedItem).Value,
                        IgnoreAllErrors = IgnoreAllErrorsCheckBox.Checked,
                        //css specific
                        ColorNames = (CssColor)((ComboBoxItem)ColorNamesComboBox.SelectedItem).Value,
                        CommentMode = (CssComment)((ComboBoxItem)CommentModeComboBox.SelectedItem).Value,
                        CssType = (CssType)((ComboBoxItem)CssTypeComboBox.SelectedItem).Value,
                        MinifyExpressions = MinifyExpressionsCheckBox.Checked
                    };
                    minifyCSS(entity, settings);
                }
            }

            this.ccsb.SetMessage("Minify complete.");
            this.Refresh();
        }
Esempio n. 36
0
 private void minifyCSS(Entity entity, CssSettings settings)
 {
     Microsoft.Ajax.Utilities.Minifier minifier = new Microsoft.Ajax.Utilities.Minifier();
     string name = entity.GetAttributeValue<string>("displayname");
     byte[] cssFileBytes = Convert.FromBase64String(entity.GetAttributeValue<string>("content"));
     string originalCss = UnicodeEncoding.UTF8.GetString(cssFileBytes);
     string minifiedCss = minifier.MinifyStyleSheet(originalCss, settings);
     byte[] minifiedCssBytes = UnicodeEncoding.UTF8.GetBytes(minifiedCss);
     string minifiedCssBytesString = Convert.ToBase64String(minifiedCssBytes);
     Entity updatedWebResource = new Entity(entity.LogicalName);
     updatedWebResource.Attributes.Add("content", minifiedCssBytesString);
     updatedWebResource.Id = entity.Id;
     this.service.Update(updatedWebResource);
 }