/// <summary>
        /// Logs a information about the error
        /// </summary>
        /// <param name="category">Error category</param>
        /// <param name="message">Error message</param>
        /// <param name="filePath">File path</param>
        /// <param name="lineNumber">Line number on which the error occurred</param>
        /// <param name="columnNumber">Column number on which the error occurred</param>
        /// <param name="sourceFragment">Fragment of source code</param>
        public override void Error(string category, string message, string filePath = "",
                                   int lineNumber = 0, int columnNumber = 0, string sourceFragment = "")
        {
            StringBuilder errorBuilder = StringBuilderPool.GetBuilder();

            errorBuilder.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_Category, category);
            errorBuilder.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_Message, message);

            if (!string.IsNullOrWhiteSpace(filePath))
            {
                errorBuilder.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_File, filePath);
            }

            if (lineNumber > 0)
            {
                errorBuilder.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_LineNumber, lineNumber);
            }

            if (columnNumber > 0)
            {
                errorBuilder.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_ColumnNumber, columnNumber);
            }

            if (!string.IsNullOrWhiteSpace(sourceFragment))
            {
                errorBuilder.AppendFormatLine("{1}:{0}{0}{2}", Environment.NewLine,
                                              Strings.ErrorDetails_SourceFragment, sourceFragment);
            }

            string errorMessage = errorBuilder.ToString();

            StringBuilderPool.ReleaseBuilder(errorBuilder);

            throw new MarkupMinificationException(errorMessage);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Converts a string to an XML-encoded string
        /// </summary>
        /// <param name="value">The string to encode</param>
        /// <returns>The encoded string</returns>
        public static string XmlAttributeEncode(string value)
        {
            if (string.IsNullOrWhiteSpace(value) || !ContainsXmlAttributeEncodingChars(value))
            {
                return(value);
            }

            string        result;
            StringBuilder sb = StringBuilderPool.GetBuilder();

            using (var writer = new StringWriter(sb))
            {
                int charCount = value.Length;

                for (int charIndex = 0; charIndex < charCount; charIndex++)
                {
                    char charValue = value[charIndex];

                    switch (charValue)
                    {
                    case '"':
                        writer.Write("&quot;");
                        break;

                    case '&':
                        writer.Write("&amp;");
                        break;

                    case '<':
                        writer.Write("&lt;");
                        break;

                    case '>':
                        writer.Write("&gt;");
                        break;

                    default:
                        writer.Write(charValue);
                        break;
                    }
                }

                writer.Flush();

                result = writer.ToString();
            }

            StringBuilderPool.ReleaseBuilder(sb);

            return(result);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Removes a comments and unnecessary whitespace from JavaScript code
        /// </summary>
        /// <param name="content">JavaScript content</param>
        /// <returns>Minified JavaScript content</returns>
        public String Minify(string content)
        {
            string minifiedContent;

            lock (_minificationSynchronizer)
            {
                _theA         = 0;
                _theB         = 0;
                _theLookahead = EOF;
                _theX         = EOF;
                _theY         = EOF;

                int           estimatedCapacity = (int)Math.Floor(content.Length * AVERAGE_COMPRESSION_RATIO);
                StringBuilder sb = StringBuilderPool.GetBuilder(estimatedCapacity);
                _reader = new StringReader(content);
                _writer = new StringWriter(sb);

                try
                {
                    InnerMinify();
                    _writer.Flush();

                    minifiedContent = sb.TrimStart().ToString();
                }
                catch (JsMinificationException)
                {
                    throw;
                }
                finally
                {
                    _reader.Dispose();
                    _reader = null;

                    _writer.Dispose();
                    _writer = null;

                    StringBuilderPool.ReleaseBuilder(sb);
                }
            }

            return(minifiedContent);
        }
        /// <summary>
        /// Returns a string that represents the HTML attribute expression
        /// </summary>
        /// <returns>A string that represents the HTML attribute expression</returns>
        public override string ToString()
        {
            StringBuilder sb = StringBuilderPool.GetBuilder();

            if (!string.IsNullOrEmpty(_tagNameInLowercase))
            {
                sb.Append(_tagNameInLowercase);
            }
            sb.Append("[");
            sb.Append(Regex.Escape(_attributeNameInLowercase));
            if (_attributeValue != null)
            {
                string quote = GetQuoteForAttributeValue(_attributeValue);

                sb.Append("=");
                if (quote.Length > 0)
                {
                    sb.Append(quote);
                }
                sb.Append(Regex.Escape(_attributeValue));
                if (quote.Length > 0)
                {
                    sb.Append(quote);
                }
                if (_caseInsensitive)
                {
                    sb.Append(" i");
                }
            }
            sb.Append("]");

            string attributeExpressionString = sb.ToString();

            StringBuilderPool.ReleaseBuilder(sb);

            return(attributeExpressionString);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Converts a string to an HTML-encoded string
        /// </summary>
        /// <param name="value">The string to encode</param>
        /// <param name="attributeQuotesType">HTML attribute quotes type</param>
        /// <returns>The encoded string</returns>
        public static string HtmlAttributeEncode(string value,
                                                 HtmlAttributeQuotesType attributeQuotesType = HtmlAttributeQuotesType.Double)
        {
            char   quoteCharValue     = '"';
            string quoteCharReference = "&#34;";             // use `&#34;` instead of `&quot;`, because it is shorter

            if (attributeQuotesType == HtmlAttributeQuotesType.Single)
            {
                quoteCharValue     = '\'';
                quoteCharReference = "&#39;";
            }

            if (string.IsNullOrWhiteSpace(value) || !ContainsHtmlAttributeEncodingChars(value, quoteCharValue))
            {
                return(value);
            }

            string        result;
            StringBuilder sb = StringBuilderPool.GetBuilder();

            using (var writer = new StringWriter(sb))
            {
                int charCount = value.Length;

                for (int charIndex = 0; charIndex < charCount; charIndex++)
                {
                    char charValue = value[charIndex];

                    switch (charValue)
                    {
                    case '"':
                    case '\'':
                        if (charValue == quoteCharValue)
                        {
                            writer.Write(quoteCharReference);
                        }
                        else
                        {
                            writer.Write(charValue);
                        }

                        break;

                    case '&':
                        writer.Write("&amp;");
                        break;

                    case '<':
                        writer.Write("&lt;");
                        break;

                    default:
                        writer.Write(charValue);
                        break;
                    }
                }

                writer.Flush();

                result = writer.ToString();
            }

            StringBuilderPool.ReleaseBuilder(sb);

            return(result);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Minify XML content
        /// </summary>
        /// <param name="content">XML content</param>
        /// <param name="fileContext">File context</param>
        /// <param name="encoding">Text encoding</param>
        /// <param name="generateStatistics">Flag for whether to allow generate minification statistics</param>
        /// <returns>Minification result</returns>
        public MarkupMinificationResult Minify(string content, string fileContext, Encoding encoding,
                                               bool generateStatistics)
        {
            MinificationStatistics statistics = null;
            string cleanedContent             = Utils.RemoveByteOrderMark(content);
            string minifiedContent            = string.Empty;
            var    errors = new List <MinificationErrorInfo>();

            lock (_minificationSynchronizer)
            {
                try
                {
                    if (generateStatistics)
                    {
                        statistics = new MinificationStatistics(encoding);
                        statistics.Init(cleanedContent);
                    }

                    int estimatedCapacity = (int)Math.Floor(cleanedContent.Length * AVERAGE_COMPRESSION_RATIO);
                    _result = StringBuilderPool.GetBuilder(estimatedCapacity);

                    _xmlParser.Parse(cleanedContent);

                    FlushBuffer();

                    if (_errors.Count == 0)
                    {
                        minifiedContent = _result.ToString();

                        if (generateStatistics)
                        {
                            statistics.End(minifiedContent);
                        }
                    }
                }
                catch (XmlParsingException e)
                {
                    WriteError(LogCategoryConstants.XmlParsingError, e.Message, fileContext,
                               e.LineNumber, e.ColumnNumber, e.SourceFragment);
                }
                finally
                {
                    StringBuilderPool.ReleaseBuilder(_result);
                    _buffer.Clear();
                    _currentNodeType = XmlNodeType.Unknown;
                    _currentText     = string.Empty;

                    errors.AddRange(_errors);
                    _errors.Clear();
                }

                if (errors.Count == 0)
                {
                    _logger.Info(LogCategoryConstants.XmlMinificationSuccess,
                                 string.Format(Strings.SuccesMessage_MarkupMinificationComplete, "XML"),
                                 fileContext, statistics);
                }
            }

            return(new MarkupMinificationResult(minifiedContent, errors, statistics));
        }
Exemplo n.º 7
0
        private static string ConvertXmlReader(XmlReader xmlReader, string resourceName,
                                               string resourceNamespace, bool internalAccessModifier)
        {
            string accessModifier   = internalAccessModifier ? "internal" : "public";
            var    resourceDataList = new List <ResourceData>();

            try
            {
                while (xmlReader.Read())
                {
                    if (xmlReader.Depth == 1 &&
                        xmlReader.NodeType == XmlNodeType.Element &&
                        xmlReader.Name == "data")
                    {
                        var resourceData = new ResourceData();
                        int attrCount    = xmlReader.AttributeCount;

                        for (int attrIndex = 0; attrIndex < attrCount; attrIndex++)
                        {
                            xmlReader.MoveToAttribute(attrIndex);
                            if (xmlReader.Name == "name")
                            {
                                resourceData.Name = xmlReader.Value;
                                break;
                            }
                        }

                        if (xmlReader.ReadToFollowing("value"))
                        {
                            resourceData.Value = xmlReader.ReadElementContentAsString();
                        }

                        resourceDataList.Add(resourceData);
                    }
                }
            }
            catch (XmlException e)
            {
                throw new ResxConversionException(
                          string.Format("During parsing the Resx code an error occurred: {0}", e.Message), e);
            }
            catch
            {
                throw;
            }

            var outputBuilder = StringBuilderPool.GetBuilder();

            outputBuilder.AppendFormat(
                @"//------------------------------------------------------------------------------
// <auto-generated>
//	 This code was generated by a tool.
//
//	 Changes to this file may cause incorrect behavior and will be lost if
//	 the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace {1}
{{
	using System;
	using System.Globalization;
	using System.Reflection;
	using System.Resources;

	/// <summary>
	/// A strongly-typed resource class, for looking up localized strings, etc.
	/// </summary>
	{2} class {0}
	{{
		private static Lazy<ResourceManager> _resourceManager =
			new Lazy<ResourceManager>(() => new ResourceManager(
				""{1}.{0}"",
#if NET40
				typeof({0}).Assembly
#else
				typeof({0}).GetTypeInfo().Assembly
#endif
			));

		private static CultureInfo _resourceCulture;

		/// <summary>
		/// Returns a cached ResourceManager instance used by this class
		/// </summary>
		{2} static ResourceManager ResourceManager
		{{
			get
			{{
				return _resourceManager.Value;
			}}
		}}

		/// <summary>
		/// Overrides a current thread's CurrentUICulture property for all
		/// resource lookups using this strongly typed resource class
		/// </summary>
		{2} static CultureInfo Culture
		{{
			get
			{{
				return _resourceCulture;
			}}
			set
			{{
				_resourceCulture = value;
			}}
		}}
", resourceName, resourceNamespace, accessModifier);

            foreach (ResourceData resourceData in resourceDataList)
            {
                outputBuilder.AppendLine();
                RenderProperty(outputBuilder, resourceData, accessModifier);
            }

            outputBuilder.Append(@"
		private static string GetString(string name)
		{
			string value = ResourceManager.GetString(name, _resourceCulture);

			return value;
		}
	}
}");

            string output = outputBuilder.ToString();

            StringBuilderPool.ReleaseBuilder(outputBuilder);

            return(output);
        }