internal XmlCharCheckingWriter(XmlWriter baseWriter, bool checkValues, bool checkNames, bool replaceNewLines, string newLineChars) : base(baseWriter)
 {
     this.checkValues = checkValues;
     this.checkNames = checkNames;
     this.replaceNewLines = replaceNewLines;
     this.newLineChars = newLineChars;
     if (checkValues)
     {
         this.xmlCharType = XmlCharType.Instance;
     }
 }
 internal XmlCharCheckingReader(XmlReader reader, bool checkCharacters, bool ignoreWhitespace, bool ignoreComments, bool ignorePis, DtdProcessing dtdProcessing) : base(reader)
 {
     this.state = State.Initial;
     this.checkCharacters = checkCharacters;
     this.ignoreWhitespace = ignoreWhitespace;
     this.ignoreComments = ignoreComments;
     this.ignorePis = ignorePis;
     this.dtdProcessing = dtdProcessing;
     this.lastNodeType = XmlNodeType.None;
     if (checkCharacters)
     {
         this.xmlCharType = XmlCharType.Instance;
     }
 }
Esempio n. 3
0
        // 
        // Constructor
        //
        internal XmlCharCheckingWriter(XmlWriter baseWriter, bool checkValues, bool checkNames, bool replaceNewLines, string newLineChars)
            : base(baseWriter)
        {
            Debug.Assert(checkValues || replaceNewLines);
            _checkValues = checkValues;
            _checkNames = checkNames;
            _replaceNewLines = replaceNewLines;
            _newLineChars = newLineChars;

            if (checkValues)
            {
                _xmlCharType = XmlCharType.Instance;
            }
        }
 internal XmlTextWriter()
 {
     this.xmlCharType = XmlCharType.Instance;
     this.namespaces = true;
     this.formatting = System.Xml.Formatting.None;
     this.indentation = 2;
     this.indentChar = ' ';
     this.nsStack = new Namespace[8];
     this.nsTop = -1;
     this.stack = new TagInfo[10];
     this.top = 0;
     this.stack[this.top].Init(-1);
     this.quoteChar = '"';
     this.stateTable = stateTableDefault;
     this.currentState = State.Start;
     this.lastToken = Token.Empty;
 }
//
// Constructor
//
        internal XmlCharCheckingReader( XmlReader reader, bool checkCharacters, bool ignoreWhitespace, bool ignoreComments, bool ignorePis, DtdProcessing dtdProcessing ) 
            : base( reader ) {

            Debug.Assert( checkCharacters || ignoreWhitespace || ignoreComments || ignorePis || (int)dtdProcessing != -1 );

            state = State.Initial;

            this.checkCharacters = checkCharacters;
            this.ignoreWhitespace = ignoreWhitespace;
            this.ignoreComments = ignoreComments;
            this.ignorePis = ignorePis;
            this.dtdProcessing = dtdProcessing;

            lastNodeType = XmlNodeType.None;

            if ( checkCharacters ) {
                xmlCharType = XmlCharType.Instance;
            }
        }
 protected XmlEncodedRawTextWriter(XmlWriterSettings settings)
 {
     this.xmlCharType = XmlCharType.Instance;
     this.bufPos = 1;
     this.textPos = 1;
     this.bufLen = 0x1800;
     this.newLineHandling = settings.NewLineHandling;
     this.omitXmlDeclaration = settings.OmitXmlDeclaration;
     this.newLineChars = settings.NewLineChars;
     this.checkCharacters = settings.CheckCharacters;
     this.closeOutput = settings.CloseOutput;
     this.standalone = settings.Standalone;
     this.outputMethod = settings.OutputMethod;
     this.mergeCDataSections = settings.MergeCDataSections;
     if (this.checkCharacters && (this.newLineHandling == NewLineHandling.Replace))
     {
         this.ValidateContentChars(this.newLineChars, "NewLineChars", false);
     }
 }
 internal XsdValidatingReader(XmlReader reader, XmlResolver xmlResolver, XmlReaderSettings readerSettings, XmlSchemaObject partialValidationType)
 {
     this.xmlCharType = XmlCharType.Instance;
     this.coreReader = reader;
     this.coreReaderNSResolver = reader as IXmlNamespaceResolver;
     this.lineInfo = reader as IXmlLineInfo;
     this.coreReaderNameTable = this.coreReader.NameTable;
     if (this.coreReaderNSResolver == null)
     {
         this.nsManager = new XmlNamespaceManager(this.coreReaderNameTable);
         this.manageNamespaces = true;
     }
     this.thisNSResolver = this;
     this.xmlResolver = xmlResolver;
     this.processInlineSchema = (readerSettings.ValidationFlags & XmlSchemaValidationFlags.ProcessInlineSchema) != XmlSchemaValidationFlags.None;
     this.Init();
     this.SetupValidator(readerSettings, reader, partialValidationType);
     this.validationEvent = readerSettings.GetEventHandler();
 }
//
// Constructor
//
        internal XmlCharCheckingReader( XmlReader reader, bool checkCharacters, bool ignoreWhitespace, bool ignoreComments, bool ignorePis, bool prohibitDtd ) 
            : base( reader ) {

            Debug.Assert( checkCharacters || ignoreWhitespace || ignoreComments || ignorePis || prohibitDtd );

            state = State.Initial;

            this.checkCharacters = checkCharacters;
            this.ignoreWhitespace = ignoreWhitespace;
            this.ignoreComments = ignoreComments;
            this.ignorePis = ignorePis;
            this.prohibitDtd = prohibitDtd;

            lastNodeType = XmlNodeType.None;

            if ( checkCharacters ) {
                xmlCharType = XmlCharType.Instance;
            }
        }
Esempio n. 9
0
        internal static void VerifyCharData(char[] data, int offset, int len, ExceptionType exceptionType)
        {
            if (data == null || len == 0)
            {
                return;
            }

            int i      = offset;
            int endPos = offset + len;

            for (; ;)
            {
                while (i < endPos && s_xmlCharType.IsCharData(data[i]))
                {
                    i++;
                }
                if (i == endPos)
                {
                    return;
                }

                char ch = data[i];
                if (XmlCharType.IsHighSurrogate(ch))
                {
                    if (i + 1 == endPos)
                    {
                        throw CreateException(SR.Xml_InvalidSurrogateMissingLowChar, exceptionType, 0, offset - i + 1);
                    }
                    ch = data[i + 1];
                    if (XmlCharType.IsLowSurrogate(ch))
                    {
                        i += 2;
                        continue;
                    }
                    else
                    {
                        throw CreateInvalidSurrogatePairException(data[i + 1], data[i], exceptionType, 0, offset - i + 1);
                    }
                }
                throw CreateInvalidCharException(data, len, i, exceptionType);
            }
        }
Esempio n. 10
0
        internal static void VerifyCharData(string data, ExceptionType invCharExceptionType, ExceptionType invSurrogateExceptionType)
        {
            if (data == null || data.Length == 0)
            {
                return;
            }

            int i   = 0;
            int len = data.Length;

            for (; ;)
            {
                while (i < len && s_xmlCharType.IsCharData(data[i]))
                {
                    i++;
                }
                if (i == len)
                {
                    return;
                }

                char ch = data[i];
                if (XmlCharType.IsHighSurrogate(ch))
                {
                    if (i + 1 == len)
                    {
                        throw CreateException(SR.Xml_InvalidSurrogateMissingLowChar, invSurrogateExceptionType, 0, i + 1);
                    }
                    ch = data[i + 1];
                    if (XmlCharType.IsLowSurrogate(ch))
                    {
                        i += 2;
                        continue;
                    }
                    else
                    {
                        throw CreateInvalidSurrogatePairException(data[i + 1], data[i], invSurrogateExceptionType, 0, i + 1);
                    }
                }
                throw CreateInvalidCharException(data, i, invCharExceptionType);
            }
        }
Esempio n. 11
0
        public static unsafe void VerifyCharData(string data, ExceptionType invCharExceptionType, ExceptionType invSurrogateExceptionType)
        {
            if (string.IsNullOrEmpty(data))
            {
                return;
            }

            int i   = 0;
            int len = data.Length;

            for (; ;)
            {
                while (i < len && (xmlCharType.charProperties[data[i]] & XmlCharType.fCharData) != 0)
                {
                    i++;
                }
                if (i == len)
                {
                    return;
                }

                char ch = data[i];
                if (XmlCharType.IsHighSurrogate(ch))
                {
                    if (i + 1 == len)
                    {
                        throw CreateException(SR.Xml_InvalidSurrogateMissingLowChar, invSurrogateExceptionType, 0, i + 1);
                    }
                    ch = data[i + 1];
                    if (XmlCharType.IsLowSurrogate(ch))
                    {
                        i += 2;
                        continue;
                    }
                    else
                    {
                        throw CreateInvalidSurrogatePairException(data[i + 1], data[i], invSurrogateExceptionType, 0, i + 1);
                    }
                }
                throw CreateInvalidCharException(data, i, invCharExceptionType);
            }
        }
Esempio n. 12
0
        internal unsafe void EncodeChar(ref char *pSrc, char *pSrcEnd, ref byte *pDst)
        {
            int ch = (int)pSrc;

            if (XmlCharType.IsSurrogate(ch))
            {
                pDst  = EncodeSurrogate(pSrc, pSrcEnd, pDst);
                pSrc += (IntPtr)4;
            }
            else if ((ch <= 0x7f) || (ch >= 0xfffe))
            {
                pDst  = this.InvalidXmlChar(ch, pDst, false);
                pSrc += (IntPtr)2;
            }
            else
            {
                pDst  = EncodeMultibyteUTF8(ch, pDst);
                pSrc += (IntPtr)2;
            }
        }
Esempio n. 13
0
        internal void WriteSurrogateCharEntity(char lowChar, char highChar)
        {
            if (!XmlCharType.IsLowSurrogate(lowChar) ||
                !XmlCharType.IsHighSurrogate(highChar))
            {
                throw XmlConvert.CreateInvalidSurrogatePairException(lowChar, highChar);
            }
            int surrogateChar = XmlCharType.CombineSurrogateChar(lowChar, highChar);

            if (_cacheAttrValue)
            {
                Debug.Assert(_attrValue != null);
                _attrValue.Append(highChar);
                _attrValue.Append(lowChar);
            }

            _textWriter.Write("&#x");
            _textWriter.Write(surrogateChar.ToString("X", NumberFormatInfo.InvariantInfo));
            _textWriter.Write(';');
        }
Esempio n. 14
0
        //
        // Constructor
        //
        internal XmlCharCheckingReader(XmlReader reader, bool checkCharacters, bool ignoreWhitespace, bool ignoreComments, bool ignorePis, DtdProcessing dtdProcessing)
            : base(reader)
        {
            Debug.Assert(checkCharacters || ignoreWhitespace || ignoreComments || ignorePis || (int)dtdProcessing != -1);

            _state = State.Initial;

            _checkCharacters  = checkCharacters;
            _ignoreWhitespace = ignoreWhitespace;
            _ignoreComments   = ignoreComments;
            _ignorePis        = ignorePis;
            _dtdProcessing    = dtdProcessing;

            _lastNodeType = XmlNodeType.None;

            if (checkCharacters)
            {
                _xmlCharType = XmlCharType.Instance;
            }
        }
Esempio n. 15
0
 internal static string[] BuildCharExceptionArgs(char invChar, char nextChar)
 {
     string[] strArray = new string[2];
     if (XmlCharType.IsHighSurrogate(invChar) && (nextChar != '\0'))
     {
         int num = XmlCharType.CombineSurrogateChar(nextChar, invChar);
         strArray[0] = new string(new char[] { invChar, nextChar });
         strArray[1] = string.Format(CultureInfo.InvariantCulture, "0x{0:X2}", new object[] { num });
         return(strArray);
     }
     if (invChar == '\0')
     {
         strArray[0] = ".";
     }
     else
     {
         strArray[0] = invChar.ToString(CultureInfo.InvariantCulture);
     }
     strArray[1] = string.Format(CultureInfo.InvariantCulture, "0x{0:X2}", new object[] { (int)invChar });
     return(strArray);
 }
Esempio n. 16
0
        public override void WriteWhitespace(string?ws)
        {
            ws ??= string.Empty;

            // "checkNames" is intentional here; if false, the whitespace is checked in XmlWellformedWriter
            if (_checkNames)
            {
                int i;
                if ((i = XmlCharType.IsOnlyWhitespaceWithPos(ws)) != -1)
                {
                    throw new ArgumentException(SR.Format(SR.Xml_InvalidWhitespaceCharacter, XmlException.BuildCharExceptionArgs(ws, i)));
                }
            }

            if (_replaceNewLines)
            {
                ws = ReplaceNewLines(ws);
            }

            writer.WriteWhitespace(ws);
        }
Esempio n. 17
0
        internal static unsafe void CharToUTF8(ref char *pSrc, char *pSrcEnd, ref byte *pDst)
        {
            int ch = (int)pSrc;

            if (ch <= 0x7f)
            {
                pDst  = (byte *)((byte)ch);
                pDst += (IntPtr)1;
                pSrc += (IntPtr)2;
            }
            else if (XmlCharType.IsSurrogate(ch))
            {
                pDst  = EncodeSurrogate(pSrc, pSrcEnd, pDst);
                pSrc += (IntPtr)4;
            }
            else
            {
                pDst  = EncodeMultibyteUTF8(ch, pDst);
                pSrc += (IntPtr)2;
            }
        }
Esempio n. 18
0
        //-----------------------------------------------
        // Nmtoken parsing (no XML namespaces support)
        //-----------------------------------------------
        /// <summary>
        /// Attempts to parse the input string as an Nmtoken (see the XML spec production [7]) without taking
        /// into account the XML Namespaces spec. What it means is that the ':' character is allowed at any
        /// position and any number of times in the token.
        /// Quits parsing when an invalid Nmtoken char is reached or the end of string is reached.
        /// Returns the number of valid Nmtoken chars that were parsed.
        /// </summary>
        internal static int ParseNmtokenNoNamespaces(string s, int offset)
        {
            Debug.Assert(s != null && offset <= s.Length);

            // Keep parsing until the end of string or an invalid Name character is reached
            int i = offset;

            while (i < s.Length)
            {
                if (XmlCharType.IsNameSingleChar(s[i]) || s[i] == ':')
                {
                    i++;
                }
                else
                {
                    break;
                }
            }

            return(i - offset);
        }
Esempio n. 19
0
        internal static Exception GetInvalidNameException(string s, int offsetStartChar, int offsetBadChar)
        {
            // If the name is empty, throw an exception
            if (offsetStartChar >= s.Length)
            {
                return(new XmlException(SR.Xml_EmptyName, string.Empty));
            }

            Debug.Assert(offsetBadChar < s.Length);

            if (XmlCharType.IsNCNameSingleChar(s[offsetBadChar]) && !XmlCharType.IsStartNCNameSingleChar(s[offsetBadChar]))
            {
                // The error character is a valid name character, but is not a valid start name character
                return(new XmlException(SR.Xml_BadStartNameChar, XmlException.BuildCharExceptionArgs(s, offsetBadChar)));
            }
            else
            {
                // The error character is an invalid name character
                return(new XmlException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(s, offsetBadChar)));
            }
        }
Esempio n. 20
0
        /// <include file='doc\XmlReader.uex' path='docs/doc[@for="XmlReader.IsNameToken"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public static bool IsNameToken(string str)
        {
            if (str == String.Empty)
            {
                return(false);
            }
            int i = str.Length - 1;

            while (i >= 0)
            {
                if (XmlCharType.IsNameChar(str[i]))
                {
                    i--;
                }
                else
                {
                    return(false);
                }
            }
            return(true);
        }
Esempio n. 21
0
 internal int IsOnlyCharData(string str)
 {
     if (str != null)
     {
         for (int i = 0; i < str.Length; i++)
         {
             if ((charProperties[str[i]] & fCharData) == 0)
             {
                 if (i + 1 >= str.Length || !(XmlCharType.IsHighSurrogate(str[i]) && XmlCharType.IsLowSurrogate(str[i + 1])))
                 {
                     return(i);
                 }
                 else
                 {
                     i++;
                 }
             }
         }
     }
     return(-1);
 }
Esempio n. 22
0
        internal override int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
        {
            uint code;
            int  i, j;

            byteCount += byteIndex;

            for (i = byteIndex, j = charIndex; i + 3 < byteCount;)
            {
                code = BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(i));
                if (code > 0x10FFFF)
                {
                    throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] {
                        i
                    }), (string?)null);
                }
                else if (code > 0xFFFF)
                {
                    Ucs4ToUTF16(code, chars, j);
                    j++;
                }
                else
                {
                    if (XmlCharType.IsSurrogate((int)code))
                    {
                        throw new XmlException(SR.Xml_InvalidCharInThisEncoding, string.Empty);
                    }
                    else
                    {
                        chars[j] = (char)code;
                    }
                }

                j++;
                i += 4;
            }

            return(j - charIndex);
        }
Esempio n. 23
0
        internal override int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
        {
            uint code;
            int  i, j;

            byteCount += byteIndex;

            for (i = byteIndex, j = charIndex; i + 3 < byteCount;)
            {
                code = (uint)((bytes[i + 2] << 24) | (bytes[i + 3] << 16) | (bytes[i] << 8) | bytes[i + 1]);
                if (code > 0x10FFFF)
                {
                    throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] {
                        i
                    }), (string?)null);
                }
                else if (code > 0xFFFF)
                {
                    Ucs4ToUTF16(code, chars, j);
                    j++;
                }
                else
                {
                    if (XmlCharType.IsSurrogate((int)code))
                    {
                        throw new XmlException(SR.Xml_InvalidCharInThisEncoding, string.Empty);
                    }
                    else
                    {
                        chars[j] = (char)code;
                    }
                }

                j++;
                i += 4;
            }

            return(j - charIndex);
        }
Esempio n. 24
0
        public override Task WriteDocTypeAsync(string name, string?pubid, string?sysid, string?subset)
        {
            if (_checkNames)
            {
                ValidateQName(name);
            }

            if (_checkValues)
            {
                if (pubid != null)
                {
                    int i;
                    if ((i = XmlCharType.IsPublicId(pubid)) >= 0)
                    {
                        throw XmlConvert.CreateInvalidCharException(pubid, i);
                    }
                }

                if (sysid != null)
                {
                    CheckCharacters(sysid);
                }

                if (subset != null)
                {
                    CheckCharacters(subset);
                }
            }

            if (_replaceNewLines)
            {
                sysid  = ReplaceNewLines(sysid);
                pubid  = ReplaceNewLines(pubid);
                subset = ReplaceNewLines(subset);
            }

            return(writer.WriteDocTypeAsync(name, pubid, sysid, subset));
        }
Esempio n. 25
0
        //-----------------------------------------------
        // NCName parsing
        //-----------------------------------------------

        // <summary>
        // Attempts to parse the input string as an NCName (see the XML Namespace spec).
        // Quits parsing when an invalid NCName char is reached or the end of string is reached.
        // Returns the number of valid NCName chars that were parsed.
        // </summary>
        public static unsafe int ParseNCName(string s, int offset)
        {
            int         offsetStart = offset;
            XmlCharType xmlCharType = XmlCharType.Instance;

            Debug.Assert(s != null && offset <= s.Length);

            // Quit if the first character is not a valid NCName starting character
            if (offset < s.Length &&
                (s[offset] > XmlCharType.MaxAsciiChar || (xmlCharType.charProperties[s[offset]] & XmlCharType.fNCStartName) != 0))
            { // xmlCharType.IsStartNCNameChar(s[offset])) {
                // Keep parsing until the end of string or an invalid NCName character is reached
                for (offset++; offset < s.Length; offset++)
                {
                    if (!(s[offset] > XmlCharType.MaxAsciiChar || (xmlCharType.charProperties[s[offset]] & XmlCharType.fNCName) != 0)) // if (!xmlCharType.IsNCNameChar(s[offset]))
                    {
                        break;
                    }
                }
            }

            return(offset - offsetStart);
        }
Esempio n. 26
0
        internal static string VerifyNMTOKEN(string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (name == string.Empty)
            {
                throw new XmlException(Res.Xml_InvalidNmToken, name);
            }
            int nameLength = name.Length;
            int position   = 0;

            while (position < nameLength)
            {
                if (!XmlCharType.IsNameChar(name[position]))
                {
                    throw new XmlException(Res.Xml_BadNameChar, XmlException.BuildCharExceptionStr(name[position]));
                }
                position++;
            }
            return(name);
        }
Esempio n. 27
0
        /// <include file='doc\XmlConvert.uex' path='docs/doc[@for="XmlConvert.VerifyNCName"]/*' />
        /// <devdoc>
        ///    <para>
        ///    </para>
        /// </devdoc>
        public static string VerifyNCName(string name)
        {
            if (name == null || name == string.Empty)
            {
                throw new ArgumentNullException("name");
            }

            if (!XmlCharType.IsStartNCNameChar(name[0]))
            {
                throw new XmlException(Res.Xml_BadStartNameChar, XmlException.BuildCharExceptionStr(name[0]));
            }
            int nameLength = name.Length;
            int position   = 1;

            while (position < nameLength)
            {
                if (!XmlCharType.IsNCNameChar(name[position]))
                {
                    throw new XmlException(Res.Xml_BadNameChar, XmlException.BuildCharExceptionStr(name[position]));
                }
                position++;
            }
            return(name);
        }
Esempio n. 28
0
        // Replaces \r\n, \n, \r and \t with single space (0x20) and then removes spaces
        // at the beggining and the end of the string and replaces sequences of spaces
        // with a single space.
        public static string NonCDataNormalize(string value)
        {
            int len = value.Length;

            if (len <= 0)
            {
                return(string.Empty);
            }

            int           startPos = 0;
            StringBuilder?norValue = null;

            while (XmlCharType.IsWhiteSpace(value[startPos]))
            {
                startPos++;
                if (startPos == len)
                {
                    return(" ");
                }
            }

            int i = startPos;

            while (i < len)
            {
                if (!XmlCharType.IsWhiteSpace(value[i]))
                {
                    i++;
                    continue;
                }

                int j = i + 1;
                while (j < len && XmlCharType.IsWhiteSpace(value[j]))
                {
                    j++;
                }
                if (j == len)
                {
                    if (norValue == null)
                    {
                        return(value.Substring(startPos, i - startPos));
                    }
                    else
                    {
                        norValue.Append(value, startPos, i - startPos);
                        return(norValue.ToString());
                    }
                }
                if (j > i + 1 || value[i] != 0x20)
                {
                    if (norValue == null)
                    {
                        norValue = new StringBuilder(len);
                    }
                    norValue.Append(value, startPos, i - startPos);
                    norValue.Append((char)0x20);
                    startPos = j;
                    i        = j;
                }
                else
                {
                    i++;
                }
            }

            if (norValue != null)
            {
                if (startPos < i)
                {
                    norValue.Append(value, startPos, i - startPos);
                }
                return(norValue.ToString());
            }
            else
            {
                if (startPos > 0)
                {
                    return(value.Substring(startPos, len - startPos));
                }
                else
                {
                    return(value);
                }
            }
        }
Esempio n. 29
0
 //
 // Constructor
 //
 internal XmlTextEncoder(TextWriter textWriter)
 {
     _textWriter  = textWriter;
     _quoteChar   = '"';
     _xmlCharType = XmlCharType.Instance;
 }
Esempio n. 30
0
        internal void Write(string text)
        {
            if (text == null)
            {
                return;
            }

            if (_cacheAttrValue)
            {
                _attrValue.Append(text);
            }

            // scan through the string to see if there are any characters to be escaped
            int  len      = text.Length;
            int  i        = 0;
            int  startPos = 0;
            char ch       = (char)0;

            while (true)
            {
                while (i < len && _xmlCharType.IsAttributeValueChar(ch = text[i]))
                {
                    i++;
                }

                if (i == len)
                {
                    // reached the end of the string -> write it whole out
                    _textWriter.Write(text);
                    return;
                }
                if (_inAttribute)
                {
                    if (ch == 0x9)
                    {
                        i++;
                        continue;
                    }
                }
                else
                {
                    if (ch == 0x9 || ch == 0xA || ch == 0xD || ch == '"' || ch == '\'')
                    {
                        i++;
                        continue;
                    }
                }
                // some character that needs to be escaped is found:
                break;
            }

            char[] helperBuffer = new char[256];
            while (true)
            {
                if (startPos < i)
                {
                    WriteStringFragment(text, startPos, i - startPos, helperBuffer);
                }
                if (i == len)
                {
                    break;
                }

                switch (ch)
                {
                case (char)0x9:
                    _textWriter.Write(ch);
                    break;

                case (char)0xA:
                case (char)0xD:
                    if (_inAttribute)
                    {
                        WriteCharEntityImpl(ch);
                    }
                    else
                    {
                        _textWriter.Write(ch);
                    }
                    break;

                case '<':
                    WriteEntityRefImpl("lt");
                    break;

                case '>':
                    WriteEntityRefImpl("gt");
                    break;

                case '&':
                    WriteEntityRefImpl("amp");
                    break;

                case '\'':
                    if (_inAttribute && _quoteChar == ch)
                    {
                        WriteEntityRefImpl("apos");
                    }
                    else
                    {
                        _textWriter.Write('\'');
                    }
                    break;

                case '"':
                    if (_inAttribute && _quoteChar == ch)
                    {
                        WriteEntityRefImpl("quot");
                    }
                    else
                    {
                        _textWriter.Write('"');
                    }
                    break;

                default:
                    if (XmlCharType.IsHighSurrogate(ch))
                    {
                        if (i + 1 < len)
                        {
                            WriteSurrogateChar(text[++i], ch);
                        }
                        else
                        {
                            throw XmlConvert.CreateInvalidSurrogatePairException(text[i], ch);
                        }
                    }
                    else if (XmlCharType.IsLowSurrogate(ch))
                    {
                        throw XmlConvert.CreateInvalidHighSurrogateCharException(ch);
                    }
                    else
                    {
                        Debug.Assert((ch < 0x20 && !_xmlCharType.IsWhiteSpace(ch)) || (ch > 0xFFFD));
                        WriteCharEntityImpl(ch);
                    }
                    break;
                }
                i++;
                startPos = i;
                while (i < len && _xmlCharType.IsAttributeValueChar(ch = text[i]))
                {
                    i++;
                }
            }
        }
Esempio n. 31
0
        internal void Write(char[] array, int offset, int count)
        {
            if (null == array)
            {
                throw new ArgumentNullException(nameof(array));
            }

            if (0 > offset)
            {
                throw new ArgumentOutOfRangeException(nameof(offset));
            }

            if (0 > count)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }

            if (count > array.Length - offset)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }

            if (_cacheAttrValue)
            {
                _attrValue.Append(array, offset, count);
            }

            int  endPos = offset + count;
            int  i      = offset;
            char ch     = (char)0;

            while (true)
            {
                int startPos = i;
                while (i < endPos && _xmlCharType.IsAttributeValueChar(ch = array[i]))
                {
                    i++;
                }

                if (startPos < i)
                {
                    _textWriter.Write(array, startPos, i - startPos);
                }
                if (i == endPos)
                {
                    break;
                }

                switch (ch)
                {
                case (char)0x9:
                    _textWriter.Write(ch);
                    break;

                case (char)0xA:
                case (char)0xD:
                    if (_inAttribute)
                    {
                        WriteCharEntityImpl(ch);
                    }
                    else
                    {
                        _textWriter.Write(ch);
                    }
                    break;

                case '<':
                    WriteEntityRefImpl("lt");
                    break;

                case '>':
                    WriteEntityRefImpl("gt");
                    break;

                case '&':
                    WriteEntityRefImpl("amp");
                    break;

                case '\'':
                    if (_inAttribute && _quoteChar == ch)
                    {
                        WriteEntityRefImpl("apos");
                    }
                    else
                    {
                        _textWriter.Write('\'');
                    }
                    break;

                case '"':
                    if (_inAttribute && _quoteChar == ch)
                    {
                        WriteEntityRefImpl("quot");
                    }
                    else
                    {
                        _textWriter.Write('"');
                    }
                    break;

                default:
                    if (XmlCharType.IsHighSurrogate(ch))
                    {
                        if (i + 1 < endPos)
                        {
                            WriteSurrogateChar(array[++i], ch);
                        }
                        else
                        {
                            throw new ArgumentException(SR.Xml_SurrogatePairSplit);
                        }
                    }
                    else if (XmlCharType.IsLowSurrogate(ch))
                    {
                        throw XmlConvert.CreateInvalidHighSurrogateCharException(ch);
                    }
                    else
                    {
                        Debug.Assert((ch < 0x20 && !_xmlCharType.IsWhiteSpace(ch)) || (ch > 0xFFFD));
                        WriteCharEntityImpl(ch);
                    }
                    break;
                }
                i++;
            }
        }
Esempio n. 32
0
 //
 // Constructor
 //
 internal XmlTextEncoder(TextWriter textWriter)
 {
     this.textWriter  = textWriter;
     this.quoteChar   = '"';
     this.xmlCharType = XmlCharType.Instance;
 }
Esempio n. 33
0
        internal int DecodeBinHex(char[] inArray, int offset, int inLength, byte[] outArray, int offsetOut, int countOut, bool flush)
        {
            String msg;

            if (0 > offset)
            {
                throw new ArgumentOutOfRangeException("offset");
            }

            if (0 > offsetOut)
            {
                throw new ArgumentOutOfRangeException("offsetOut");
            }

            int len = (null == inArray) ? 0 : inArray.Length;

            if (len < inLength)
            {
                throw new ArgumentOutOfRangeException("inLength");
            }

            // make sure that countOut + offsetOut are okay
            int outArrayLen = outArray.Length;

            if (outArrayLen < (countOut + offsetOut))
            {
                throw new ArgumentOutOfRangeException("offsetOut");
            }

            int inBufferCount = inLength - offset;

            if (flush)
            {
                _charBuffer.Refresh();
            }

            if (inBufferCount > 0)
            {
                _charBuffer.Append(inArray, offset, inLength);
            }

            if ((_charBuffer.Length == 0) || (countOut == 0))
            {
                return(0);
            }

            // let's just make sure countOut > 0 and countOut < outArray.Length
            countOut += offsetOut;
            byte lowHalfByte;

            // walk hex digits pairing them up and shoving the value of each pair into a byte
            int  internalBufferLength = _charBuffer.Length;
            int  offsetOutCur         = offsetOut;
            char ch;
            int  internalBufferOffset = 0;

            do
            {
                ch = _charBuffer[internalBufferOffset++];
                if (ch >= 'a' && ch <= 'f')
                {
                    lowHalfByte = (byte)(10 + ch - 'a');
                }
                else if (ch >= 'A' && ch <= 'F')
                {
                    lowHalfByte = (byte)(10 + ch - 'A');
                }
                else if (ch >= '0' && ch <= '9')
                {
                    lowHalfByte = (byte)(ch - '0');
                }
                else if (XmlCharType.IsWhiteSpace(ch))
                {
                    continue; // skip whitespace
                }
                else
                {
                    msg = new String(_charBuffer.CurrentBuffer, _charBuffer.CurrentBufferOffset, (_charBuffer.CurrentBuffer == null) ? 0:(_charBuffer.CurrentBufferLength - _charBuffer.CurrentBufferOffset));
                    throw new XmlException(Res.Xml_InvalidBinHexValue, msg);
                }

                if (_HighNibblePresent)
                {
                    outArray[offsetOutCur++] = (byte)((_highHalfByte << 4) + lowHalfByte);
                    _HighNibblePresent       = false;
                    if (offsetOutCur == countOut)
                    {
                        break;
                    }
                }
                else
                {
                    // shift nibble into top half of byte
                    _highHalfByte      = lowHalfByte;
                    _HighNibblePresent = true;
                }
            }while (internalBufferOffset < internalBufferLength);

            _charBuffer.CleanUp(internalBufferOffset);

            return(offsetOutCur - offsetOut);
        }
//
// Constructor
//
        internal XmlTextEncoder( TextWriter textWriter ) {
            this.textWriter = textWriter;
            this.quoteChar = '"';
            this.xmlCharType = XmlCharType.Instance;
        }
        public static string NonCDataNormalize(string value)
        {
            int length = value.Length;

            if (length <= 0)
            {
                return(string.Empty);
            }
            int           startIndex = 0;
            StringBuilder builder    = null;
            XmlCharType   instance   = XmlCharType.Instance;

            while (instance.IsWhiteSpace(value[startIndex]))
            {
                startIndex++;
                if (startIndex == length)
                {
                    return(" ");
                }
            }
            int num3 = startIndex;

            while (num3 < length)
            {
                if (!instance.IsWhiteSpace(value[num3]))
                {
                    num3++;
                }
                else
                {
                    int num4 = num3 + 1;
                    while ((num4 < length) && instance.IsWhiteSpace(value[num4]))
                    {
                        num4++;
                    }
                    if (num4 == length)
                    {
                        if (builder == null)
                        {
                            return(value.Substring(startIndex, num3 - startIndex));
                        }
                        builder.Append(value, startIndex, num3 - startIndex);
                        return(builder.ToString());
                    }
                    if ((num4 > (num3 + 1)) || (value[num3] != ' '))
                    {
                        if (builder == null)
                        {
                            builder = new StringBuilder(length);
                        }
                        builder.Append(value, startIndex, num3 - startIndex);
                        builder.Append(' ');
                        startIndex = num4;
                        num3       = num4;
                        continue;
                    }
                    num3++;
                }
            }
            if (builder != null)
            {
                if (startIndex < num3)
                {
                    builder.Append(value, startIndex, num3 - startIndex);
                }
                return(builder.ToString());
            }
            if (startIndex > 0)
            {
                return(value.Substring(startIndex, length - startIndex));
            }
            return(value);
        }
 private int SurrogateCharToUtf32(char highSurrogate, char lowSurrogate)
 {
     return(XmlCharType.CombineSurrogateChar(lowSurrogate, highSurrogate));
 }
Esempio n. 37
0
 //
 // Constructor
 //
 internal XmlTextEncoder(TextWriter textWriter)
 {
     _textWriter = textWriter;
     _quoteChar = '"';
     _xmlCharType = XmlCharType.Instance;
 }
Esempio n. 38
0
            // This method trims whitespace from the beginning and the end of the string and cached writer events
            internal void Trim()
            {
                // if only one string value -> trim the write spaces directly
                if (_singleStringValue != null)
                {
                    _singleStringValue = XmlConvert.TrimString(_singleStringValue);
                    return;
                }

                // trim the string in StringBuilder
                string valBefore = _stringValue.ToString();
                string valAfter  = XmlConvert.TrimString(valBefore);

                if (valBefore != valAfter)
                {
                    _stringValue = new StringBuilder(valAfter);
                }

                // trim the beginning of the recorded writer events
                XmlCharType xmlCharType = XmlCharType.Instance;

                int i = _firstItem;

                while (i == _firstItem && i <= _lastItem)
                {
                    Item item = _items[i];
                    switch (item.type)
                    {
                    case ItemType.Whitespace:
                        _firstItem++;
                        break;

                    case ItemType.String:
                    case ItemType.Raw:
                    case ItemType.ValueString:
                        item.data = XmlConvert.TrimStringStart((string)item.data);
                        if (((string)item.data).Length == 0)
                        {
                            // no characters left -> move the firstItem index to exclude it from the Replay
                            _firstItem++;
                        }
                        break;

                    case ItemType.StringChars:
                    case ItemType.RawChars:
                        BufferChunk bufChunk = (BufferChunk)item.data;
                        int         endIndex = bufChunk.index + bufChunk.count;
                        while (bufChunk.index < endIndex && xmlCharType.IsWhiteSpace(bufChunk.buffer[bufChunk.index]))
                        {
                            bufChunk.index++;
                            bufChunk.count--;
                        }
                        if (bufChunk.index == endIndex)
                        {
                            // no characters left -> move the firstItem index to exclude it from the Replay
                            _firstItem++;
                        }
                        break;
                    }
                    i++;
                }

                // trim the end of the recorded writer events
                i = _lastItem;
                while (i == _lastItem && i >= _firstItem)
                {
                    Item item = _items[i];
                    switch (item.type)
                    {
                    case ItemType.Whitespace:
                        _lastItem--;
                        break;

                    case ItemType.String:
                    case ItemType.Raw:
                    case ItemType.ValueString:
                        item.data = XmlConvert.TrimStringEnd((string)item.data);
                        if (((string)item.data).Length == 0)
                        {
                            // no characters left -> move the lastItem index to exclude it from the Replay
                            _lastItem--;
                        }
                        break;

                    case ItemType.StringChars:
                    case ItemType.RawChars:
                        BufferChunk bufChunk = (BufferChunk)item.data;
                        while (bufChunk.count > 0 && xmlCharType.IsWhiteSpace(bufChunk.buffer[bufChunk.index + bufChunk.count - 1]))
                        {
                            bufChunk.count--;
                        }
                        if (bufChunk.count == 0)
                        {
                            // no characters left -> move the lastItem index to exclude it from the Replay
                            _lastItem--;
                        }
                        break;
                    }
                    i--;
                }
            }
        public override async Task <bool> ReadAsync()
        {
            switch (_state)
            {
            case State.Initial:
                _state = State.Interactive;
                if (base.reader.ReadState == ReadState.Initial)
                {
                    goto case State.Interactive;
                }
                break;

            case State.Error:
                return(false);

            case State.InReadBinary:
                _state = State.Interactive;
                if (_readBinaryHelper != null)
                {
                    await _readBinaryHelper.FinishAsync().ConfigureAwait(false);
                }
                _state = State.Interactive;
                goto case State.Interactive;

            case State.Interactive:
                if (!await base.reader.ReadAsync().ConfigureAwait(false))
                {
                    return(false);
                }
                break;

            default:
                Debug.Fail($"Unexpected state {_state}");
                return(false);
            }

            XmlNodeType nodeType = base.reader.NodeType;

            if (!_checkCharacters)
            {
                switch (nodeType)
                {
                case XmlNodeType.Comment:
                    if (_ignoreComments)
                    {
                        return(await ReadAsync().ConfigureAwait(false));
                    }
                    break;

                case XmlNodeType.Whitespace:
                    if (_ignoreWhitespace)
                    {
                        return(await ReadAsync().ConfigureAwait(false));
                    }
                    break;

                case XmlNodeType.ProcessingInstruction:
                    if (_ignorePis)
                    {
                        return(await ReadAsync().ConfigureAwait(false));
                    }
                    break;

                case XmlNodeType.DocumentType:
                    if (_dtdProcessing == DtdProcessing.Prohibit)
                    {
                        Throw(SR.Xml_DtdIsProhibitedEx, string.Empty);
                    }
                    else if (_dtdProcessing == DtdProcessing.Ignore)
                    {
                        return(await ReadAsync().ConfigureAwait(false));
                    }
                    break;
                }
                return(true);
            }
            else
            {
                switch (nodeType)
                {
                case XmlNodeType.Element:
                    if (_checkCharacters)
                    {
                        // check element name
                        ValidateQName(base.reader.Prefix, base.reader.LocalName);

                        // check values of attributes
                        if (base.reader.MoveToFirstAttribute())
                        {
                            do
                            {
                                ValidateQName(base.reader.Prefix, base.reader.LocalName);
                                CheckCharacters(base.reader.Value);
                            } while (base.reader.MoveToNextAttribute());

                            base.reader.MoveToElement();
                        }
                    }
                    break;

                case XmlNodeType.Text:
                case XmlNodeType.CDATA:
                    if (_checkCharacters)
                    {
                        CheckCharacters(await base.reader.GetValueAsync().ConfigureAwait(false));
                    }
                    break;

                case XmlNodeType.EntityReference:
                    if (_checkCharacters)
                    {
                        // check name
                        ValidateQName(base.reader.Name);
                    }
                    break;

                case XmlNodeType.ProcessingInstruction:
                    if (_ignorePis)
                    {
                        return(await ReadAsync().ConfigureAwait(false));
                    }
                    if (_checkCharacters)
                    {
                        ValidateQName(base.reader.Name);
                        CheckCharacters(base.reader.Value);
                    }
                    break;

                case XmlNodeType.Comment:
                    if (_ignoreComments)
                    {
                        return(await ReadAsync().ConfigureAwait(false));
                    }
                    if (_checkCharacters)
                    {
                        CheckCharacters(base.reader.Value);
                    }
                    break;

                case XmlNodeType.DocumentType:
                    if (_dtdProcessing == DtdProcessing.Prohibit)
                    {
                        Throw(SR.Xml_DtdIsProhibitedEx, string.Empty);
                    }
                    else if (_dtdProcessing == DtdProcessing.Ignore)
                    {
                        return(await ReadAsync().ConfigureAwait(false));
                    }
                    if (_checkCharacters)
                    {
                        ValidateQName(base.reader.Name);
                        CheckCharacters(base.reader.Value);

                        string?str = base.reader.GetAttribute("SYSTEM");
                        if (str != null)
                        {
                            CheckCharacters(str);
                        }

                        str = base.reader.GetAttribute("PUBLIC");
                        if (str != null)
                        {
                            int i;
                            if ((i = XmlCharType.IsPublicId(str)) >= 0)
                            {
                                Throw(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(str, i));
                            }
                        }
                    }
                    break;

                case XmlNodeType.Whitespace:
                    if (_ignoreWhitespace)
                    {
                        return(await ReadAsync().ConfigureAwait(false));
                    }
                    if (_checkCharacters)
                    {
                        CheckWhitespace(await base.reader.GetValueAsync().ConfigureAwait(false));
                    }
                    break;

                case XmlNodeType.SignificantWhitespace:
                    if (_checkCharacters)
                    {
                        CheckWhitespace(await base.reader.GetValueAsync().ConfigureAwait(false));
                    }
                    break;

                case XmlNodeType.EndElement:
                    if (_checkCharacters)
                    {
                        ValidateQName(base.reader.Prefix, base.reader.LocalName);
                    }
                    break;

                default:
                    break;
                }
                _lastNodeType = nodeType;
                return(true);
            }
        }
Esempio n. 40
0
 private bool IsValidXmlVersion(string ver)
 {
     return(ver.Length >= 3 && ver[0] == '1' && ver[1] == '.' && XmlCharType.IsOnlyDigits(ver, 2, ver.Length - 2));
 }
        public XmlSqlBinaryReader(System.IO.Stream stream, byte[] data, int len, string baseUri, bool closeInput, XmlReaderSettings settings) {
            unicode = System.Text.Encoding.Unicode;
            xmlCharType = XmlCharType.Instance;

            this.xnt = settings.NameTable;
            if (this.xnt == null) {
                this.xnt = new NameTable();
                this.xntFromSettings = false;
            }
            else {
                this.xntFromSettings = true;
            }
            this.xml = this.xnt.Add("xml");
            this.xmlns = this.xnt.Add("xmlns");
            this.nsxmlns = this.xnt.Add(XmlReservedNs.NsXmlNs);
            this.baseUri = baseUri;
            this.state = ScanState.Init;
            this.nodetype = XmlNodeType.None;
            this.token = BinXmlToken.Error;
            this.elementStack = new ElemInfo[16];
            //this.elemDepth = 0;
            this.attributes = new AttrInfo[8];
            this.attrHashTbl = new int[8];
            //this.attrCount = 0;
            //this.attrIndex = 0;
            this.symbolTables.Init();
            this.qnameOther.Clear();
            this.qnameElement.Clear();
            this.xmlspacePreserve = false;
            this.hasher = new SecureStringHasher();
            this.namespaces = new Dictionary<String, NamespaceDecl>(hasher);
            AddInitNamespace(String.Empty, String.Empty);
            AddInitNamespace(this.xml, this.xnt.Add(XmlReservedNs.NsXml));
            AddInitNamespace(this.xmlns, this.nsxmlns);
            this.valueType = TypeOfString;
            // init buffer position, etc
            this.inStrm = stream;
            if (data != null) {
                Debug.Assert(len >= 2 && (data[0] == 0xdf && data[1] == 0xff));
                this.data = data;
                this.end = len;
                this.pos = 2;
                this.sniffed = true;
            }
            else {
                this.data = new byte[XmlReader.DefaultBufferSize];
                this.end = stream.Read(this.data, 0, XmlReader.DefaultBufferSize);
                this.pos = 0;
                this.sniffed = false;
            }

            this.mark = -1;
            this.eof = (0 == this.end);
            this.offset = 0;
            this.closeInput = closeInput;
            switch (settings.ConformanceLevel) {
                case ConformanceLevel.Auto:
                    this.docState = 0; break;
                case ConformanceLevel.Fragment:
                    this.docState = 9; break;
                case ConformanceLevel.Document:
                    this.docState = 1; break;
            }
            this.checkCharacters = settings.CheckCharacters;
            this.dtdProcessing = settings.DtdProcessing;
            this.ignoreWhitespace = settings.IgnoreWhitespace;
            this.ignorePIs = settings.IgnoreProcessingInstructions;
            this.ignoreComments = settings.IgnoreComments;

            if (TokenTypeMap == null)
                GenerateTokenTypeMap();
        }