Пример #1
0
        public override string MinifyString(string source)
        {
            var weHtmlSettings = WESettings.Instance.Html;
            var settings = new HtmlMinificationSettings
            {
                // Tags
                RemoveOptionalEndTags = false,
                //EmptyTagRenderMode = HtmlEmptyTagRenderMode.Slash,

                // Attributes
                AttributeQuotesRemovalMode = weHtmlSettings.AttributeQuotesRemovalMode,
                RemoveRedundantAttributes = false,

                // JavaScript templating
                ProcessableScriptTypeList = weHtmlSettings.ProcessableScriptTypeList,
                MinifyKnockoutBindingExpressions = weHtmlSettings.MinifyKnockoutBindingExpressions,
                MinifyAngularBindingExpressions = weHtmlSettings.MinifyAngularBindingExpressions,
                CustomAngularDirectiveList = weHtmlSettings.CustomAngularDirectiveList
            };

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

            if (result.Errors.Count == 0)
            {
                WebEssentialsPackage.DTE.StatusBar.Text = "Web Essentials: HTML minified by " + result.Statistics.SavedInPercent + "%";
                return result.MinifiedContent;
            }
            else
            {
                WebEssentialsPackage.DTE.StatusBar.Text = "Web Essentials: Cannot minify the current selection.  See Output Window for details.";
                Logger.ShowMessage("Cannot minify the selection:\r\n\r\n" + String.Join(Environment.NewLine, result.Errors.Select(e => e.Message)));
                return null;
            }
        }
Пример #2
0
        /// <summary>
        /// Safely Attempts to minify the provided string.
        /// </summary>
        /// <param name="recording">The string to minify</param>
        /// <returns>Minified version of the string, or, if errors were encountered, returns the original string.</returns>
        private string Minify(string recording)
        {
            var settings    = new HtmlMinificationSettings();
            var cssMinifier = new KristensenCssMinifier();
            var jsMinifier  = new CrockfordJsMinifier();

            var minifier = new HtmlMinifier(settings, cssMinifier, jsMinifier);

            MarkupMinificationResult result = minifier.Minify(recording);

            if (result.Errors.Count != 0)
            {
                var builder = new StringBuilder("Attempt to minify rendering failed");

                foreach (var error in result.Errors)
                {
                    builder.AppendLine(error.Category + " - " + error.Message);
                }

                Log.Warn(builder.ToString(), this);
                return(recording);
            }

            return(result.MinifiedContent);
        }
		/// <summary>
		/// Safely Attempts to minify the provided string.
		/// </summary>
		/// <param name="recording">The string to minify</param>
		/// <returns>Minified version of the string, or, if errors were encountered, returns the original string.</returns>
		private string Minify(string recording)
		{
			var settings = new HtmlMinificationSettings();
			var cssMinifier = new KristensenCssMinifier();
			var jsMinifier = new CrockfordJsMinifier();

			var minifier = new HtmlMinifier(settings, cssMinifier, jsMinifier);

			MarkupMinificationResult result = minifier.Minify(recording);

			if (result.Errors.Count != 0)
			{
				var builder = new StringBuilder("Attempt to minify rendering failed");

				foreach (var error in result.Errors)
				{
					builder.AppendLine(error.Category + " - " + error.Message);
				}

				Log.Warn(builder.ToString(), this);
				return recording;
			}

			return result.MinifiedContent;
		}
Пример #4
0
        public override string MinifyString(string source)
        {
            var weHtmlSettings = WESettings.Instance.Html;
            var settings       = new HtmlMinificationSettings
            {
                // Tags
                RemoveOptionalEndTags = false,
                //EmptyTagRenderMode = HtmlEmptyTagRenderMode.Slash,

                // Attributes
                AttributeQuotesRemovalMode = weHtmlSettings.AttributeQuotesRemovalMode,
                RemoveRedundantAttributes  = false,

                // JavaScript templating
                ProcessableScriptTypeList        = weHtmlSettings.ProcessableScriptTypeList,
                MinifyKnockoutBindingExpressions = weHtmlSettings.MinifyKnockoutBindingExpressions,
                MinifyAngularBindingExpressions  = weHtmlSettings.MinifyAngularBindingExpressions,
                CustomAngularDirectiveList       = weHtmlSettings.CustomAngularDirectiveList
            };

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

            if (result.Errors.Count == 0)
            {
                WebEssentialsPackage.DTE.StatusBar.Text = "Web Essentials: HTML minified by " + result.Statistics.SavedInPercent + "%";
                return(result.MinifiedContent);
            }
            else
            {
                WebEssentialsPackage.DTE.StatusBar.Text = "Web Essentials: Cannot minify the current selection.  See Output Window for details.";
                Logger.ShowMessage("Cannot minify the selection:\r\n\r\n" + String.Join(Environment.NewLine, result.Errors.Select(e => e.Message)));
                return(null);
            }
        }
Пример #5
0
        public override string MinifyString(string source)
        {
            var settings = new HtmlMinificationSettings
            {
                RemoveOptionalEndTags = false,

                AttributeQuotesRemovalMode = WESettings.Instance.Html.MinificationMode,
                RemoveRedundantAttributes  = false,
                //EmptyTagRenderMode = HtmlEmptyTagRenderMode.Slash,
            };

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

            if (result.Errors.Count == 0)
            {
                WebEssentialsPackage.DTE.StatusBar.Text = "Web Essentials: HTML minified by " + result.Statistics.SavedInPercent + "%";
                return(result.MinifiedContent);
            }
            else
            {
                WebEssentialsPackage.DTE.StatusBar.Text = "Web Essentials: Cannot minify the current selection.  See Output Window for details.";
                Logger.ShowMessage("Cannot minify the selection:\r\n\r\n" + String.Join(Environment.NewLine, result.Errors.Select(e => e.Message)));
                return(null);
            }
        }
Пример #6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddInstance(Configuration);

            // Add WebMarkupMin services to the services container.
            services.AddWebMarkupMin(options =>
            {
                options.AllowMinificationInDevelopmentEnvironment = true;
                options.AllowCompressionInDevelopmentEnvironment  = true;
            })
            .AddHtmlMinification(options =>
            {
                options.ExcludedPages = new List <IUrlMatcher>
                {
                    new WildcardUrlMatcher("/minifiers/x*ml-minifier"),
                    new ExactUrlMatcher("/contact")
                };

                HtmlMinificationSettings settings          = options.MinificationSettings;
                settings.RemoveRedundantAttributes         = true;
                settings.RemoveHttpProtocolFromAttributes  = true;
                settings.RemoveHttpsProtocolFromAttributes = true;

                options.CssMinifierFactory = new MsAjaxCssMinifierFactory();
                options.JsMinifierFactory  = new MsAjaxJsMinifierFactory();
            })
            .AddXhtmlMinification(options =>
            {
                options.IncludedPages = new List <IUrlMatcher>
                {
                    new WildcardUrlMatcher("/minifiers/x*ml-minifier"),
                    new ExactUrlMatcher("/contact")
                };

                XhtmlMinificationSettings settings         = options.MinificationSettings;
                settings.RemoveRedundantAttributes         = true;
                settings.RemoveHttpProtocolFromAttributes  = true;
                settings.RemoveHttpsProtocolFromAttributes = true;

                options.CssMinifierFactory = new YuiCssMinifierFactory();
                options.JsMinifierFactory  = new YuiJsMinifierFactory();
            })
            .AddXmlMinification(options => {
                XmlMinificationSettings settings    = options.MinificationSettings;
                settings.CollapseTagsWithoutContent = true;
            })
            .AddHttpCompression()
            ;

            // Add framework services.
            services.AddMvc();

            // Add WebMarkupMin sample services to the services container.
            services.AddSingleton <SitemapService>();
            services.AddSingleton <CssMinifierFactory>();
            services.AddSingleton <JsMinifierFactory>();
            services.AddSingleton <HtmlMinificationService>();
            services.AddSingleton <XhtmlMinificationService>();
            services.AddSingleton <XmlMinificationService>();
        }
Пример #7
0
        public override string MinifyString(string source)
        {
            var settings = new HtmlMinificationSettings
            {
                RemoveOptionalEndTags = false,

                AttributeQuotesRemovalMode = WESettings.Instance.Html.MinificationMode,
                RemoveRedundantAttributes = false,
                //EmptyTagRenderMode = HtmlEmptyTagRenderMode.Slash,
            };

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

            if (result.Errors.Count == 0)
            {
                WebEssentialsPackage.DTE.StatusBar.Text = "Web Essentials: HTML minified by " + result.Statistics.SavedInPercent + "%";
                return result.MinifiedContent;
            }
            else
            {
                WebEssentialsPackage.DTE.StatusBar.Text = "Web Essentials: Cannot minify the current selection.  See Output Window for details.";
                Logger.ShowMessage("Cannot minify the selection:\r\n\r\n" + String.Join(Environment.NewLine, result.Errors.Select(e => e.Message)));
                return null;
            }
        }
        public static void Configure(WebMarkupMinConfiguration configuration)
        {
            configuration.AllowMinificationInDebugMode = true;
            configuration.AllowCompressionInDebugMode  = true;

            DefaultCssMinifierFactory.Current = new MsAjaxCssMinifierFactory();
            DefaultJsMinifierFactory.Current  = new MsAjaxJsMinifierFactory();

            IHtmlMinificationManager htmlMinificationManager  = HtmlMinificationManager.Current;
            HtmlMinificationSettings htmlMinificationSettings = htmlMinificationManager.MinificationSettings;

            htmlMinificationSettings.RemoveRedundantAttributes         = true;
            htmlMinificationSettings.RemoveHttpProtocolFromAttributes  = true;
            htmlMinificationSettings.RemoveHttpsProtocolFromAttributes = true;

            IXhtmlMinificationManager xhtmlMinificationManager  = XhtmlMinificationManager.Current;
            XhtmlMinificationSettings xhtmlMinificationSettings = xhtmlMinificationManager.MinificationSettings;

            xhtmlMinificationSettings.RemoveRedundantAttributes         = true;
            xhtmlMinificationSettings.RemoveHttpProtocolFromAttributes  = true;
            xhtmlMinificationSettings.RemoveHttpsProtocolFromAttributes = true;

            IXmlMinificationManager xmlMinificationManager  = XmlMinificationManager.Current;
            XmlMinificationSettings xmlMinificationSettings = xmlMinificationManager.MinificationSettings;

            xmlMinificationSettings.CollapseTagsWithoutContent = true;

            IHttpCompressionManager httpCompressionManager = HttpCompressionManager.Current;

            httpCompressionManager.CompressorFactories = new List <ICompressorFactory>
            {
                new DeflateCompressorFactory(),
                new GZipCompressorFactory()
            };
        }
Пример #9
0
        public static void  Register(IServiceCollection services)
        {
            services.AddWebMarkupMin(options =>
            {
                options.AllowMinificationInDevelopmentEnvironment = true;
                options.AllowCompressionInDevelopmentEnvironment  = true;
            })
            .AddHtmlMinification(options =>
            {
                options.ExcludedPages = new List <IUrlMatcher>
                {
                    new WildcardUrlMatcher("/minifiers/x*ml-minifier")
                };

                HtmlMinificationSettings settings          = options.MinificationSettings;
                settings.RemoveRedundantAttributes         = true;
                settings.RemoveHttpProtocolFromAttributes  = true;
                settings.RemoveHttpsProtocolFromAttributes = true;

                options.CssMinifierFactory = new NUglifyCssMinifierFactory();
                options.JsMinifierFactory  = new NUglifyJsMinifierFactory();
            })
            .AddXhtmlMinification(options =>
            {
                options.IncludedPages = new List <IUrlMatcher>
                {
                    new WildcardUrlMatcher("/minifiers/x*ml-minifier"),
                    new ExactUrlMatcher("/contact")
                };

                XhtmlMinificationSettings settings         = options.MinificationSettings;
                settings.RemoveRedundantAttributes         = true;
                settings.RemoveHttpProtocolFromAttributes  = true;
                settings.RemoveHttpsProtocolFromAttributes = true;

                options.CssMinifierFactory = new KristensenCssMinifierFactory();
                options.JsMinifierFactory  = new CrockfordJsMinifierFactory();
            })
            .AddXmlMinification(options =>
            {
                XmlMinificationSettings settings    = options.MinificationSettings;
                settings.CollapseTagsWithoutContent = true;
            })
            .AddHttpCompression(options =>
            {
                options.CompressorFactories = new List <ICompressorFactory>
                {
                    new GZipCompressorFactory(new GZipCompressionSettings
                    {
                        Level = CompressionLevel.Fastest
                    }),
                    new DeflateCompressorFactory(new DeflateCompressionSettings
                    {
                        Level = CompressionLevel.Fastest
                    })
                };
            });
        }
Пример #10
0
        private static MinificationResult MinifyHtml(string file, bool produceGzipFile)
        {
            var settings = new HtmlMinificationSettings
            {
                RemoveOptionalEndTags      = false,
                AttributeQuotesRemovalMode = WebMarkupMin.Core.HtmlAttributeQuotesRemovalMode.Html5,
                RemoveRedundantAttributes  = false,
            };

            string content = File.ReadAllText(file);
            string minFile = GetMinFileName(file);

            var minifier  = new HtmlMinifier(settings);
            var minResult = new MinificationResult(file, null, null);

            try
            {
                MarkupMinificationResult result = minifier.Minify(content, generateStatistics: true);
                minResult.MinifiedContent = result.MinifiedContent;

                if (!result.Errors.Any())
                {
                    OnBeforeWritingMinFile(file, minFile);
                    File.WriteAllText(minFile, result.MinifiedContent, new UTF8Encoding(true));
                    OnAfterWritingMinFile(file, minFile);

                    if (produceGzipFile)
                    {
                        GzipFile(minFile);
                    }
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        minResult.Errors.Add(new MinificationError
                        {
                            FileName     = file,
                            Message      = error.Message,
                            LineNumber   = error.LineNumber,
                            ColumnNumber = error.ColumnNumber
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                minResult.Errors.Add(new MinificationError
                {
                    FileName     = file,
                    Message      = ex.Message,
                    LineNumber   = 0,
                    ColumnNumber = 0
                });
            }

            return(minResult);
        }
Пример #11
0
        public static HtmlMinificationSettings GetSettings(Bundle bundle)
        {
            HtmlMinificationSettings settings = new HtmlMinificationSettings();

            settings.RemoveOptionalEndTags     = GetValue(bundle, "removeOptionalEndTags") == "True";
            settings.RemoveRedundantAttributes = GetValue(bundle, "removeRedundantAttributes") == "True";

            settings.CollapseBooleanAttributes       = GetValue(bundle, "collapseBooleanAttributes", true) == "True";
            settings.CustomAngularDirectiveList      = GetValue(bundle, "customAngularDirectiveList");
            settings.MinifyAngularBindingExpressions = GetValue(bundle, "minifyAngularBindingExpressions") == "True";
            settings.MinifyEmbeddedCssCode           = GetValue(bundle, "minifyEmbeddedCssCode", true) == "True";
            settings.MinifyEmbeddedJsCode            = GetValue(bundle, "minifyEmbeddedJsCode", true) == "True";
            settings.MinifyInlineCssCode             = GetValue(bundle, "minifyInlineCssCode", true) == "True";
            settings.MinifyInlineJsCode = GetValue(bundle, "minifyInlineJsCode", true) == "True";
            settings.MinifyKnockoutBindingExpressions = GetValue(bundle, "minifyKnockoutBindingExpressions") == "True";
            settings.ProcessableScriptTypeList        = GetValue(bundle, "processableScriptTypeList");
            settings.RemoveHtmlComments       = GetValue(bundle, "removeHtmlComments", true) == "True";
            settings.RemoveTagsWithoutContent = GetValue(bundle, "removeTagsWithoutContent") == "True";

            string quotes = GetValue(bundle, "attributeQuotesRemovalMode", "html5");

            if (quotes == "html4")
            {
                settings.AttributeQuotesRemovalMode = HtmlAttributeQuotesRemovalMode.Html4;
            }
            else if (quotes == "html5")
            {
                settings.AttributeQuotesRemovalMode = HtmlAttributeQuotesRemovalMode.Html5;
            }
            else if (quotes == "keepQuotes")
            {
                settings.AttributeQuotesRemovalMode = HtmlAttributeQuotesRemovalMode.KeepQuotes;
            }

            string whitespace = GetValue(bundle, "whitespaceMinificationMode", "medium");

            if (whitespace == "aggressive")
            {
                settings.WhitespaceMinificationMode = WhitespaceMinificationMode.Aggressive;
            }
            else if (whitespace == "medium")
            {
                settings.WhitespaceMinificationMode = WhitespaceMinificationMode.Medium;
            }
            else if (whitespace == "none")
            {
                settings.WhitespaceMinificationMode = WhitespaceMinificationMode.None;
            }
            else if (whitespace == "safe")
            {
                settings.WhitespaceMinificationMode = WhitespaceMinificationMode.Safe;
            }

            return(settings);
        }
 /// <summary>
 /// Constructs a instance of HTML minification manager
 /// </summary>
 /// <param name="settings">HTML minification settings</param>
 /// <param name="cssMinifierFactory">CSS minifier factory</param>
 /// <param name="jsMinifierFactory">JS minifier factory</param>
 /// <param name="logger">Logger</param>
 public HtmlMinificationManager(HtmlMinificationSettings settings,
                                ICssMinifierFactory cssMinifierFactory,
                                IJsMinifierFactory jsMinifierFactory,
                                ILogger logger)
 {
     MinificationSettings = settings;
     SupportedMediaTypes  = new HashSet <string>(MediaTypeGroupConstants.Html);
     CssMinifierFactory   = cssMinifierFactory;
     JsMinifierFactory    = jsMinifierFactory;
     Logger = logger;
 }
        /// <summary>
        /// Constructs a instance of HTML minification manager
        /// </summary>
        /// <param name="settings">HTML minification settings</param>
        /// <param name="cssMinifierFactory">CSS minifier factory</param>
        /// <param name="jsMinifierFactory">JS minifier factory</param>
        /// <param name="logger">Logger</param>
        public HtmlMinificationManager(HtmlMinificationSettings settings,
                                       ICssMinifierFactory cssMinifierFactory,
                                       IJsMinifierFactory jsMinifierFactory,
                                       ILogger logger)
        {
            MinificationSettings = settings;
            SupportedMediaTypes  = new HashSet <string>(MediaTypeGroupConstants.Html);
            IncludedPages        = new List <IUrlMatcher>();
            ExcludedPages        = new List <IUrlMatcher>();
            CssMinifierFactory   = cssMinifierFactory;
            JsMinifierFactory    = jsMinifierFactory;

            _logger = logger;
        }
		protected string Minify(string content)
		{
			var settings = new HtmlMinificationSettings();
			var cssMinifier = new KristensenCssMinifier();
			var jsMinifier = new CrockfordJsMinifier();
			var minifier = new HtmlMinifier(settings, cssMinifier, jsMinifier);

			MarkupMinificationResult result = minifier.Minify(content);

			if (result.Errors.Count != 0)
			{
				Log.Warn("Attempt to minify content failed", this);
				return content;
			}

			return result.MinifiedContent;
		}
Пример #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add response caching service.
            services.AddResponseCaching();

            // Add WebMarkupMin services to the services container.
            services.AddWebMarkupMin(options =>
            {
                options.AllowMinificationInDevelopmentEnvironment = true;
                options.AllowCompressionInDevelopmentEnvironment  = true;
            })
            .AddHtmlMinification(options =>
            {
                HtmlMinificationSettings settings          = options.MinificationSettings;
                settings.RemoveRedundantAttributes         = true;
                settings.RemoveHttpProtocolFromAttributes  = true;
                settings.RemoveHttpsProtocolFromAttributes = true;

                options.CssMinifierFactory = new NUglifyCssMinifierFactory();
                options.JsMinifierFactory  = new NUglifyJsMinifierFactory();
            })
            .AddHttpCompression(options =>
            {
                options.CompressorFactories = new List <ICompressorFactory>
                {
                    new BuiltInBrotliCompressorFactory(new BuiltInBrotliCompressionSettings
                    {
                        Level = CompressionLevel.Fastest
                    }),
                    new DeflateCompressorFactory(new DeflateCompressionSettings
                    {
                        Level = CompressionLevel.Fastest
                    }),
                    new GZipCompressorFactory(new GZipCompressionSettings
                    {
                        Level = CompressionLevel.Fastest
                    })
                };
            })
            ;

            // Override the default logger for WebMarkupMin.
            services.AddSingleton <IWmmLogger, WmmThrowExceptionLogger>();

            services.AddControllersWithViews();
        }
Пример #16
0
        /// <summary>
        /// HTML minification.
        /// </summary>
        /// <param name="html">Code to minify.</param>
        /// <returns>Minified html.</returns>
        public static string MinifyHtml(string html)
        {
            var settings     = new HtmlMinificationSettings();
            var cssMinifier  = new KristensenCssMinifier();
            var jsMinifier   = new CrockfordJsMinifier();
            var htmlMinifier = new HtmlMinifier(settings, cssMinifier, jsMinifier);

            MarkupMinificationResult result = htmlMinifier.Minify(
                html,
                generateStatistics: false);

            if (result.Errors.Count == 0)
            {
                return(result.MinifiedContent);
            }
            else
            {
                return(html);
            }
        }
Пример #17
0
        public static void Configure(WebMarkupMinConfiguration configuration)
        {
            configuration.AllowMinificationInDebugMode = true;
            configuration.AllowCompressionInDebugMode  = true;

            IHtmlMinificationManager htmlMinificationManager  = HtmlMinificationManager.Current;
            HtmlMinificationSettings htmlMinificationSettings = htmlMinificationManager.MinificationSettings;

            htmlMinificationSettings.RemoveRedundantAttributes         = true;
            htmlMinificationSettings.RemoveHttpProtocolFromAttributes  = true;
            htmlMinificationSettings.RemoveHttpsProtocolFromAttributes = true;

            IHttpCompressionManager httpCompressionManager = HttpCompressionManager.Current;

            httpCompressionManager.CompressorFactories = new List <ICompressorFactory>
            {
                new GZipCompressorFactory(),
                new DeflateCompressorFactory()
            };
        }
Пример #18
0
        public static void Configure(WebMarkupMinConfiguration configuration)
        {
            configuration.AllowMinificationInDebugMode = true;
            configuration.AllowCompressionInDebugMode  = true;

            DefaultLogger.Current             = new ThrowExceptionLogger();
            DefaultCssMinifierFactory.Current = new MsAjaxCssMinifierFactory();
            DefaultJsMinifierFactory.Current  = new MsAjaxJsMinifierFactory();

            IHtmlMinificationManager htmlMinificationManager  = HtmlMinificationManager.Current;
            HtmlMinificationSettings htmlMinificationSettings = htmlMinificationManager.MinificationSettings;

            htmlMinificationSettings.RemoveRedundantAttributes         = true;
            htmlMinificationSettings.RemoveHttpProtocolFromAttributes  = true;
            htmlMinificationSettings.RemoveHttpsProtocolFromAttributes = true;

            IXhtmlMinificationManager xhtmlMinificationManager  = XhtmlMinificationManager.Current;
            XhtmlMinificationSettings xhtmlMinificationSettings = xhtmlMinificationManager.MinificationSettings;

            xhtmlMinificationSettings.RemoveRedundantAttributes         = true;
            xhtmlMinificationSettings.RemoveHttpProtocolFromAttributes  = true;
            xhtmlMinificationSettings.RemoveHttpsProtocolFromAttributes = true;

            IHttpCompressionManager httpCompressionManager = HttpCompressionManager.Current;

            httpCompressionManager.CompressorFactories = new List <ICompressorFactory>
            {
                new BrotliCompressorFactory(new BrotliCompressionSettings
                {
                    Level = 1
                }),
                new DeflateCompressorFactory(new DeflateCompressionSettings
                {
                    Level = CompressionLevel.Fastest
                }),
                new GZipCompressorFactory(new GZipCompressionSettings
                {
                    Level = CompressionLevel.Fastest
                })
            };
        }
Пример #19
0
        /// <summary>
        /// Constructs instance of HTML minifier
        /// </summary>
        /// <param name="settings">HTML minification settings</param>
        /// <param name="cssMinifier">CSS minifier</param>
        /// <param name="jsMinifier">JS minifier</param>
        /// <param name="logger">Logger</param>
        public HtmlMinifier(HtmlMinificationSettings settings = null, ICssMinifier cssMinifier = null,
                            IJsMinifier jsMinifier            = null, ILogger logger = null)
        {
            settings = settings ?? new HtmlMinificationSettings();

            _genericHtmlMinifier = new GenericHtmlMinifier(
                new GenericHtmlMinificationSettings
            {
                WhitespaceMinificationMode              = settings.WhitespaceMinificationMode,
                RemoveHtmlComments                      = settings.RemoveHtmlComments,
                RemoveHtmlCommentsFromScriptsAndStyles  = settings.RemoveHtmlCommentsFromScriptsAndStyles,
                RemoveCdataSectionsFromScriptsAndStyles = settings.RemoveCdataSectionsFromScriptsAndStyles,
                UseShortDoctype                   = settings.UseShortDoctype,
                UseMetaCharsetTag                 = settings.UseMetaCharsetTag,
                EmptyTagRenderMode                = settings.EmptyTagRenderMode,
                RemoveOptionalEndTags             = settings.RemoveOptionalEndTags,
                RemoveTagsWithoutContent          = settings.RemoveTagsWithoutContent,
                CollapseBooleanAttributes         = settings.CollapseBooleanAttributes,
                RemoveEmptyAttributes             = settings.RemoveEmptyAttributes,
                AttributeQuotesRemovalMode        = settings.AttributeQuotesRemovalMode,
                RemoveRedundantAttributes         = settings.RemoveRedundantAttributes,
                RemoveJsTypeAttributes            = settings.RemoveJsTypeAttributes,
                RemoveCssTypeAttributes           = settings.RemoveCssTypeAttributes,
                RemoveHttpProtocolFromAttributes  = settings.RemoveHttpProtocolFromAttributes,
                RemoveHttpsProtocolFromAttributes = settings.RemoveHttpsProtocolFromAttributes,
                RemoveJsProtocolFromAttributes    = settings.RemoveJsProtocolFromAttributes,
                MinifyEmbeddedCssCode             = settings.MinifyEmbeddedCssCode,
                MinifyInlineCssCode               = settings.MinifyInlineCssCode,
                MinifyEmbeddedJsCode              = settings.MinifyEmbeddedJsCode,
                MinifyInlineJsCode                = settings.MinifyInlineJsCode,
                ProcessableScriptTypeList         = settings.ProcessableScriptTypeList,
                MinifyKnockoutBindingExpressions  = settings.MinifyKnockoutBindingExpressions,
                MinifyAngularBindingExpressions   = settings.MinifyAngularBindingExpressions,
                CustomAngularDirectiveList        = settings.CustomAngularDirectiveList,
                UseXhtmlSyntax = false
            },
                cssMinifier,
                jsMinifier,
                logger
                );
        }
Пример #20
0
        public static void Configure(WebMarkupMinConfiguration configuration)
        {
            configuration.AllowMinificationInDebugMode = true;
            configuration.AllowCompressionInDebugMode  = true;

            DefaultCssMinifierFactory.Current = new MsAjaxCssMinifierFactory();
            DefaultJsMinifierFactory.Current  = new MsAjaxJsMinifierFactory();

            IHtmlMinificationManager htmlMinificationManager  = HtmlMinificationManager.Current;
            HtmlMinificationSettings htmlMinificationSettings = htmlMinificationManager.MinificationSettings;

            htmlMinificationSettings.RemoveRedundantAttributes         = true;
            htmlMinificationSettings.RemoveHttpProtocolFromAttributes  = true;
            htmlMinificationSettings.RemoveHttpsProtocolFromAttributes = true;

            IXhtmlMinificationManager xhtmlMinificationManager  = XhtmlMinificationManager.Current;
            XhtmlMinificationSettings xhtmlMinificationSettings = xhtmlMinificationManager.MinificationSettings;

            xhtmlMinificationSettings.RemoveRedundantAttributes         = true;
            xhtmlMinificationSettings.RemoveHttpProtocolFromAttributes  = true;
            xhtmlMinificationSettings.RemoveHttpsProtocolFromAttributes = true;
        }
        private static string Minify(string html)
        {
            var settings = new HtmlMinificationSettings
            {
                RemoveOptionalEndTags      = false,
                AttributeQuotesRemovalMode = HtmlAttributeQuotesRemovalMode.Html5,
                RemoveRedundantAttributes  = false,
                WhitespaceMinificationMode = WhitespaceMinificationMode.Aggressive,
                MinifyEmbeddedCssCode      = true,
                MinifyEmbeddedJsCode       = true,
                MinifyInlineCssCode        = true,
                MinifyInlineJsCode         = true,
            };

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

            if (result.Errors.Count == 0)
            {
                return(result.MinifiedContent);
            }

            return(html);
        }
Пример #22
0
        private static MinificationResult MinifyHtml(string file, bool produceGzipFile)
        {
            var settings = new HtmlMinificationSettings
            {
                RemoveOptionalEndTags = false,
                AttributeQuotesRemovalMode = WebMarkupMin.Core.HtmlAttributeQuotesRemovalMode.Html5,
                RemoveRedundantAttributes = false,
            };

            string content = File.ReadAllText(file);
            string minFile = GetMinFileName(file);

            var minifier = new HtmlMinifier(settings);
            var minResult = new MinificationResult(file, null, null);

            try
            {
                MarkupMinificationResult result = minifier.Minify(content, generateStatistics: true);
                minResult.MinifiedContent = result.MinifiedContent;

                if (!result.Errors.Any())
                {
                    OnBeforeWritingMinFile(file, minFile);
                    File.WriteAllText(minFile, result.MinifiedContent, new UTF8Encoding(true));
                    OnAfterWritingMinFile(file, minFile);

                    if (produceGzipFile)
                        GzipFile(minFile);
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        minResult.Errors.Add(new MinificationError
                        {
                            FileName = file,
                            Message = error.Message,
                            LineNumber = error.LineNumber,
                            ColumnNumber = error.ColumnNumber
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                minResult.Errors.Add(new MinificationError
                {
                    FileName = file,
                    Message = ex.Message,
                    LineNumber = 0,
                    ColumnNumber = 0
                });
            }

            return minResult;
        }
Пример #23
0
 /// <summary>
 /// Minifies the HTML content.
 /// </summary>
 /// <param name="useEmptyMinificationSettings">
 /// Boolean to specify whether to use empty minification settings.
 /// Default value is <c>false</c>, this will use commonly accepted settings.
 /// </param>
 public MinifyHtml(bool useEmptyMinificationSettings = false)
 {
     // https://github.com/Taritsyn/WebMarkupMin/wiki/HTML-Minifier
     _minificationSettings = new HtmlMinificationSettings(useEmptyMinificationSettings);
 }
Пример #24
0
        public void ConfigureServices(IServiceCollection services)
        {
            #region Database

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("DefaultConnection")));
            #endregion

            #region Identity

            services.AddIdentity <IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.Configure <IdentityOptions>(options =>
            {
                // Password settings.
                options.Password.RequireDigit           = true;
                options.Password.RequireLowercase       = true;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 8;
                options.Password.RequiredUniqueChars    = 1;

                // Lockout settings.
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(15);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers      = true;

                // User settings.
                options.SignIn.RequireConfirmedEmail   = true;
                options.User.AllowedUserNameCharacters =
                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                options.User.RequireUniqueEmail = true;
            });

            services.AddScoped <AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider <IdentityUser> >();

            #endregion

            #region Cookies and Validators

            services.Configure <SecurityStampValidatorOptions>(options =>
                                                               options.ValidationInterval = TimeSpan.FromMinutes(15)
                                                               );

            services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.HttpOnly     = true;
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                options.Cookie.MaxAge       = TimeSpan.FromDays(3);
                options.ExpireTimeSpan      = TimeSpan.FromDays(3);
                options.LoginPath           = new PathString("/Account");
                options.AccessDeniedPath    = new PathString("/AccessDenied");
                options.LogoutPath          = new PathString("/Account/Logout");
                options.SlidingExpiration   = true;
                options.Cookie.SameSite     = SameSiteMode.Lax;
            });

            services.Configure <DataProtectionTokenProviderOptions>(o =>
                                                                    o.TokenLifespan = TimeSpan.FromMinutes(15));

            services.Configure <CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.Lax;
            });

            #endregion

            #region Caching and Antiforgery

            services.AddResponseCaching(options =>
            {
                options.UseCaseSensitivePaths = false;
            });

            services.AddMemoryCache();

            services.AddAntiforgery(o =>
            {
                o.HeaderName         = "XSRF-ZEC-TOKEN-HEADER";
                o.Cookie.Name        = "XSRF-ZEC-TOKEN";
                o.FormFieldName      = "XSRF-ZEC-TOKEN-FORM";
                o.Cookie.HttpOnly    = true;
                o.Cookie.IsEssential = true;
                o.Cookie.SameSite    = SameSiteMode.Strict;
            });

            #endregion

            #region AutoMapper

            services.AddAutoMapper(typeof(Startup));

            #endregion

            #region Markup Minification

            services.AddWebMarkupMin(options =>
            {
                options.AllowCompressionInDevelopmentEnvironment  = false;
                options.AllowMinificationInDevelopmentEnvironment = false;
                options.DefaultEncoding             = Encoding.UTF8;
                options.DisablePoweredByHttpHeaders = true;
            }).AddHtmlMinification(options =>
            {
                HtmlMinificationSettings settings          = options.MinificationSettings;
                settings.RemoveRedundantAttributes         = true;
                settings.RemoveHttpProtocolFromAttributes  = true;
                settings.RemoveHttpsProtocolFromAttributes = true;

                options.CssMinifierFactory = new NUglifyCssMinifierFactory();
                options.JsMinifierFactory  = new NUglifyJsMinifierFactory();
            })
            .AddHttpCompression(options =>
            {
                options.CompressorFactories = new List <ICompressorFactory>
                {
                    new BrotliCompressorFactory(new BrotliCompressionSettings
                    {
                        Level = 4
                    }),
                    new DeflateCompressorFactory(new DeflateCompressionSettings
                    {
                        Level = CompressionLevel.Fastest
                    }),
                    new GZipCompressorFactory(new GZipCompressionSettings
                    {
                        Level = CompressionLevel.Fastest
                    })
                };
            });

            #endregion

            #region Razor & Blazor config

            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddControllersWithViews(options =>
            {
                options.CacheProfiles.Add("Caching", new CacheProfile()
                {
                    Duration     = 120,
                    Location     = ResponseCacheLocation.Any,
                    VaryByHeader = "cookie"
                });
                options.CacheProfiles.Add("NoCaching", new CacheProfile()
                {
                    NoStore  = true,
                    Location = ResponseCacheLocation.None
                });
            }).AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            })
            .AddRazorRuntimeCompilation()
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                                                          factory.Create(typeof(SharedResources));
            });

            #endregion

            #region Localization

            services.AddLocalization(L => L.ResourcesPath = "Localization/Resources");

            #endregion

            #region HSTS

            services.AddHsts(options =>
            {
                options.Preload           = true;
                options.IncludeSubDomains = true;
                options.MaxAge            = TimeSpan.FromDays(365);
            });

            #endregion

            #region Logging

            services.AddLogging();

            #endregion

            #region Other services

            services.Configure <WebEncoderOptions>(options =>
            {
                options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);
            });

            #endregion
        }
Пример #25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.

            // Add the localization services to the services container
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            //services.AddWebMarkupMin(
            //       options =>
            //       {
            //           options.AllowMinificationInDevelopmentEnvironment = true;
            //           options.AllowCompressionInDevelopmentEnvironment = true;
            //       })
            //       .AddHtmlMinification(
            //           options =>
            //           {
            //               options.MinificationSettings.RemoveRedundantAttributes = true;
            //               options.MinificationSettings.RemoveHttpProtocolFromAttributes = true;
            //               options.MinificationSettings.RemoveHttpsProtocolFromAttributes = true;
            //           })
            //       .AddHttpCompression();

            //services.Configure<GzipCompressionProviderOptions>
            //   (options => options.Level = CompressionLevel.Optimal);
            //        services.AddResponseCompression(options =>
            //        {
            //            options.Providers.Add<GzipCompressionProvider>();
            //        });

            // Add WebMarkupMin services.
            services.AddWebMarkupMin(options =>
            {
                options.AllowMinificationInDevelopmentEnvironment = true;
                options.AllowCompressionInDevelopmentEnvironment  = true;
            })
            .AddHtmlMinification(options =>
            {
                HtmlMinificationSettings settings          = options.MinificationSettings;
                settings.RemoveRedundantAttributes         = true;
                settings.RemoveHttpProtocolFromAttributes  = true;
                settings.RemoveHttpsProtocolFromAttributes = true;
            })
            .AddXhtmlMinification(options =>
            {
                XhtmlMinificationSettings settings         = options.MinificationSettings;
                settings.RemoveRedundantAttributes         = true;
                settings.RemoveHttpProtocolFromAttributes  = true;
                settings.RemoveHttpsProtocolFromAttributes = true;

                options.CssMinifierFactory = new KristensenCssMinifierFactory();
                options.JsMinifierFactory  = new CrockfordJsMinifierFactory();
            })
            .AddXmlMinification(options =>
            {
                XmlMinificationSettings settings    = options.MinificationSettings;
                settings.CollapseTagsWithoutContent = true;
            })
            .AddHttpCompression(options =>
            {
                options.CompressorFactories = new List <ICompressorFactory>
                {
                    new DeflateCompressorFactory(new DeflateCompressionSettings
                    {
                        Level = CompressionLevel.Fastest
                    }),
                    new GZipCompressorFactory(new GZipCompressionSettings
                    {
                        Level = CompressionLevel.Fastest
                    })
                };
            });

            services.AddMvc()
            // Add support for finding localized views, based on file name suffix, e.g. Index.fr.cshtml
            .AddViewLocalization(
                LanguageViewLocationExpanderFormat.Suffix,
                opts => { opts.ResourcesPath = "Resources"; }
                )
            // Add support for localizing strings in data annotations (e.g. validation messages) via the
            // IStringLocalizer abstractions.
            .AddDataAnnotationsLocalization();

            // Configure supported cultures and localization options
            services.Configure <RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new[]
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("pt-BR")
                };

                // State what the default culture for your application is. This will be used if no specific culture
                // can be determined for a given request.
                options.DefaultRequestCulture = new RequestCulture(CultureInfo.CurrentCulture);//culture: "en-US", uiCulture: "en-US");

                // You must explicitly state which cultures your application supports.
                // These are the cultures the app supports for formatting numbers, dates, etc.
                options.SupportedCultures = supportedCultures;

                // These are the cultures the app supports for UI strings, i.e. we have localized resources for.
                options.SupportedUICultures = supportedCultures;

                // You can change which providers are configured to determine the culture for requests, or even add a custom
                // provider with your own logic. The providers will be asked in order to provide a culture for each request,
                // and the first to provide a non-null result that is in the configured supported cultures list will be used.
                // By default, the following built-in providers are configured:
                // - QueryStringRequestCultureProvider, sets culture via "culture" and "ui-culture" query string values, useful for testing
                // - CookieRequestCultureProvider, sets culture via "ASPNET_CULTURE" cookie
                // - AcceptLanguageHeaderRequestCultureProvider, sets culture via the "Accept-Language" request header
                //options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
                //{
                //  // My custom request culture logic
                //  return new ProviderCultureResult("en");
                //}));
            });
        }
Пример #26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(Configuration);

            // Add response caching service.
            services.AddResponseCaching();

            // Add WebMarkupMin services to the services container.
            services.AddWebMarkupMin(options =>
            {
                options.AllowMinificationInDevelopmentEnvironment = true;
                options.AllowCompressionInDevelopmentEnvironment  = true;
            })
            .AddHtmlMinification(options =>
            {
                options.ExcludedPages = new List <IUrlMatcher>
                {
                    new RegexUrlMatcher(@"^/minifiers/x(?:ht)?ml-minifier$"),
                    new ExactUrlMatcher("/contact")
                };

                HtmlMinificationSettings settings          = options.MinificationSettings;
                settings.RemoveRedundantAttributes         = true;
                settings.RemoveHttpProtocolFromAttributes  = true;
                settings.RemoveHttpsProtocolFromAttributes = true;

                options.CssMinifierFactory = new NUglifyCssMinifierFactory();
                options.JsMinifierFactory  = new NUglifyJsMinifierFactory();
            })
            .AddXhtmlMinification(options =>
            {
                options.IncludedPages = new List <IUrlMatcher>
                {
                    new RegexUrlMatcher(@"^/minifiers/x(?:ht)?ml-minifier$"),
                    new ExactUrlMatcher("/contact")
                };

                XhtmlMinificationSettings settings         = options.MinificationSettings;
                settings.RemoveRedundantAttributes         = true;
                settings.RemoveHttpProtocolFromAttributes  = true;
                settings.RemoveHttpsProtocolFromAttributes = true;

                options.CssMinifierFactory = new KristensenCssMinifierFactory();
                options.JsMinifierFactory  = new CrockfordJsMinifierFactory();
            })
            .AddXmlMinification(options =>
            {
                XmlMinificationSettings settings    = options.MinificationSettings;
                settings.CollapseTagsWithoutContent = true;
            })
            .AddHttpCompression(options =>
            {
                options.CompressorFactories = new List <ICompressorFactory>
                {
                    new BrotliCompressorFactory(new BrotliCompressionSettings
                    {
                        Level = 1
                    }),
                    new DeflateCompressorFactory(new DeflateCompressionSettings
                    {
                        Level = CompressionLevel.Fastest
                    }),
                    new GZipCompressorFactory(new GZipCompressionSettings
                    {
                        Level = CompressionLevel.Fastest
                    })
                };
            })
            ;

            // Override the default logger for WebMarkupMin.
            services.AddSingleton <IWmmLogger, WmmThrowExceptionLogger>();

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            // Add framework services.
            services.AddMvc(options =>
            {
                options.CacheProfiles.Add("CacheCompressedContent5Minutes",
                                          new CacheProfile
                {
                    NoStore      = HostingEnvironment.IsDevelopment(),
                    Duration     = 300,
                    Location     = ResponseCacheLocation.Any,
                    VaryByHeader = "Accept-Encoding"
                }
                                          );
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // Add WebMarkupMin sample services to the services container.
            services.AddSingleton <SitemapService>();
            services.AddSingleton <CssMinifierFactory>();
            services.AddSingleton <JsMinifierFactory>();
            services.AddSingleton <HtmlMinificationService>();
            services.AddSingleton <XhtmlMinificationService>();
            services.AddSingleton <XmlMinificationService>();
        }
Пример #27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(Configuration);

            // Add WebMarkupMin services to the services container.
            services.AddWebMarkupMin(options =>
            {
                options.AllowMinificationInDevelopmentEnvironment = true;
                options.AllowCompressionInDevelopmentEnvironment  = true;
            })
            .AddHtmlMinification(options =>
            {
                options.ExcludedPages = new List <IUrlMatcher>
                {
                    new WildcardUrlMatcher("/minifiers/x*ml-minifier"),
                    new ExactUrlMatcher("/contact")
                };

                HtmlMinificationSettings settings          = options.MinificationSettings;
                settings.RemoveRedundantAttributes         = true;
                settings.RemoveHttpProtocolFromAttributes  = true;
                settings.RemoveHttpsProtocolFromAttributes = true;

                options.CssMinifierFactory = new MsAjaxCssMinifierFactory();
                options.JsMinifierFactory  = new MsAjaxJsMinifierFactory();
            })
            .AddXhtmlMinification(options =>
            {
                options.IncludedPages = new List <IUrlMatcher>
                {
                    new WildcardUrlMatcher("/minifiers/x*ml-minifier"),
                    new ExactUrlMatcher("/contact")
                };

                XhtmlMinificationSettings settings         = options.MinificationSettings;
                settings.RemoveRedundantAttributes         = true;
                settings.RemoveHttpProtocolFromAttributes  = true;
                settings.RemoveHttpsProtocolFromAttributes = true;

                options.CssMinifierFactory = new YuiCssMinifierFactory();
                options.JsMinifierFactory  = new YuiJsMinifierFactory();
            })
            .AddXmlMinification(options =>
            {
                XmlMinificationSettings settings    = options.MinificationSettings;
                settings.CollapseTagsWithoutContent = true;
            })
            .AddHttpCompression(options =>
            {
                options.CompressorFactories = new List <ICompressorFactory>
                {
                    new BrotliCompressorFactory(new BrotliCompressionSettings
                    {
                        Level = 1
                    }),
                    new DeflateCompressorFactory(new DeflateCompressionSettings
                    {
                        Level = CompressionLevel.Fastest
                    }),
                    new GZipCompressorFactory(new GZipCompressionSettings
                    {
                        Level = CompressionLevel.Fastest
                    })
                };
            })
            ;

            // Override the default logger for WebMarkupMin.
            services.AddSingleton <IWmmLogger, WmmThrowExceptionLogger>();

            // Add framework services.
            var manager = new ApplicationPartManager();

            manager.ApplicationParts.Add(new AssemblyPart(typeof(Startup).Assembly));

            services.AddSingleton(manager);

            services.AddMvc(options =>
            {
                options.CacheProfiles.Add("CacheCompressedContent5Minutes",
                                          new CacheProfile
                {
                    NoStore      = HostingEnvironment.IsDevelopment(),
                    Duration     = 300,
                    Location     = ResponseCacheLocation.Client,
                    VaryByHeader = "Accept-Encoding"
                }
                                          );
            });

            // Add WebMarkupMin sample services to the services container.
            services.AddSingleton <SitemapService>();
            services.AddSingleton <CssMinifierFactory>();
            services.AddSingleton <JsMinifierFactory>();
            services.AddSingleton <HtmlMinificationService>();
            services.AddSingleton <XhtmlMinificationService>();
            services.AddSingleton <XmlMinificationService>();
        }
Пример #28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(Configuration);

            // Add WebMarkupMin services to the services container.
            services.AddWebMarkupMin(options =>
            {
                options.AllowMinificationInDevelopmentEnvironment = true;
                options.AllowCompressionInDevelopmentEnvironment  = true;
            })
            .AddHtmlMinification(options =>
            {
                options.ExcludedPages = new List <IUrlMatcher>
                {
                    new RegexUrlMatcher(@"^/minifiers/x(?:ht)?ml-minifier$"),
                    new ExactUrlMatcher("/contact")
                };

                HtmlMinificationSettings settings          = options.MinificationSettings;
                settings.RemoveRedundantAttributes         = true;
                settings.RemoveHttpProtocolFromAttributes  = true;
                settings.RemoveHttpsProtocolFromAttributes = true;

                options.CssMinifierFactory = new NUglifyCssMinifierFactory();
                options.JsMinifierFactory  = new NUglifyJsMinifierFactory();
            })
            .AddXhtmlMinification(options =>
            {
                options.IncludedPages = new List <IUrlMatcher>
                {
                    new RegexUrlMatcher(@"^/minifiers/x(?:ht)?ml-minifier$"),
                    new ExactUrlMatcher("/contact")
                };

                XhtmlMinificationSettings settings         = options.MinificationSettings;
                settings.RemoveRedundantAttributes         = true;
                settings.RemoveHttpProtocolFromAttributes  = true;
                settings.RemoveHttpsProtocolFromAttributes = true;

                options.CssMinifierFactory = new KristensenCssMinifierFactory();
                options.JsMinifierFactory  = new CrockfordJsMinifierFactory();
            })
            .AddXmlMinification(options =>
            {
                XmlMinificationSettings settings    = options.MinificationSettings;
                settings.CollapseTagsWithoutContent = true;
            })
            .AddHttpCompression(options =>
            {
                options.CompressorFactories = new List <ICompressorFactory>
                {
                    new DeflateCompressorFactory(new DeflateCompressionSettings
                    {
                        Level = CompressionLevel.Fastest
                    }),
                    new GZipCompressorFactory(new GZipCompressionSettings
                    {
                        Level = CompressionLevel.Fastest
                    })
                };
            })
            ;

            // Add framework services.
            services.AddMvc(options =>
            {
                options.CacheProfiles.Add("CacheCompressedContent5Minutes",
                                          new CacheProfile
                {
                    NoStore      = HostingEnvironment.IsDevelopment(),
                    Duration     = 300,
                    Location     = ResponseCacheLocation.Client,
                    VaryByHeader = "Accept-Encoding"
                }
                                          );
            });

            // Add WebMarkupMin sample services to the services container.
            services.AddSingleton <SitemapService>();
            services.AddSingleton <CssMinifierFactory>();
            services.AddSingleton <JsMinifierFactory>();
            services.AddSingleton <HtmlMinificationService>();
            services.AddSingleton <XhtmlMinificationService>();
            services.AddSingleton <XmlMinificationService>();
        }