using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Configuration; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Diagnostics; using System.Runtime.Serialization.Diagnostics.Application; using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Json; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Xml.XPath; using Unity; [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("System.Runtime.Serialization.dll")] [assembly: AssemblyDescription("System.Runtime.Serialization.dll")] [assembly: AssemblyDefaultAlias("System.Runtime.Serialization.dll")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: SatelliteContractVersion("4.0.0.0")] [assembly: AssemblyInformationalVersion("4.0.30319.17020")] [assembly: AssemblyFileVersion("4.0.30319.17020")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyKeyFile("../silverlight.pub")] [assembly: CompilationRelaxations(8)] [assembly: ComVisible(false)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.0.0")] [module: UnverifiableCode] internal static class SR { internal static string GetString(string name, params object[] args) { return GetString(CultureInfo.InvariantCulture, name, args); } internal static string GetString(CultureInfo culture, string name, params object[] args) { return string.Format(culture, name, args); } internal static string GetString(string name) { return name; } internal static string GetString(CultureInfo culture, string name) { return name; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2, p3); } } namespace System { internal static class LocalAppContextSwitches { public static readonly bool DoNotUseTimeZoneInfo; public static readonly bool DoNotUseEcmaScriptV6EscapeControlCharacter; } } namespace System.Xml { internal abstract class ArrayHelper { public TArray[] ReadArray(XmlDictionaryReader reader, TArgument localName, TArgument namespaceUri, int maxArrayLength) { TArray[][] array = null; TArray[] array2 = null; int num = 0; int num2 = 0; if (reader.TryGetArrayLength(out var count)) { if (count > maxArrayLength) { XmlExceptionHelper.ThrowMaxArrayLengthOrMaxItemsQuotaExceeded(reader, maxArrayLength); } if (count > 65535) { count = 65535; } } else { count = 32; } while (true) { array2 = new TArray[count]; int i; int num3; for (i = 0; i < array2.Length; i += num3) { num3 = ReadArray(reader, localName, namespaceUri, array2, i, array2.Length - i); if (num3 == 0) { break; } } if (num2 > maxArrayLength - i) { XmlExceptionHelper.ThrowMaxArrayLengthOrMaxItemsQuotaExceeded(reader, maxArrayLength); } num2 += i; if (i < array2.Length || reader.NodeType == XmlNodeType.EndElement) { break; } if (array == null) { array = new TArray[32][]; } array[num++] = array2; count *= 2; } if (num2 != array2.Length || num > 0) { TArray[] array3 = new TArray[num2]; int num4 = 0; for (int j = 0; j < num; j++) { Array.Copy(array[j], 0, array3, num4, array[j].Length); num4 += array[j].Length; } Array.Copy(array2, 0, array3, num4, num2 - num4); array2 = array3; } return array2; } public void WriteArray(XmlDictionaryWriter writer, string prefix, TArgument localName, TArgument namespaceUri, XmlDictionaryReader reader) { int count = ((!reader.TryGetArrayLength(out count)) ? 256 : Math.Min(count, 256)); TArray[] array = new TArray[count]; while (true) { int num = ReadArray(reader, localName, namespaceUri, array, 0, array.Length); if (num != 0) { WriteArray(writer, prefix, localName, namespaceUri, array, 0, num); continue; } break; } } protected abstract int ReadArray(XmlDictionaryReader reader, TArgument localName, TArgument namespaceUri, TArray[] array, int offset, int count); protected abstract void WriteArray(XmlDictionaryWriter writer, string prefix, TArgument localName, TArgument namespaceUri, TArray[] array, int offset, int count); } internal class BooleanArrayHelperWithString : ArrayHelper { public static readonly BooleanArrayHelperWithString Instance = new BooleanArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, bool[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, bool[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class BooleanArrayHelperWithDictionaryString : ArrayHelper { public static readonly BooleanArrayHelperWithDictionaryString Instance = new BooleanArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class Int16ArrayHelperWithString : ArrayHelper { public static readonly Int16ArrayHelperWithString Instance = new Int16ArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, short[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, short[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class Int16ArrayHelperWithDictionaryString : ArrayHelper { public static readonly Int16ArrayHelperWithDictionaryString Instance = new Int16ArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class Int32ArrayHelperWithString : ArrayHelper { public static readonly Int32ArrayHelperWithString Instance = new Int32ArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, int[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, int[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class Int32ArrayHelperWithDictionaryString : ArrayHelper { public static readonly Int32ArrayHelperWithDictionaryString Instance = new Int32ArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class Int64ArrayHelperWithString : ArrayHelper { public static readonly Int64ArrayHelperWithString Instance = new Int64ArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, long[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, long[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class Int64ArrayHelperWithDictionaryString : ArrayHelper { public static readonly Int64ArrayHelperWithDictionaryString Instance = new Int64ArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class SingleArrayHelperWithString : ArrayHelper { public static readonly SingleArrayHelperWithString Instance = new SingleArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, float[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, float[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class SingleArrayHelperWithDictionaryString : ArrayHelper { public static readonly SingleArrayHelperWithDictionaryString Instance = new SingleArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class DoubleArrayHelperWithString : ArrayHelper { public static readonly DoubleArrayHelperWithString Instance = new DoubleArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, double[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, double[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class DoubleArrayHelperWithDictionaryString : ArrayHelper { public static readonly DoubleArrayHelperWithDictionaryString Instance = new DoubleArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class DecimalArrayHelperWithString : ArrayHelper { public static readonly DecimalArrayHelperWithString Instance = new DecimalArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, decimal[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class DecimalArrayHelperWithDictionaryString : ArrayHelper { public static readonly DecimalArrayHelperWithDictionaryString Instance = new DecimalArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class DateTimeArrayHelperWithString : ArrayHelper { public static readonly DateTimeArrayHelperWithString Instance = new DateTimeArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, DateTime[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class DateTimeArrayHelperWithDictionaryString : ArrayHelper { public static readonly DateTimeArrayHelperWithDictionaryString Instance = new DateTimeArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class GuidArrayHelperWithString : ArrayHelper { public static readonly GuidArrayHelperWithString Instance = new GuidArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, Guid[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class GuidArrayHelperWithDictionaryString : ArrayHelper { public static readonly GuidArrayHelperWithDictionaryString Instance = new GuidArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class TimeSpanArrayHelperWithString : ArrayHelper { public static readonly TimeSpanArrayHelperWithString Instance = new TimeSpanArrayHelperWithString(); protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, TimeSpan[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class TimeSpanArrayHelperWithDictionaryString : ArrayHelper { public static readonly TimeSpanArrayHelperWithDictionaryString Instance = new TimeSpanArrayHelperWithDictionaryString(); protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) { return reader.ReadArray(localName, namespaceUri, array, offset, count); } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) { writer.WriteArray(prefix, localName, namespaceUri, array, offset, count); } } internal class EncodingStreamWrapper : Stream { private enum SupportedEncoding { UTF8, UTF16LE, UTF16BE, None } private static readonly UTF8Encoding SafeUTF8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false); private static readonly UnicodeEncoding SafeUTF16 = new UnicodeEncoding(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: false); private static readonly UnicodeEncoding SafeBEUTF16 = new UnicodeEncoding(bigEndian: true, byteOrderMark: false, throwOnInvalidBytes: false); private static readonly UTF8Encoding ValidatingUTF8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); private static readonly UnicodeEncoding ValidatingUTF16 = new UnicodeEncoding(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: true); private static readonly UnicodeEncoding ValidatingBEUTF16 = new UnicodeEncoding(bigEndian: true, byteOrderMark: false, throwOnInvalidBytes: true); private const int BufferLength = 128; private static readonly byte[] encodingAttr = new byte[8] { 101, 110, 99, 111, 100, 105, 110, 103 }; private static readonly byte[] encodingUTF8 = new byte[5] { 117, 116, 102, 45, 56 }; private static readonly byte[] encodingUnicode = new byte[6] { 117, 116, 102, 45, 49, 54 }; private static readonly byte[] encodingUnicodeLE = new byte[8] { 117, 116, 102, 45, 49, 54, 108, 101 }; private static readonly byte[] encodingUnicodeBE = new byte[8] { 117, 116, 102, 45, 49, 54, 98, 101 }; private SupportedEncoding encodingCode; private Encoding encoding; private Encoder enc; private Decoder dec; private bool isReading; private Stream stream; private char[] chars; private byte[] bytes; private int byteOffset; private int byteCount; private byte[] byteBuffer = new byte[1]; public override bool CanRead { get { if (!isReading) { return false; } return stream.CanRead; } } public override bool CanSeek => false; public override bool CanWrite { get { if (isReading) { return false; } return stream.CanWrite; } } public override long Position { get { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } set { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } } public override bool CanTimeout => stream.CanTimeout; public override long Length => stream.Length; public override int ReadTimeout { get { return stream.ReadTimeout; } set { stream.ReadTimeout = value; } } public override int WriteTimeout { get { return stream.WriteTimeout; } set { stream.WriteTimeout = value; } } public EncodingStreamWrapper(Stream stream, Encoding encoding) { try { isReading = true; this.stream = new BufferedStream(stream); SupportedEncoding supportedEncoding = GetSupportedEncoding(encoding); SupportedEncoding supportedEncoding2 = ReadBOMEncoding(encoding == null); if (supportedEncoding != SupportedEncoding.None && supportedEncoding != supportedEncoding2) { ThrowExpectedEncodingMismatch(supportedEncoding, supportedEncoding2); } if (supportedEncoding2 == SupportedEncoding.UTF8) { FillBuffer(2); if (bytes[byteOffset + 1] == 63 && bytes[byteOffset] == 60) { FillBuffer(128); CheckUTF8DeclarationEncoding(bytes, byteOffset, byteCount, supportedEncoding2, supportedEncoding); } return; } EnsureBuffers(); FillBuffer(254); SetReadDocumentEncoding(supportedEncoding2); CleanupCharBreak(); int charCount = this.encoding.GetChars(bytes, byteOffset, byteCount, chars, 0); byteOffset = 0; byteCount = ValidatingUTF8.GetBytes(chars, 0, charCount, bytes, 0); if (bytes[1] == 63 && bytes[0] == 60) { CheckUTF8DeclarationEncoding(bytes, 0, byteCount, supportedEncoding2, supportedEncoding); } else if (supportedEncoding == SupportedEncoding.None) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("An XML declaration with an encoding is required for all non-UTF8 documents."))); } } catch (DecoderFallbackException innerException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Invalid byte encoding."), innerException)); } } private void SetReadDocumentEncoding(SupportedEncoding e) { EnsureBuffers(); encodingCode = e; encoding = GetEncoding(e); } private static Encoding GetEncoding(SupportedEncoding e) { return e switch { SupportedEncoding.UTF8 => ValidatingUTF8, SupportedEncoding.UTF16LE => ValidatingUTF16, SupportedEncoding.UTF16BE => ValidatingBEUTF16, _ => throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("XML encoding not supported."))), }; } private static Encoding GetSafeEncoding(SupportedEncoding e) { return e switch { SupportedEncoding.UTF8 => SafeUTF8, SupportedEncoding.UTF16LE => SafeUTF16, SupportedEncoding.UTF16BE => SafeBEUTF16, _ => throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("XML encoding not supported."))), }; } private static string GetEncodingName(SupportedEncoding enc) { return enc switch { SupportedEncoding.UTF8 => "utf-8", SupportedEncoding.UTF16LE => "utf-16LE", SupportedEncoding.UTF16BE => "utf-16BE", _ => throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("XML encoding not supported."))), }; } private static SupportedEncoding GetSupportedEncoding(Encoding encoding) { if (encoding == null) { return SupportedEncoding.None; } if (encoding.WebName == ValidatingUTF8.WebName) { return SupportedEncoding.UTF8; } if (encoding.WebName == ValidatingUTF16.WebName) { return SupportedEncoding.UTF16LE; } if (encoding.WebName == ValidatingBEUTF16.WebName) { return SupportedEncoding.UTF16BE; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("XML encoding not supported."))); } public EncodingStreamWrapper(Stream stream, Encoding encoding, bool emitBOM) { isReading = false; this.encoding = encoding; this.stream = new BufferedStream(stream); encodingCode = GetSupportedEncoding(encoding); if (encodingCode == SupportedEncoding.UTF8) { return; } EnsureBuffers(); dec = ValidatingUTF8.GetDecoder(); enc = this.encoding.GetEncoder(); if (emitBOM) { byte[] preamble = this.encoding.GetPreamble(); if (preamble.Length != 0) { this.stream.Write(preamble, 0, preamble.Length); } } } private SupportedEncoding ReadBOMEncoding(bool notOutOfBand) { int num = stream.ReadByte(); int num2 = stream.ReadByte(); int num3 = stream.ReadByte(); int num4 = stream.ReadByte(); if (num4 == -1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Unexpected end of file."))); } int preserve; SupportedEncoding result = ReadBOMEncoding((byte)num, (byte)num2, (byte)num3, (byte)num4, notOutOfBand, out preserve); EnsureByteBuffer(); switch (preserve) { case 1: bytes[0] = (byte)num4; break; case 2: bytes[0] = (byte)num3; bytes[1] = (byte)num4; break; case 4: bytes[0] = (byte)num; bytes[1] = (byte)num2; bytes[2] = (byte)num3; bytes[3] = (byte)num4; break; } byteCount = preserve; return result; } private static SupportedEncoding ReadBOMEncoding(byte b1, byte b2, byte b3, byte b4, bool notOutOfBand, out int preserve) { SupportedEncoding result = SupportedEncoding.UTF8; preserve = 0; if (b1 == 60 && b2 != 0) { result = SupportedEncoding.UTF8; preserve = 4; } else if (b1 == byte.MaxValue && b2 == 254) { result = SupportedEncoding.UTF16LE; preserve = 2; } else if (b1 == 254 && b2 == byte.MaxValue) { result = SupportedEncoding.UTF16BE; preserve = 2; } else if (b1 == 0 && b2 == 60) { result = SupportedEncoding.UTF16BE; if (notOutOfBand && (b3 != 0 || b4 != 63)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("An XML declaration is required for all non-UTF8 documents."))); } preserve = 4; } else if (b1 == 60 && b2 == 0) { result = SupportedEncoding.UTF16LE; if (notOutOfBand && (b3 != 63 || b4 != 0)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("An XML declaration is required for all non-UTF8 documents."))); } preserve = 4; } else if (b1 == 239 && b2 == 187) { if (notOutOfBand && b3 != 191) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Unrecognized Byte Order Mark."))); } preserve = 1; } else { preserve = 4; } return result; } private void FillBuffer(int count) { count -= byteCount; while (count > 0) { int num = stream.Read(bytes, byteOffset + byteCount, count); if (num != 0) { byteCount += num; count -= num; continue; } break; } } private void EnsureBuffers() { EnsureByteBuffer(); if (chars == null) { chars = new char[128]; } } private void EnsureByteBuffer() { if (bytes == null) { bytes = new byte[512]; byteOffset = 0; byteCount = 0; } } private static void CheckUTF8DeclarationEncoding(byte[] buffer, int offset, int count, SupportedEncoding e, SupportedEncoding expectedEnc) { byte b = 0; int num = -1; int num2 = offset + Math.Min(count, 128); int num3 = 0; int num4 = 0; for (num3 = offset + 2; num3 < num2; num3++) { if (b != 0) { if (buffer[num3] == b) { b = 0; } } else if (buffer[num3] == 39 || buffer[num3] == 34) { b = buffer[num3]; } else if (buffer[num3] == 61) { if (num4 == 1) { num = num3; break; } num4++; } else if (buffer[num3] == 63) { break; } } if (num == -1) { if (e != 0 && expectedEnc == SupportedEncoding.None) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("An XML declaration with an encoding is required for all non-UTF8 documents."))); } return; } if (num < 28) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Malformed XML declaration."))); } num3 = num - 1; while (IsWhitespace(buffer[num3])) { num3--; } if (!Compare(encodingAttr, buffer, num3 - encodingAttr.Length + 1)) { if (e == SupportedEncoding.UTF8 || expectedEnc != SupportedEncoding.None) { return; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("An XML declaration with an encoding is required for all non-UTF8 documents."))); } for (num3 = num + 1; num3 < num2 && IsWhitespace(buffer[num3]); num3++) { } if (buffer[num3] != 39 && buffer[num3] != 34) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Malformed XML declaration."))); } b = buffer[num3]; int num5 = num3++; for (; buffer[num3] != b && num3 < num2; num3++) { } if (buffer[num3] != b) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Malformed XML declaration."))); } int num6 = num5 + 1; int num7 = num3 - num6; SupportedEncoding supportedEncoding = e; if (num7 == encodingUTF8.Length && CompareCaseInsensitive(encodingUTF8, buffer, num6)) { supportedEncoding = SupportedEncoding.UTF8; } else if (num7 == encodingUnicodeLE.Length && CompareCaseInsensitive(encodingUnicodeLE, buffer, num6)) { supportedEncoding = SupportedEncoding.UTF16LE; } else if (num7 == encodingUnicodeBE.Length && CompareCaseInsensitive(encodingUnicodeBE, buffer, num6)) { supportedEncoding = SupportedEncoding.UTF16BE; } else if (num7 == encodingUnicode.Length && CompareCaseInsensitive(encodingUnicode, buffer, num6)) { if (e == SupportedEncoding.UTF8) { ThrowEncodingMismatch(SafeUTF8.GetString(buffer, num6, num7), SafeUTF8.GetString(encodingUTF8, 0, encodingUTF8.Length)); } } else { ThrowEncodingMismatch(SafeUTF8.GetString(buffer, num6, num7), e); } if (e != supportedEncoding) { ThrowEncodingMismatch(SafeUTF8.GetString(buffer, num6, num7), e); } } private static bool CompareCaseInsensitive(byte[] key, byte[] buffer, int offset) { for (int i = 0; i < key.Length; i++) { if (key[i] != buffer[offset + i] && key[i] != char.ToLower((char)buffer[offset + i], CultureInfo.InvariantCulture)) { return false; } } return true; } private static bool Compare(byte[] key, byte[] buffer, int offset) { for (int i = 0; i < key.Length; i++) { if (key[i] != buffer[offset + i]) { return false; } } return true; } private static bool IsWhitespace(byte ch) { if (ch != 32 && ch != 10 && ch != 9) { return ch == 13; } return true; } internal static ArraySegment ProcessBuffer(byte[] buffer, int offset, int count, Encoding encoding) { if (count < 4) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Unexpected end of file."))); } try { SupportedEncoding supportedEncoding = GetSupportedEncoding(encoding); int preserve; SupportedEncoding supportedEncoding2 = ReadBOMEncoding(buffer[offset], buffer[offset + 1], buffer[offset + 2], buffer[offset + 3], encoding == null, out preserve); if (supportedEncoding != SupportedEncoding.None && supportedEncoding != supportedEncoding2) { ThrowExpectedEncodingMismatch(supportedEncoding, supportedEncoding2); } offset += 4 - preserve; count -= 4 - preserve; if (supportedEncoding2 == SupportedEncoding.UTF8) { if (buffer[offset + 1] != 63 || buffer[offset] != 60) { return new ArraySegment(buffer, offset, count); } CheckUTF8DeclarationEncoding(buffer, offset, count, supportedEncoding2, supportedEncoding); return new ArraySegment(buffer, offset, count); } Encoding safeEncoding = GetSafeEncoding(supportedEncoding2); int num = Math.Min(count, 256); char[] array = new char[safeEncoding.GetMaxCharCount(num)]; int charCount = safeEncoding.GetChars(buffer, offset, num, array, 0); byte[] array2 = new byte[ValidatingUTF8.GetMaxByteCount(charCount)]; int count2 = ValidatingUTF8.GetBytes(array, 0, charCount, array2, 0); if (array2[1] == 63 && array2[0] == 60) { CheckUTF8DeclarationEncoding(array2, 0, count2, supportedEncoding2, supportedEncoding); } else if (supportedEncoding == SupportedEncoding.None) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("An XML declaration with an encoding is required for all non-UTF8 documents."))); } return new ArraySegment(ValidatingUTF8.GetBytes(GetEncoding(supportedEncoding2).GetChars(buffer, offset, count))); } catch (DecoderFallbackException innerException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Invalid byte encoding."), innerException)); } } private static void ThrowExpectedEncodingMismatch(SupportedEncoding expEnc, SupportedEncoding actualEnc) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("The expected encoding '{0}' does not match the actual encoding '{1}'.", GetEncodingName(expEnc), GetEncodingName(actualEnc)))); } private static void ThrowEncodingMismatch(string declEnc, SupportedEncoding enc) { ThrowEncodingMismatch(declEnc, GetEncodingName(enc)); } private static void ThrowEncodingMismatch(string declEnc, string docEnc) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("The encoding in the declaration '{0}' does not match the encoding of the document '{1}'.", declEnc, docEnc))); } public override void Close() { Flush(); base.Close(); stream.Close(); } public override void Flush() { stream.Flush(); } public override int ReadByte() { if (byteCount == 0 && encodingCode == SupportedEncoding.UTF8) { return stream.ReadByte(); } if (Read(byteBuffer, 0, 1) == 0) { return -1; } return byteBuffer[0]; } public override int Read(byte[] buffer, int offset, int count) { try { if (byteCount == 0) { if (encodingCode == SupportedEncoding.UTF8) { return stream.Read(buffer, offset, count); } byteOffset = 0; byteCount = stream.Read(bytes, byteCount, (chars.Length - 1) * 2); if (byteCount == 0) { return 0; } CleanupCharBreak(); int charCount = encoding.GetChars(bytes, 0, byteCount, chars, 0); byteCount = Encoding.UTF8.GetBytes(chars, 0, charCount, bytes, 0); } if (byteCount < count) { count = byteCount; } Buffer.BlockCopy(bytes, byteOffset, buffer, offset, count); byteOffset += count; byteCount -= count; return count; } catch (DecoderFallbackException innerException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Invalid byte encoding."), innerException)); } } private void CleanupCharBreak() { int num = byteOffset + byteCount; if (byteCount % 2 != 0) { int num2 = stream.ReadByte(); if (num2 < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Unexpected end of file."))); } bytes[num++] = (byte)num2; byteCount++; } int num3 = ((encodingCode != SupportedEncoding.UTF16LE) ? (bytes[num - 1] + (bytes[num - 2] << 8)) : (bytes[num - 2] + (bytes[num - 1] << 8))); if ((num3 & 0xDC00) != 56320 && num3 >= 55296 && num3 <= 56319) { int num4 = stream.ReadByte(); int num5 = stream.ReadByte(); if (num5 < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Unexpected end of file."))); } bytes[num++] = (byte)num4; bytes[num++] = (byte)num5; byteCount += 2; } } public override long Seek(long offset, SeekOrigin origin) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } public override void WriteByte(byte b) { if (encodingCode == SupportedEncoding.UTF8) { stream.WriteByte(b); return; } byteBuffer[0] = b; Write(byteBuffer, 0, 1); } public override void Write(byte[] buffer, int offset, int count) { if (encodingCode == SupportedEncoding.UTF8) { stream.Write(buffer, offset, count); return; } while (count > 0) { int num = ((chars.Length < count) ? chars.Length : count); int charCount = dec.GetChars(buffer, offset, num, chars, 0, flush: false); byteCount = enc.GetBytes(chars, 0, charCount, bytes, 0, flush: false); stream.Write(bytes, 0, byteCount); offset += num; count -= num; } } public override void SetLength(long value) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } } public interface IFragmentCapableXmlDictionaryWriter { bool CanFragment { get; } void StartFragment(Stream stream, bool generateSelfContainedTextFragment); void EndFragment(); void WriteFragment(byte[] buffer, int offset, int count); } public interface IStreamProvider { Stream GetStream(); void ReleaseStream(Stream stream); } public interface IXmlDictionary { bool TryLookup(string value, out XmlDictionaryString result); bool TryLookup(int key, out XmlDictionaryString result); bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result); } internal enum PrefixHandleType { Empty, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Buffer, Max } internal class PrefixHandle { private XmlBufferReader bufferReader; private PrefixHandleType type; private int offset; private int length; private static string[] prefixStrings = new string[27] { "", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; private static byte[] prefixBuffer = new byte[26] { 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122 }; public bool IsEmpty => type == PrefixHandleType.Empty; public bool IsXmlns { get { if (type != PrefixHandleType.Buffer) { return false; } if (length != 5) { return false; } byte[] buffer = bufferReader.Buffer; int num = offset; if (buffer[num] == 120 && buffer[num + 1] == 109 && buffer[num + 2] == 108 && buffer[num + 3] == 110) { return buffer[num + 4] == 115; } return false; } } public bool IsXml { get { if (type != PrefixHandleType.Buffer) { return false; } if (length != 3) { return false; } byte[] buffer = bufferReader.Buffer; int num = offset; if (buffer[num] == 120 && buffer[num + 1] == 109) { return buffer[num + 2] == 108; } return false; } } public PrefixHandle(XmlBufferReader bufferReader) { this.bufferReader = bufferReader; } public void SetValue(PrefixHandleType type) { this.type = type; } public void SetValue(PrefixHandle prefix) { type = prefix.type; offset = prefix.offset; length = prefix.length; } public void SetValue(int offset, int length) { switch (length) { case 0: SetValue(PrefixHandleType.Empty); return; case 1: { byte @byte = bufferReader.GetByte(offset); if (@byte >= 97 && @byte <= 122) { SetValue(GetAlphaPrefix(@byte - 97)); return; } break; } } type = PrefixHandleType.Buffer; this.offset = offset; this.length = length; } public bool TryGetShortPrefix(out PrefixHandleType type) { type = this.type; return type != PrefixHandleType.Buffer; } public static string GetString(PrefixHandleType type) { return prefixStrings[(int)type]; } public static PrefixHandleType GetAlphaPrefix(int index) { return (PrefixHandleType)(1 + index); } public static byte[] GetString(PrefixHandleType type, out int offset, out int length) { if (type == PrefixHandleType.Empty) { offset = 0; length = 0; } else { length = 1; offset = (int)(type - 1); } return prefixBuffer; } public string GetString(XmlNameTable nameTable) { PrefixHandleType prefixHandleType = type; if (prefixHandleType != PrefixHandleType.Buffer) { return GetString(prefixHandleType); } return bufferReader.GetString(offset, length, nameTable); } public string GetString() { PrefixHandleType prefixHandleType = type; if (prefixHandleType != PrefixHandleType.Buffer) { return GetString(prefixHandleType); } return bufferReader.GetString(offset, length); } public byte[] GetString(out int offset, out int length) { PrefixHandleType prefixHandleType = type; if (prefixHandleType != PrefixHandleType.Buffer) { return GetString(prefixHandleType, out offset, out length); } offset = this.offset; length = this.length; return bufferReader.Buffer; } public int CompareTo(PrefixHandle that) { return GetString().CompareTo(that.GetString()); } private bool Equals2(PrefixHandle prefix2) { PrefixHandleType prefixHandleType = type; PrefixHandleType prefixHandleType2 = prefix2.type; if (prefixHandleType != prefixHandleType2) { return false; } if (prefixHandleType != PrefixHandleType.Buffer) { return true; } if (bufferReader == prefix2.bufferReader) { return bufferReader.Equals2(offset, length, prefix2.offset, prefix2.length); } return bufferReader.Equals2(offset, length, prefix2.bufferReader, prefix2.offset, prefix2.length); } private bool Equals2(string prefix2) { PrefixHandleType prefixHandleType = type; if (prefixHandleType != PrefixHandleType.Buffer) { return GetString(prefixHandleType) == prefix2; } return bufferReader.Equals2(offset, length, prefix2); } private bool Equals2(XmlDictionaryString prefix2) { return Equals2(prefix2.Value); } public static bool operator ==(PrefixHandle prefix1, string prefix2) { return prefix1.Equals2(prefix2); } public static bool operator !=(PrefixHandle prefix1, string prefix2) { return !prefix1.Equals2(prefix2); } public static bool operator ==(PrefixHandle prefix1, XmlDictionaryString prefix2) { return prefix1.Equals2(prefix2); } public static bool operator !=(PrefixHandle prefix1, XmlDictionaryString prefix2) { return !prefix1.Equals2(prefix2); } public static bool operator ==(PrefixHandle prefix1, PrefixHandle prefix2) { return prefix1.Equals2(prefix2); } public static bool operator !=(PrefixHandle prefix1, PrefixHandle prefix2) { return !prefix1.Equals2(prefix2); } public override bool Equals(object obj) { if (!(obj is PrefixHandle prefixHandle)) { return false; } return this == prefixHandle; } public override string ToString() { return GetString(); } public override int GetHashCode() { return GetString().GetHashCode(); } } internal enum StringHandleConstStringType { Type, Root, Item } internal class StringHandle { private enum StringHandleType { Dictionary, UTF8, EscapedUTF8, ConstString } private XmlBufferReader bufferReader; private StringHandleType type; private int key; private int offset; private int length; private static string[] constStrings = new string[3] { "type", "root", "item" }; public bool IsEmpty { get { if (type == StringHandleType.UTF8) { return length == 0; } return Equals2(string.Empty); } } public bool IsXmlns { get { if (type == StringHandleType.UTF8) { if (length != 5) { return false; } byte[] buffer = bufferReader.Buffer; int num = offset; if (buffer[num] == 120 && buffer[num + 1] == 109 && buffer[num + 2] == 108 && buffer[num + 3] == 110) { return buffer[num + 4] == 115; } return false; } return Equals2("xmlns"); } } public StringHandle(XmlBufferReader bufferReader) { this.bufferReader = bufferReader; SetValue(0, 0); } public void SetValue(int offset, int length) { type = StringHandleType.UTF8; this.offset = offset; this.length = length; } public void SetConstantValue(StringHandleConstStringType constStringType) { type = StringHandleType.ConstString; key = (int)constStringType; } public void SetValue(int offset, int length, bool escaped) { type = ((!escaped) ? StringHandleType.UTF8 : StringHandleType.EscapedUTF8); this.offset = offset; this.length = length; } public void SetValue(int key) { type = StringHandleType.Dictionary; this.key = key; } public void SetValue(StringHandle value) { type = value.type; key = value.key; offset = value.offset; length = value.length; } public void ToPrefixHandle(PrefixHandle prefix) { prefix.SetValue(offset, length); } public string GetString(XmlNameTable nameTable) { return type switch { StringHandleType.UTF8 => bufferReader.GetString(offset, length, nameTable), StringHandleType.Dictionary => nameTable.Add(bufferReader.GetDictionaryString(key).Value), StringHandleType.ConstString => nameTable.Add(constStrings[key]), _ => bufferReader.GetEscapedString(offset, length, nameTable), }; } public string GetString() { return type switch { StringHandleType.UTF8 => bufferReader.GetString(offset, length), StringHandleType.Dictionary => bufferReader.GetDictionaryString(key).Value, StringHandleType.ConstString => constStrings[key], _ => bufferReader.GetEscapedString(offset, length), }; } public byte[] GetString(out int offset, out int length) { switch (type) { case StringHandleType.UTF8: offset = this.offset; length = this.length; return bufferReader.Buffer; case StringHandleType.Dictionary: { byte[] array3 = bufferReader.GetDictionaryString(key).ToUTF8(); offset = 0; length = array3.Length; return array3; } case StringHandleType.ConstString: { byte[] array2 = XmlConverter.ToBytes(constStrings[key]); offset = 0; length = array2.Length; return array2; } default: { byte[] array = XmlConverter.ToBytes(bufferReader.GetEscapedString(this.offset, this.length)); offset = 0; length = array.Length; return array; } } } public bool TryGetDictionaryString(out XmlDictionaryString value) { if (type == StringHandleType.Dictionary) { value = bufferReader.GetDictionaryString(key); return true; } if (IsEmpty) { value = XmlDictionaryString.Empty; return true; } value = null; return false; } public override string ToString() { return GetString(); } private bool Equals2(int key2, XmlBufferReader bufferReader2) { return type switch { StringHandleType.Dictionary => bufferReader.Equals2(key, key2, bufferReader2), StringHandleType.UTF8 => bufferReader.Equals2(offset, length, bufferReader2.GetDictionaryString(key2).Value), _ => GetString() == bufferReader.GetDictionaryString(key2).Value, }; } private bool Equals2(XmlDictionaryString xmlString2) { return type switch { StringHandleType.Dictionary => bufferReader.Equals2(key, xmlString2), StringHandleType.UTF8 => bufferReader.Equals2(offset, length, xmlString2.ToUTF8()), _ => GetString() == xmlString2.Value, }; } private bool Equals2(string s2) { return type switch { StringHandleType.Dictionary => bufferReader.GetDictionaryString(key).Value == s2, StringHandleType.UTF8 => bufferReader.Equals2(offset, length, s2), _ => GetString() == s2, }; } private bool Equals2(int offset2, int length2, XmlBufferReader bufferReader2) { return type switch { StringHandleType.Dictionary => bufferReader2.Equals2(offset2, length2, bufferReader.GetDictionaryString(key).Value), StringHandleType.UTF8 => bufferReader.Equals2(offset, length, bufferReader2, offset2, length2), _ => GetString() == bufferReader.GetString(offset2, length2), }; } private bool Equals2(StringHandle s2) { return s2.type switch { StringHandleType.Dictionary => Equals2(s2.key, s2.bufferReader), StringHandleType.UTF8 => Equals2(s2.offset, s2.length, s2.bufferReader), _ => Equals2(s2.GetString()), }; } public static bool operator ==(StringHandle s1, XmlDictionaryString xmlString2) { return s1.Equals2(xmlString2); } public static bool operator !=(StringHandle s1, XmlDictionaryString xmlString2) { return !s1.Equals2(xmlString2); } public static bool operator ==(StringHandle s1, string s2) { return s1.Equals2(s2); } public static bool operator !=(StringHandle s1, string s2) { return !s1.Equals2(s2); } public static bool operator ==(StringHandle s1, StringHandle s2) { return s1.Equals2(s2); } public static bool operator !=(StringHandle s1, StringHandle s2) { return !s1.Equals2(s2); } public int CompareTo(StringHandle that) { if (type == StringHandleType.UTF8 && that.type == StringHandleType.UTF8) { return bufferReader.Compare(offset, length, that.offset, that.length); } return string.Compare(GetString(), that.GetString(), StringComparison.Ordinal); } public override bool Equals(object obj) { if (!(obj is StringHandle stringHandle)) { return false; } return this == stringHandle; } public override int GetHashCode() { return GetString().GetHashCode(); } } public class UniqueId { private long idLow; private long idHigh; [SecurityCritical] private string s; private const int guidLength = 16; private const int uuidLength = 45; private static short[] char2val = new short[256] { 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 160, 176, 192, 208, 224, 240, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 10, 11, 12, 13, 14, 15, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256 }; private const string val2char = "0123456789abcdef"; public int CharArrayLength { [SecuritySafeCritical] get { if (s != null) { return s.Length; } return 45; } } public bool IsGuid => (idLow | idHigh) != 0; public UniqueId() : this(Guid.NewGuid()) { } public UniqueId(Guid guid) : this(guid.ToByteArray()) { } public UniqueId(byte[] guid) : this(guid, 0) { } [SecuritySafeCritical] public unsafe UniqueId(byte[] guid, int offset) { if (guid == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("guid")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > guid.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", guid.Length))); } if (16 > guid.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Array too small. Length of available data must be at least {0}.", 16), "guid")); } fixed (byte* ptr = &guid[offset]) { idLow = UnsafeGetInt64(ptr); idHigh = UnsafeGetInt64(ptr + 8); } } [SecuritySafeCritical] public unsafe UniqueId(string value) { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } if (value.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("UniqueId cannot be zero length."))); } fixed (char* chars = value) { UnsafeParse(chars, value.Length); } s = value; } [SecuritySafeCritical] public unsafe UniqueId(char[] chars, int offset, int count) { if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > chars.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > chars.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", chars.Length - offset))); } if (count == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("UniqueId cannot be zero length."))); } fixed (char* chars2 = &chars[offset]) { UnsafeParse(chars2, count); } if (!IsGuid) { s = new string(chars, offset, count); } } [SecurityCritical] private unsafe int UnsafeDecode(short* char2val, char ch1, char ch2) { if ((ch1 | ch2) >= 128) { return 256; } return char2val[(int)ch1] | char2val[128 + ch2]; } [SecurityCritical] private unsafe void UnsafeEncode(char* val2char, byte b, char* pch) { *pch = val2char[b >> 4]; pch[1] = val2char[b & 0xF]; } [SecurityCritical] private unsafe void UnsafeParse(char* chars, int charCount) { if (charCount != 45 || *chars != 'u' || chars[1] != 'r' || chars[2] != 'n' || chars[3] != ':' || chars[4] != 'u' || chars[5] != 'u' || chars[6] != 'i' || chars[7] != 'd' || chars[8] != ':' || chars[17] != '-' || chars[22] != '-' || chars[27] != '-' || chars[32] != '-') { return; } byte* ptr = stackalloc byte[16]; int num = 0; fixed (short* ptr2 = char2val) { short* ptr3 = ptr2; num = UnsafeDecode(ptr3, chars[15], chars[16]); *ptr = (byte)num; int num2 = 0 | num; num = UnsafeDecode(ptr3, chars[13], chars[14]); ptr[1] = (byte)num; int num3 = num2 | num; num = UnsafeDecode(ptr3, chars[11], chars[12]); ptr[2] = (byte)num; int num4 = num3 | num; num = UnsafeDecode(ptr3, chars[9], chars[10]); ptr[3] = (byte)num; int num5 = num4 | num; num = UnsafeDecode(ptr3, chars[20], chars[21]); ptr[4] = (byte)num; int num6 = num5 | num; num = UnsafeDecode(ptr3, chars[18], chars[19]); ptr[5] = (byte)num; int num7 = num6 | num; num = UnsafeDecode(ptr3, chars[25], chars[26]); ptr[6] = (byte)num; int num8 = num7 | num; num = UnsafeDecode(ptr3, chars[23], chars[24]); ptr[7] = (byte)num; int num9 = num8 | num; num = UnsafeDecode(ptr3, chars[28], chars[29]); ptr[8] = (byte)num; int num10 = num9 | num; num = UnsafeDecode(ptr3, chars[30], chars[31]); ptr[9] = (byte)num; int num11 = num10 | num; num = UnsafeDecode(ptr3, chars[33], chars[34]); ptr[10] = (byte)num; int num12 = num11 | num; num = UnsafeDecode(ptr3, chars[35], chars[36]); ptr[11] = (byte)num; int num13 = num12 | num; num = UnsafeDecode(ptr3, chars[37], chars[38]); ptr[12] = (byte)num; int num14 = num13 | num; num = UnsafeDecode(ptr3, chars[39], chars[40]); ptr[13] = (byte)num; int num15 = num14 | num; num = UnsafeDecode(ptr3, chars[41], chars[42]); ptr[14] = (byte)num; int num16 = num15 | num; num = UnsafeDecode(ptr3, chars[43], chars[44]); ptr[15] = (byte)num; if ((num16 | num) >= 256) { return; } idLow = UnsafeGetInt64(ptr); idHigh = UnsafeGetInt64(ptr + 8); } } [SecuritySafeCritical] public unsafe int ToCharArray(char[] chars, int offset) { int charArrayLength = CharArrayLength; if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > chars.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length))); } if (charArrayLength > chars.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("chars", System.Runtime.Serialization.SR.GetString("Array too small. Must be able to hold at least {0}.", charArrayLength))); } if (s != null) { s.CopyTo(0, chars, offset, charArrayLength); } else { byte* ptr = stackalloc byte[16]; UnsafeSetInt64(idLow, ptr); UnsafeSetInt64(idHigh, ptr + 8); fixed (char* ptr2 = &chars[offset]) { *ptr2 = 'u'; ptr2[1] = 'r'; ptr2[2] = 'n'; ptr2[3] = ':'; ptr2[4] = 'u'; ptr2[5] = 'u'; ptr2[6] = 'i'; ptr2[7] = 'd'; ptr2[8] = ':'; ptr2[17] = '-'; ptr2[22] = '-'; ptr2[27] = '-'; ptr2[32] = '-'; fixed (char* ptr3 = "0123456789abcdef") { char* ptr4 = ptr3; UnsafeEncode(ptr4, *ptr, ptr2 + 15); UnsafeEncode(ptr4, ptr[1], ptr2 + 13); UnsafeEncode(ptr4, ptr[2], ptr2 + 11); UnsafeEncode(ptr4, ptr[3], ptr2 + 9); UnsafeEncode(ptr4, ptr[4], ptr2 + 20); UnsafeEncode(ptr4, ptr[5], ptr2 + 18); UnsafeEncode(ptr4, ptr[6], ptr2 + 25); UnsafeEncode(ptr4, ptr[7], ptr2 + 23); UnsafeEncode(ptr4, ptr[8], ptr2 + 28); UnsafeEncode(ptr4, ptr[9], ptr2 + 30); UnsafeEncode(ptr4, ptr[10], ptr2 + 33); UnsafeEncode(ptr4, ptr[11], ptr2 + 35); UnsafeEncode(ptr4, ptr[12], ptr2 + 37); UnsafeEncode(ptr4, ptr[13], ptr2 + 39); UnsafeEncode(ptr4, ptr[14], ptr2 + 41); UnsafeEncode(ptr4, ptr[15], ptr2 + 43); } } } return charArrayLength; } public bool TryGetGuid(out Guid guid) { byte[] array = new byte[16]; if (!TryGetGuid(array, 0)) { guid = Guid.Empty; return false; } guid = new Guid(array); return true; } [SecuritySafeCritical] public unsafe bool TryGetGuid(byte[] buffer, int offset) { if (!IsGuid) { return false; } if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("buffer")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > buffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", buffer.Length))); } if (16 > buffer.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("buffer", System.Runtime.Serialization.SR.GetString("Array too small. Must be able to hold at least {0}.", 16))); } fixed (byte* ptr = &buffer[offset]) { UnsafeSetInt64(idLow, ptr); UnsafeSetInt64(idHigh, ptr + 8); } return true; } [SecuritySafeCritical] public override string ToString() { if (s == null) { int charArrayLength = CharArrayLength; char[] array = new char[charArrayLength]; ToCharArray(array, 0); s = new string(array, 0, charArrayLength); } return s; } public static bool operator ==(UniqueId id1, UniqueId id2) { if ((object)id1 == null && (object)id2 == null) { return true; } if ((object)id1 == null || (object)id2 == null) { return false; } if (id1.IsGuid && id2.IsGuid) { if (id1.idLow == id2.idLow) { return id1.idHigh == id2.idHigh; } return false; } return id1.ToString() == id2.ToString(); } public static bool operator !=(UniqueId id1, UniqueId id2) { return !(id1 == id2); } public override bool Equals(object obj) { return this == obj as UniqueId; } public override int GetHashCode() { if (IsGuid) { long num = idLow ^ idHigh; return (int)(num >> 32) ^ (int)num; } return ToString().GetHashCode(); } [SecurityCritical] private unsafe long UnsafeGetInt64(byte* pb) { int num = UnsafeGetInt32(pb); return ((long)UnsafeGetInt32(pb + 4) << 32) | (uint)num; } [SecurityCritical] private unsafe int UnsafeGetInt32(byte* pb) { return (((((pb[3] << 8) | pb[2]) << 8) | pb[1]) << 8) | *pb; } [SecurityCritical] private unsafe void UnsafeSetInt64(long value, byte* pb) { UnsafeSetInt32((int)value, pb); UnsafeSetInt32((int)(value >> 32), pb + 4); } [SecurityCritical] private unsafe void UnsafeSetInt32(int value, byte* pb) { *pb = (byte)value; value >>= 8; pb[1] = (byte)value; value >>= 8; pb[2] = (byte)value; value >>= 8; pb[3] = (byte)value; } } internal enum ValueHandleConstStringType { String, Number, Array, Object, Boolean, Null } internal static class ValueHandleLength { public const int Int8 = 1; public const int Int16 = 2; public const int Int32 = 4; public const int Int64 = 8; public const int UInt64 = 8; public const int Single = 4; public const int Double = 8; public const int Decimal = 16; public const int DateTime = 8; public const int TimeSpan = 8; public const int Guid = 16; public const int UniqueId = 16; } internal enum ValueHandleType { Empty, True, False, Zero, One, Int8, Int16, Int32, Int64, UInt64, Single, Double, Decimal, DateTime, TimeSpan, Guid, UniqueId, UTF8, EscapedUTF8, Base64, Dictionary, List, Char, Unicode, QName, ConstString } internal class ValueHandle { private XmlBufferReader bufferReader; private ValueHandleType type; private int offset; private int length; private static Base64Encoding base64Encoding; private static string[] constStrings = new string[6] { "string", "number", "array", "object", "boolean", "null" }; private static Base64Encoding Base64Encoding { get { if (base64Encoding == null) { base64Encoding = new Base64Encoding(); } return base64Encoding; } } public ValueHandle(XmlBufferReader bufferReader) { this.bufferReader = bufferReader; type = ValueHandleType.Empty; } public void SetConstantValue(ValueHandleConstStringType constStringType) { type = ValueHandleType.ConstString; offset = (int)constStringType; } public void SetValue(ValueHandleType type) { this.type = type; } public void SetDictionaryValue(int key) { SetValue(ValueHandleType.Dictionary, key, 0); } public void SetCharValue(int ch) { SetValue(ValueHandleType.Char, ch, 0); } public void SetQNameValue(int prefix, int key) { SetValue(ValueHandleType.QName, key, prefix); } public void SetValue(ValueHandleType type, int offset, int length) { this.type = type; this.offset = offset; this.length = length; } public bool IsWhitespace() { switch (type) { case ValueHandleType.UTF8: return bufferReader.IsWhitespaceUTF8(offset, length); case ValueHandleType.Dictionary: return bufferReader.IsWhitespaceKey(offset); case ValueHandleType.Char: { int @char = GetChar(); if (@char > 65535) { return false; } return XmlConverter.IsWhitespace((char)@char); } case ValueHandleType.EscapedUTF8: return bufferReader.IsWhitespaceUTF8(offset, length); case ValueHandleType.Unicode: return bufferReader.IsWhitespaceUnicode(offset, length); case ValueHandleType.True: case ValueHandleType.False: case ValueHandleType.Zero: case ValueHandleType.One: return false; case ValueHandleType.ConstString: return constStrings[offset].Length == 0; default: return length == 0; } } public Type ToType() { switch (type) { case ValueHandleType.True: case ValueHandleType.False: return typeof(bool); case ValueHandleType.Zero: case ValueHandleType.One: case ValueHandleType.Int8: case ValueHandleType.Int16: case ValueHandleType.Int32: return typeof(int); case ValueHandleType.Int64: return typeof(long); case ValueHandleType.UInt64: return typeof(ulong); case ValueHandleType.Single: return typeof(float); case ValueHandleType.Double: return typeof(double); case ValueHandleType.Decimal: return typeof(decimal); case ValueHandleType.DateTime: return typeof(DateTime); case ValueHandleType.Empty: case ValueHandleType.UTF8: case ValueHandleType.EscapedUTF8: case ValueHandleType.Dictionary: case ValueHandleType.Char: case ValueHandleType.Unicode: case ValueHandleType.QName: case ValueHandleType.ConstString: return typeof(string); case ValueHandleType.Base64: return typeof(byte[]); case ValueHandleType.List: return typeof(object[]); case ValueHandleType.UniqueId: return typeof(UniqueId); case ValueHandleType.Guid: return typeof(Guid); case ValueHandleType.TimeSpan: return typeof(TimeSpan); default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); } } public bool ToBoolean() { switch (type) { case ValueHandleType.False: return false; case ValueHandleType.True: return true; case ValueHandleType.UTF8: return XmlConverter.ToBoolean(bufferReader.Buffer, offset, length); case ValueHandleType.Int8: switch (GetInt8()) { case 0: return false; case 1: return true; } break; } return XmlConverter.ToBoolean(GetString()); } public int ToInt() { ValueHandleType valueHandleType = type; switch (valueHandleType) { case ValueHandleType.Zero: return 0; case ValueHandleType.One: return 1; case ValueHandleType.Int8: return GetInt8(); case ValueHandleType.Int16: return GetInt16(); case ValueHandleType.Int32: return GetInt32(); case ValueHandleType.Int64: { long @int = GetInt64(); if (@int >= int.MinValue && @int <= int.MaxValue) { return (int)@int; } break; } } if (valueHandleType == ValueHandleType.UInt64) { ulong uInt = GetUInt64(); if (uInt <= int.MaxValue) { return (int)uInt; } } if (valueHandleType == ValueHandleType.UTF8) { return XmlConverter.ToInt32(bufferReader.Buffer, offset, length); } return XmlConverter.ToInt32(GetString()); } public long ToLong() { ValueHandleType valueHandleType = type; switch (valueHandleType) { case ValueHandleType.Zero: return 0L; case ValueHandleType.One: return 1L; case ValueHandleType.Int8: return GetInt8(); case ValueHandleType.Int16: return GetInt16(); case ValueHandleType.Int32: return GetInt32(); case ValueHandleType.Int64: return GetInt64(); case ValueHandleType.UInt64: { ulong uInt = GetUInt64(); if (uInt <= long.MaxValue) { return (long)uInt; } break; } } if (valueHandleType == ValueHandleType.UTF8) { return XmlConverter.ToInt64(bufferReader.Buffer, offset, length); } return XmlConverter.ToInt64(GetString()); } public ulong ToULong() { ValueHandleType valueHandleType = type; switch (valueHandleType) { case ValueHandleType.Zero: return 0uL; case ValueHandleType.One: return 1uL; case ValueHandleType.Int8: case ValueHandleType.Int16: case ValueHandleType.Int32: case ValueHandleType.Int64: { long num = ToLong(); if (num >= 0) { return (ulong)num; } break; } } return valueHandleType switch { ValueHandleType.UInt64 => GetUInt64(), ValueHandleType.UTF8 => XmlConverter.ToUInt64(bufferReader.Buffer, offset, length), _ => XmlConverter.ToUInt64(GetString()), }; } public float ToSingle() { ValueHandleType valueHandleType = type; switch (valueHandleType) { case ValueHandleType.Single: return GetSingle(); case ValueHandleType.Double: { double @double = GetDouble(); if ((@double >= -3.4028234663852886E+38 && @double <= 3.4028234663852886E+38) || double.IsInfinity(@double) || double.IsNaN(@double)) { return (float)@double; } break; } } return valueHandleType switch { ValueHandleType.Zero => 0f, ValueHandleType.One => 1f, ValueHandleType.Int8 => GetInt8(), ValueHandleType.Int16 => GetInt16(), ValueHandleType.UTF8 => XmlConverter.ToSingle(bufferReader.Buffer, offset, length), _ => XmlConverter.ToSingle(GetString()), }; } public double ToDouble() { return type switch { ValueHandleType.Double => GetDouble(), ValueHandleType.Single => GetSingle(), ValueHandleType.Zero => 0.0, ValueHandleType.One => 1.0, ValueHandleType.Int8 => GetInt8(), ValueHandleType.Int16 => GetInt16(), ValueHandleType.Int32 => GetInt32(), ValueHandleType.UTF8 => XmlConverter.ToDouble(bufferReader.Buffer, offset, length), _ => XmlConverter.ToDouble(GetString()), }; } public decimal ToDecimal() { ValueHandleType valueHandleType = type; switch (valueHandleType) { case ValueHandleType.Decimal: return GetDecimal(); case ValueHandleType.Zero: return 0m; case ValueHandleType.One: return 1m; case ValueHandleType.Int8: case ValueHandleType.Int16: case ValueHandleType.Int32: case ValueHandleType.Int64: return ToLong(); default: return valueHandleType switch { ValueHandleType.UInt64 => GetUInt64(), ValueHandleType.UTF8 => XmlConverter.ToDecimal(bufferReader.Buffer, offset, length), _ => XmlConverter.ToDecimal(GetString()), }; } } public DateTime ToDateTime() { if (type == ValueHandleType.DateTime) { return XmlConverter.ToDateTime(GetInt64()); } if (type == ValueHandleType.UTF8) { return XmlConverter.ToDateTime(bufferReader.Buffer, offset, length); } return XmlConverter.ToDateTime(GetString()); } public UniqueId ToUniqueId() { if (type == ValueHandleType.UniqueId) { return GetUniqueId(); } if (type == ValueHandleType.UTF8) { return XmlConverter.ToUniqueId(bufferReader.Buffer, offset, length); } return XmlConverter.ToUniqueId(GetString()); } public TimeSpan ToTimeSpan() { if (type == ValueHandleType.TimeSpan) { return new TimeSpan(GetInt64()); } if (type == ValueHandleType.UTF8) { return XmlConverter.ToTimeSpan(bufferReader.Buffer, offset, length); } return XmlConverter.ToTimeSpan(GetString()); } public Guid ToGuid() { if (type == ValueHandleType.Guid) { return GetGuid(); } if (type == ValueHandleType.UTF8) { return XmlConverter.ToGuid(bufferReader.Buffer, offset, length); } return XmlConverter.ToGuid(GetString()); } public override string ToString() { return GetString(); } public byte[] ToByteArray() { if (type == ValueHandleType.Base64) { byte[] array = new byte[length]; GetBase64(array, 0, length); return array; } if (type == ValueHandleType.UTF8 && length % 4 == 0) { try { int num = length / 4 * 3; if (length > 0 && bufferReader.Buffer[offset + length - 1] == 61) { num--; if (bufferReader.Buffer[offset + length - 2] == 61) { num--; } } byte[] array2 = new byte[num]; int bytes = Base64Encoding.GetBytes(bufferReader.Buffer, offset, length, array2, 0); if (bytes != array2.Length) { byte[] array3 = new byte[bytes]; Buffer.BlockCopy(array2, 0, array3, 0, bytes); array2 = array3; } return array2; } catch (FormatException) { } } try { return Base64Encoding.GetBytes(XmlConverter.StripWhitespace(GetString())); } catch (FormatException ex2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(ex2.Message, ex2.InnerException)); } } public string GetString() { ValueHandleType valueHandleType = type; if (valueHandleType == ValueHandleType.UTF8) { return GetCharsText(); } switch (valueHandleType) { case ValueHandleType.False: return "false"; case ValueHandleType.True: return "true"; case ValueHandleType.Zero: return "0"; case ValueHandleType.One: return "1"; case ValueHandleType.Int8: case ValueHandleType.Int16: case ValueHandleType.Int32: return XmlConverter.ToString(ToInt()); case ValueHandleType.Int64: return XmlConverter.ToString(GetInt64()); case ValueHandleType.UInt64: return XmlConverter.ToString(GetUInt64()); case ValueHandleType.Single: return XmlConverter.ToString(GetSingle()); case ValueHandleType.Double: return XmlConverter.ToString(GetDouble()); case ValueHandleType.Decimal: return XmlConverter.ToString(GetDecimal()); case ValueHandleType.DateTime: return XmlConverter.ToString(ToDateTime()); case ValueHandleType.Empty: return string.Empty; case ValueHandleType.UTF8: return GetCharsText(); case ValueHandleType.Unicode: return GetUnicodeCharsText(); case ValueHandleType.EscapedUTF8: return GetEscapedCharsText(); case ValueHandleType.Char: return GetCharText(); case ValueHandleType.Dictionary: return GetDictionaryString().Value; case ValueHandleType.Base64: return Base64Encoding.GetString(ToByteArray()); case ValueHandleType.List: return XmlConverter.ToString(ToList()); case ValueHandleType.UniqueId: return XmlConverter.ToString(ToUniqueId()); case ValueHandleType.Guid: return XmlConverter.ToString(ToGuid()); case ValueHandleType.TimeSpan: return XmlConverter.ToString(ToTimeSpan()); case ValueHandleType.QName: return GetQNameDictionaryText(); case ValueHandleType.ConstString: return constStrings[offset]; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); } } public bool Equals2(string str, bool checkLower) { if (type != ValueHandleType.UTF8) { return GetString() == str; } if (length != str.Length) { return false; } byte[] buffer = bufferReader.Buffer; for (int i = 0; i < length; i++) { byte b = buffer[i + offset]; if (b != str[i] && (!checkLower || char.ToLowerInvariant((char)b) != str[i])) { return false; } } return true; } public void Sign(XmlSigningNodeWriter writer) { switch (type) { case ValueHandleType.Int8: case ValueHandleType.Int16: case ValueHandleType.Int32: writer.WriteInt32Text(ToInt()); break; case ValueHandleType.Int64: writer.WriteInt64Text(GetInt64()); break; case ValueHandleType.UInt64: writer.WriteUInt64Text(GetUInt64()); break; case ValueHandleType.Single: writer.WriteFloatText(GetSingle()); break; case ValueHandleType.Double: writer.WriteDoubleText(GetDouble()); break; case ValueHandleType.Decimal: writer.WriteDecimalText(GetDecimal()); break; case ValueHandleType.DateTime: writer.WriteDateTimeText(ToDateTime()); break; case ValueHandleType.UTF8: writer.WriteEscapedText(bufferReader.Buffer, offset, length); break; case ValueHandleType.Base64: writer.WriteBase64Text(bufferReader.Buffer, 0, bufferReader.Buffer, offset, length); break; case ValueHandleType.UniqueId: writer.WriteUniqueIdText(ToUniqueId()); break; case ValueHandleType.Guid: writer.WriteGuidText(ToGuid()); break; case ValueHandleType.TimeSpan: writer.WriteTimeSpanText(ToTimeSpan()); break; default: writer.WriteEscapedText(GetString()); break; case ValueHandleType.Empty: break; } } public object[] ToList() { return bufferReader.GetList(offset, length); } public object ToObject() { switch (type) { case ValueHandleType.True: case ValueHandleType.False: return ToBoolean(); case ValueHandleType.Zero: case ValueHandleType.One: case ValueHandleType.Int8: case ValueHandleType.Int16: case ValueHandleType.Int32: return ToInt(); case ValueHandleType.Int64: return ToLong(); case ValueHandleType.UInt64: return GetUInt64(); case ValueHandleType.Single: return ToSingle(); case ValueHandleType.Double: return ToDouble(); case ValueHandleType.Decimal: return ToDecimal(); case ValueHandleType.DateTime: return ToDateTime(); case ValueHandleType.Empty: case ValueHandleType.UTF8: case ValueHandleType.EscapedUTF8: case ValueHandleType.Dictionary: case ValueHandleType.Char: case ValueHandleType.Unicode: case ValueHandleType.ConstString: return ToString(); case ValueHandleType.Base64: return ToByteArray(); case ValueHandleType.List: return ToList(); case ValueHandleType.UniqueId: return ToUniqueId(); case ValueHandleType.Guid: return ToGuid(); case ValueHandleType.TimeSpan: return ToTimeSpan(); default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); } } public bool TryReadBase64(byte[] buffer, int offset, int count, out int actual) { if (type == ValueHandleType.Base64) { actual = Math.Min(length, count); GetBase64(buffer, offset, actual); this.offset += actual; length -= actual; return true; } if (type == ValueHandleType.UTF8 && count >= 3 && length % 4 == 0) { try { int num = Math.Min(count / 3 * 4, length); actual = Base64Encoding.GetBytes(bufferReader.Buffer, this.offset, num, buffer, offset); this.offset += num; length -= num; return true; } catch (FormatException) { } } actual = 0; return false; } public bool TryReadChars(char[] chars, int offset, int count, out int actual) { if (type == ValueHandleType.Unicode) { return TryReadUnicodeChars(chars, offset, count, out actual); } if (type != ValueHandleType.UTF8) { actual = 0; return false; } int num = offset; int num2 = count; byte[] buffer = bufferReader.Buffer; int num3 = this.offset; int num4 = length; bool flag = false; while (true) { if (num2 > 0 && num4 > 0) { byte b = buffer[num3]; if (b < 128) { chars[num] = (char)b; num3++; num4--; num++; num2--; continue; } } if (num2 == 0 || num4 == 0 || flag) { break; } UTF8Encoding uTF8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); int chars2; int num5; try { if (num2 >= uTF8Encoding.GetMaxCharCount(num4) || num2 >= uTF8Encoding.GetCharCount(buffer, num3, num4)) { chars2 = uTF8Encoding.GetChars(buffer, num3, num4, chars, num); num5 = num4; } else { Decoder decoder = uTF8Encoding.GetDecoder(); num5 = Math.Min(num2, num4); chars2 = decoder.GetChars(buffer, num3, num5, chars, num); while (chars2 == 0) { if (num5 >= 3 && num2 < 2) { flag = true; break; } chars2 = decoder.GetChars(buffer, num3 + num5, 1, chars, num); num5++; } num5 = uTF8Encoding.GetByteCount(chars, num, chars2); } } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(buffer, num3, num4, exception)); } num3 += num5; num4 -= num5; num += chars2; num2 -= chars2; } this.offset = num3; length = num4; actual = count - num2; return true; } private bool TryReadUnicodeChars(char[] chars, int offset, int count, out int actual) { int num = Math.Min(count, length / 2); for (int i = 0; i < num; i++) { chars[offset + i] = (char)bufferReader.GetInt16(this.offset + i * 2); } this.offset += num * 2; length -= num * 2; actual = num; return true; } public bool TryGetDictionaryString(out XmlDictionaryString value) { if (type == ValueHandleType.Dictionary) { value = GetDictionaryString(); return true; } value = null; return false; } public bool TryGetByteArrayLength(out int length) { if (type == ValueHandleType.Base64) { length = this.length; return true; } length = 0; return false; } private string GetCharsText() { if (length == 1 && bufferReader.GetByte(offset) == 49) { return "1"; } return bufferReader.GetString(offset, length); } private string GetUnicodeCharsText() { return bufferReader.GetUnicodeString(offset, length); } private string GetEscapedCharsText() { return bufferReader.GetEscapedString(offset, length); } private string GetCharText() { int @char = GetChar(); if (@char > 65535) { SurrogateChar surrogateChar = new SurrogateChar(@char); return new string(new char[2] { surrogateChar.HighChar, surrogateChar.LowChar }, 0, 2); } return ((char)@char).ToString(); } private int GetChar() { return offset; } private int GetInt8() { return bufferReader.GetInt8(offset); } private int GetInt16() { return bufferReader.GetInt16(offset); } private int GetInt32() { return bufferReader.GetInt32(offset); } private long GetInt64() { return bufferReader.GetInt64(offset); } private ulong GetUInt64() { return bufferReader.GetUInt64(offset); } private float GetSingle() { return bufferReader.GetSingle(offset); } private double GetDouble() { return bufferReader.GetDouble(offset); } private decimal GetDecimal() { return bufferReader.GetDecimal(offset); } private UniqueId GetUniqueId() { return bufferReader.GetUniqueId(offset); } private Guid GetGuid() { return bufferReader.GetGuid(offset); } private void GetBase64(byte[] buffer, int offset, int count) { bufferReader.GetBase64(this.offset, buffer, offset, count); } private XmlDictionaryString GetDictionaryString() { return bufferReader.GetDictionaryString(offset); } private string GetQNameDictionaryText() { return PrefixHandle.GetString(PrefixHandle.GetAlphaPrefix(length)) + ":" + bufferReader.GetDictionaryString(offset); } } internal abstract class XmlBaseReader : XmlDictionaryReader { protected enum QNameType { Normal, Xmlns } protected class XmlNode { protected enum XmlNodeFlags { None = 0, CanGetAttribute = 1, CanMoveToElement = 2, HasValue = 4, AtomicValue = 8, SkipValue = 0x10, HasContent = 0x20 } private XmlNodeType nodeType; private PrefixHandle prefix; private StringHandle localName; private ValueHandle value; private Namespace ns; private bool hasValue; private bool canGetAttribute; private bool canMoveToElement; private ReadState readState; private XmlAttributeTextNode attributeTextNode; private bool exitScope; private int depthDelta; private bool isAtomicValue; private bool skipValue; private QNameType qnameType; private bool hasContent; private bool isEmptyElement; private char quoteChar; public bool HasValue => hasValue; public ReadState ReadState => readState; public StringHandle LocalName => localName; public PrefixHandle Prefix => prefix; public bool CanGetAttribute => canGetAttribute; public bool CanMoveToElement => canMoveToElement; public XmlAttributeTextNode AttributeText => attributeTextNode; public bool SkipValue => skipValue; public ValueHandle Value => value; public int DepthDelta => depthDelta; public bool HasContent => hasContent; public XmlNodeType NodeType { get { return nodeType; } set { nodeType = value; } } public QNameType QNameType { get { return qnameType; } set { qnameType = value; } } public Namespace Namespace { get { return ns; } set { ns = value; } } public bool IsAtomicValue { get { return isAtomicValue; } set { isAtomicValue = value; } } public bool ExitScope { get { return exitScope; } set { exitScope = value; } } public bool IsEmptyElement { get { return isEmptyElement; } set { isEmptyElement = value; } } public char QuoteChar { get { return quoteChar; } set { quoteChar = value; } } public string ValueAsString { get { if (qnameType == QNameType.Normal) { return Value.GetString(); } return Namespace.Uri.GetString(); } } protected XmlNode(XmlNodeType nodeType, PrefixHandle prefix, StringHandle localName, ValueHandle value, XmlNodeFlags nodeFlags, ReadState readState, XmlAttributeTextNode attributeTextNode, int depthDelta) { this.nodeType = nodeType; this.prefix = prefix; this.localName = localName; this.value = value; ns = NamespaceManager.EmptyNamespace; hasValue = (nodeFlags & XmlNodeFlags.HasValue) != 0; canGetAttribute = (nodeFlags & XmlNodeFlags.CanGetAttribute) != 0; canMoveToElement = (nodeFlags & XmlNodeFlags.CanMoveToElement) != 0; isAtomicValue = (nodeFlags & XmlNodeFlags.AtomicValue) != 0; skipValue = (nodeFlags & XmlNodeFlags.SkipValue) != 0; hasContent = (nodeFlags & XmlNodeFlags.HasContent) != 0; this.readState = readState; this.attributeTextNode = attributeTextNode; exitScope = nodeType == XmlNodeType.EndElement; this.depthDelta = depthDelta; isEmptyElement = false; quoteChar = '"'; qnameType = QNameType.Normal; } public bool IsLocalName(string localName) { if (qnameType == QNameType.Normal) { return LocalName == localName; } return Namespace.Prefix == localName; } public bool IsLocalName(XmlDictionaryString localName) { if (qnameType == QNameType.Normal) { return LocalName == localName; } return Namespace.Prefix == localName; } public bool IsNamespaceUri(string ns) { if (qnameType == QNameType.Normal) { return Namespace.IsUri(ns); } return ns == "http://www.w3.org/2000/xmlns/"; } public bool IsNamespaceUri(XmlDictionaryString ns) { if (qnameType == QNameType.Normal) { return Namespace.IsUri(ns); } return ns.Value == "http://www.w3.org/2000/xmlns/"; } public bool IsLocalNameAndNamespaceUri(string localName, string ns) { if (qnameType == QNameType.Normal) { if (LocalName == localName) { return Namespace.IsUri(ns); } return false; } if (Namespace.Prefix == localName) { return ns == "http://www.w3.org/2000/xmlns/"; } return false; } public bool IsLocalNameAndNamespaceUri(XmlDictionaryString localName, XmlDictionaryString ns) { if (qnameType == QNameType.Normal) { if (LocalName == localName) { return Namespace.IsUri(ns); } return false; } if (Namespace.Prefix == localName) { return ns.Value == "http://www.w3.org/2000/xmlns/"; } return false; } public bool IsPrefixAndLocalName(string prefix, string localName) { if (qnameType == QNameType.Normal) { if (Prefix == prefix) { return LocalName == localName; } return false; } if (prefix == "xmlns") { return Namespace.Prefix == localName; } return false; } public bool TryGetLocalNameAsDictionaryString(out XmlDictionaryString localName) { if (qnameType == QNameType.Normal) { return LocalName.TryGetDictionaryString(out localName); } localName = null; return false; } public bool TryGetNamespaceUriAsDictionaryString(out XmlDictionaryString ns) { if (qnameType == QNameType.Normal) { return Namespace.Uri.TryGetDictionaryString(out ns); } ns = null; return false; } public bool TryGetValueAsDictionaryString(out XmlDictionaryString value) { if (qnameType == QNameType.Normal) { return Value.TryGetDictionaryString(out value); } value = null; return false; } } protected class XmlElementNode : XmlNode { private XmlEndElementNode endElementNode; private int bufferOffset; public int NameOffset; public int NameLength; public XmlEndElementNode EndElement => endElementNode; public int BufferOffset { get { return bufferOffset; } set { bufferOffset = value; } } public XmlElementNode(XmlBufferReader bufferReader) : this(new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader)) { } private XmlElementNode(PrefixHandle prefix, StringHandle localName, ValueHandle value) : base(XmlNodeType.Element, prefix, localName, value, (XmlNodeFlags)33, ReadState.Interactive, null, -1) { endElementNode = new XmlEndElementNode(prefix, localName, value); } } protected class XmlAttributeNode : XmlNode { public XmlAttributeNode(XmlBufferReader bufferReader) : this(new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader)) { } private XmlAttributeNode(PrefixHandle prefix, StringHandle localName, ValueHandle value) : base(XmlNodeType.Attribute, prefix, localName, value, (XmlNodeFlags)15, ReadState.Interactive, new XmlAttributeTextNode(prefix, localName, value), 0) { } } protected class XmlEndElementNode : XmlNode { public XmlEndElementNode(PrefixHandle prefix, StringHandle localName, ValueHandle value) : base(XmlNodeType.EndElement, prefix, localName, value, XmlNodeFlags.HasContent, ReadState.Interactive, null, -1) { } } protected class XmlTextNode : XmlNode { protected XmlTextNode(XmlNodeType nodeType, PrefixHandle prefix, StringHandle localName, ValueHandle value, XmlNodeFlags nodeFlags, ReadState readState, XmlAttributeTextNode attributeTextNode, int depthDelta) : base(nodeType, prefix, localName, value, nodeFlags, readState, attributeTextNode, depthDelta) { } } protected class XmlAtomicTextNode : XmlTextNode { public XmlAtomicTextNode(XmlBufferReader bufferReader) : base(XmlNodeType.Text, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), (XmlNodeFlags)60, ReadState.Interactive, null, 0) { } } protected class XmlComplexTextNode : XmlTextNode { public XmlComplexTextNode(XmlBufferReader bufferReader) : base(XmlNodeType.Text, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), (XmlNodeFlags)36, ReadState.Interactive, null, 0) { } } protected class XmlWhitespaceTextNode : XmlTextNode { public XmlWhitespaceTextNode(XmlBufferReader bufferReader) : base(XmlNodeType.Whitespace, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), XmlNodeFlags.HasValue, ReadState.Interactive, null, 0) { } } protected class XmlCDataNode : XmlTextNode { public XmlCDataNode(XmlBufferReader bufferReader) : base(XmlNodeType.CDATA, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), (XmlNodeFlags)36, ReadState.Interactive, null, 0) { } } protected class XmlAttributeTextNode : XmlTextNode { public XmlAttributeTextNode(PrefixHandle prefix, StringHandle localName, ValueHandle value) : base(XmlNodeType.Text, prefix, localName, value, (XmlNodeFlags)47, ReadState.Interactive, null, 1) { } } protected class XmlInitialNode : XmlNode { public XmlInitialNode(XmlBufferReader bufferReader) : base(XmlNodeType.None, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), XmlNodeFlags.None, ReadState.Initial, null, 0) { } } protected class XmlDeclarationNode : XmlNode { public XmlDeclarationNode(XmlBufferReader bufferReader) : base(XmlNodeType.XmlDeclaration, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), XmlNodeFlags.CanGetAttribute, ReadState.Interactive, null, 0) { } } protected class XmlCommentNode : XmlNode { public XmlCommentNode(XmlBufferReader bufferReader) : base(XmlNodeType.Comment, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), XmlNodeFlags.HasValue, ReadState.Interactive, null, 0) { } } protected class XmlEndOfFileNode : XmlNode { public XmlEndOfFileNode(XmlBufferReader bufferReader) : base(XmlNodeType.None, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), XmlNodeFlags.None, ReadState.EndOfFile, null, 0) { } } protected class XmlClosedNode : XmlNode { public XmlClosedNode(XmlBufferReader bufferReader) : base(XmlNodeType.None, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), XmlNodeFlags.None, ReadState.Closed, null, 0) { } } private class AttributeSorter : IComparer { private object[] indeces; private XmlAttributeNode[] attributeNodes; private int attributeCount; private int attributeIndex1; private int attributeIndex2; public bool Sort(XmlAttributeNode[] attributeNodes, int attributeCount) { attributeIndex1 = -1; attributeIndex2 = -1; this.attributeNodes = attributeNodes; this.attributeCount = attributeCount; bool result = Sort(); this.attributeNodes = null; this.attributeCount = 0; return result; } public void GetIndeces(out int attributeIndex1, out int attributeIndex2) { attributeIndex1 = this.attributeIndex1; attributeIndex2 = this.attributeIndex2; } public void Close() { if (indeces != null && indeces.Length > 32) { indeces = null; } } private bool Sort() { if (indeces != null && indeces.Length == attributeCount && IsSorted()) { return true; } object[] array = new object[attributeCount]; for (int i = 0; i < array.Length; i++) { array[i] = i; } indeces = array; Array.Sort(indeces, 0, attributeCount, this); return IsSorted(); } private bool IsSorted() { for (int i = 0; i < indeces.Length - 1; i++) { if (Compare(indeces[i], indeces[i + 1]) >= 0) { attributeIndex1 = (int)indeces[i]; attributeIndex2 = (int)indeces[i + 1]; return false; } } return true; } public int Compare(object obj1, object obj2) { int num = (int)obj1; int num2 = (int)obj2; XmlAttributeNode xmlAttributeNode = attributeNodes[num]; XmlAttributeNode xmlAttributeNode2 = attributeNodes[num2]; int num3 = CompareQNameType(xmlAttributeNode.QNameType, xmlAttributeNode2.QNameType); if (num3 == 0) { if (xmlAttributeNode.QNameType == QNameType.Normal) { num3 = xmlAttributeNode.LocalName.CompareTo(xmlAttributeNode2.LocalName); if (num3 == 0) { num3 = xmlAttributeNode.Namespace.Uri.CompareTo(xmlAttributeNode2.Namespace.Uri); } } else { num3 = xmlAttributeNode.Namespace.Prefix.CompareTo(xmlAttributeNode2.Namespace.Prefix); } } return num3; } public int CompareQNameType(QNameType type1, QNameType type2) { return type1 - type2; } } private class NamespaceManager { private class XmlAttribute { private XmlSpace space; private string lang; private int depth; public int Depth { get { return depth; } set { depth = value; } } public string XmlLang { get { return lang; } set { lang = value; } } public XmlSpace XmlSpace { get { return space; } set { space = value; } } } private XmlBufferReader bufferReader; private Namespace[] namespaces; private int nsCount; private int depth; private Namespace[] shortPrefixUri; private static Namespace emptyNamespace = new Namespace(XmlBufferReader.Empty); private static Namespace xmlNamespace; private XmlAttribute[] attributes; private int attributeCount; private XmlSpace space; private string lang; public static Namespace XmlNamespace { get { if (xmlNamespace == null) { byte[] array = new byte[39] { 120, 109, 108, 104, 116, 116, 112, 58, 47, 47, 119, 119, 119, 46, 119, 51, 46, 111, 114, 103, 47, 88, 77, 76, 47, 49, 57, 57, 56, 47, 110, 97, 109, 101, 115, 112, 97, 99, 101 }; Namespace @namespace = new Namespace(new XmlBufferReader(array)); @namespace.Prefix.SetValue(0, 3); @namespace.Uri.SetValue(3, array.Length - 3); xmlNamespace = @namespace; } return xmlNamespace; } } public static Namespace EmptyNamespace => emptyNamespace; public string XmlLang => lang; public XmlSpace XmlSpace => space; public NamespaceManager(XmlBufferReader bufferReader) { this.bufferReader = bufferReader; shortPrefixUri = new Namespace[28]; shortPrefixUri[0] = emptyNamespace; namespaces = null; nsCount = 0; attributes = null; attributeCount = 0; space = XmlSpace.None; lang = string.Empty; depth = 0; } public void Close() { if (namespaces != null && namespaces.Length > 32) { namespaces = null; } if (attributes != null && attributes.Length > 4) { attributes = null; } lang = string.Empty; } public void Clear() { if (nsCount != 0) { if (shortPrefixUri != null) { for (int i = 0; i < shortPrefixUri.Length; i++) { shortPrefixUri[i] = null; } } shortPrefixUri[0] = emptyNamespace; nsCount = 0; } attributeCount = 0; space = XmlSpace.None; lang = string.Empty; depth = 0; } public void EnterScope() { depth++; } public void ExitScope() { while (nsCount > 0) { Namespace @namespace = namespaces[nsCount - 1]; if (@namespace.Depth != depth) { break; } if (@namespace.Prefix.TryGetShortPrefix(out var type)) { shortPrefixUri[(int)type] = @namespace.OuterUri; } nsCount--; } while (attributeCount > 0) { XmlAttribute xmlAttribute = attributes[attributeCount - 1]; if (xmlAttribute.Depth != depth) { break; } space = xmlAttribute.XmlSpace; lang = xmlAttribute.XmlLang; attributeCount--; } depth--; } public void Sign(XmlSigningNodeWriter writer) { for (int i = 0; i < nsCount; i++) { PrefixHandle prefix = namespaces[i].Prefix; bool flag = false; for (int j = i + 1; j < nsCount; j++) { if (object.Equals(prefix, namespaces[j].Prefix)) { flag = true; break; } } if (!flag) { int offset; int length; byte[] @string = prefix.GetString(out offset, out length); int offset2; int length2; byte[] string2 = namespaces[i].Uri.GetString(out offset2, out length2); writer.WriteXmlnsAttribute(@string, offset, length, string2, offset2, length2); } } } public void AddLangAttribute(string lang) { AddAttribute(); this.lang = lang; } public void AddSpaceAttribute(XmlSpace space) { AddAttribute(); this.space = space; } private void AddAttribute() { if (attributes == null) { attributes = new XmlAttribute[1]; } else if (attributes.Length == attributeCount) { XmlAttribute[] destinationArray = new XmlAttribute[attributeCount * 2]; Array.Copy(attributes, destinationArray, attributeCount); attributes = destinationArray; } XmlAttribute xmlAttribute = attributes[attributeCount]; if (xmlAttribute == null) { xmlAttribute = new XmlAttribute(); attributes[attributeCount] = xmlAttribute; } xmlAttribute.XmlLang = lang; xmlAttribute.XmlSpace = space; xmlAttribute.Depth = depth; attributeCount++; } public void Register(Namespace nameSpace) { if (nameSpace.Prefix.TryGetShortPrefix(out var type)) { nameSpace.OuterUri = shortPrefixUri[(int)type]; shortPrefixUri[(int)type] = nameSpace; } else { nameSpace.OuterUri = null; } } public Namespace AddNamespace() { if (namespaces == null) { namespaces = new Namespace[4]; } else if (namespaces.Length == nsCount) { Namespace[] destinationArray = new Namespace[nsCount * 2]; Array.Copy(namespaces, destinationArray, nsCount); namespaces = destinationArray; } Namespace @namespace = namespaces[nsCount]; if (@namespace == null) { @namespace = new Namespace(bufferReader); namespaces[nsCount] = @namespace; } @namespace.Clear(); @namespace.Depth = depth; nsCount++; return @namespace; } public Namespace LookupNamespace(PrefixHandleType prefix) { return shortPrefixUri[(int)prefix]; } public Namespace LookupNamespace(PrefixHandle prefix) { if (prefix.TryGetShortPrefix(out var type)) { return LookupNamespace(type); } for (int num = nsCount - 1; num >= 0; num--) { Namespace @namespace = namespaces[num]; if (@namespace.Prefix == prefix) { return @namespace; } } if (prefix.IsXml) { return XmlNamespace; } return null; } public Namespace LookupNamespace(string prefix) { if (TryGetShortPrefix(prefix, out var shortPrefix)) { return LookupNamespace(shortPrefix); } for (int num = nsCount - 1; num >= 0; num--) { Namespace @namespace = namespaces[num]; if (@namespace.Prefix == prefix) { return @namespace; } } if (prefix == "xml") { return XmlNamespace; } return null; } private bool TryGetShortPrefix(string s, out PrefixHandleType shortPrefix) { switch (s.Length) { case 0: shortPrefix = PrefixHandleType.Empty; return true; case 1: { char c = s[0]; if (c >= 'a' && c <= 'z') { shortPrefix = PrefixHandle.GetAlphaPrefix(c - 97); return true; } break; } } shortPrefix = PrefixHandleType.Empty; return false; } } protected class Namespace { private PrefixHandle prefix; private StringHandle uri; private int depth; private Namespace outerUri; private string uriString; public int Depth { get { return depth; } set { depth = value; } } public PrefixHandle Prefix => prefix; public StringHandle Uri => uri; public Namespace OuterUri { get { return outerUri; } set { outerUri = value; } } public Namespace(XmlBufferReader bufferReader) { prefix = new PrefixHandle(bufferReader); uri = new StringHandle(bufferReader); outerUri = null; uriString = null; } public void Clear() { uriString = null; } public bool IsUri(string s) { if ((object)s == uriString) { return true; } if (uri == s) { uriString = s; return true; } return false; } public bool IsUri(XmlDictionaryString s) { if ((object)s.Value == uriString) { return true; } if (uri == s) { uriString = s.Value; return true; } return false; } } private class QuotaNameTable : XmlNameTable { private XmlDictionaryReader reader; private XmlNameTable nameTable; private int maxCharCount; private int charCount; public QuotaNameTable(XmlDictionaryReader reader, int maxCharCount) { this.reader = reader; nameTable = new NameTable(); this.maxCharCount = maxCharCount; charCount = 0; } public override string Get(char[] chars, int offset, int count) { return nameTable.Get(chars, offset, count); } public override string Get(string value) { return nameTable.Get(value); } private void Add(int charCount) { if (charCount > maxCharCount - this.charCount) { XmlExceptionHelper.ThrowMaxNameTableCharCountExceeded(reader, maxCharCount); } this.charCount += charCount; } public override string Add(char[] chars, int offset, int count) { string text = nameTable.Get(chars, offset, count); if (text != null) { return text; } Add(count); return nameTable.Add(chars, offset, count); } public override string Add(string value) { string text = nameTable.Get(value); if (text != null) { return text; } Add(value.Length); return nameTable.Add(value); } } private XmlBufferReader bufferReader; private XmlNode node; private NamespaceManager nsMgr; private XmlElementNode[] elementNodes; private XmlAttributeNode[] attributeNodes; private XmlAtomicTextNode atomicTextNode; private int depth; private int attributeCount; private int attributeStart; private XmlDictionaryReaderQuotas quotas; private XmlNameTable nameTable; private XmlDeclarationNode declarationNode; private XmlComplexTextNode complexTextNode; private XmlWhitespaceTextNode whitespaceTextNode; private XmlCDataNode cdataNode; private XmlCommentNode commentNode; private XmlElementNode rootElementNode; private int attributeIndex; private char[] chars; private string prefix; private string localName; private string ns; private string value; private int trailCharCount; private int trailByteCount; private char[] trailChars; private byte[] trailBytes; private bool rootElement; private bool readingElement; private XmlSigningNodeWriter signingWriter; private bool signing; private AttributeSorter attributeSorter; private static XmlInitialNode initialNode = new XmlInitialNode(XmlBufferReader.Empty); private static XmlEndOfFileNode endOfFileNode = new XmlEndOfFileNode(XmlBufferReader.Empty); private static XmlClosedNode closedNode = new XmlClosedNode(XmlBufferReader.Empty); private static BinHexEncoding binhexEncoding; private static Base64Encoding base64Encoding; private const string xmlns = "xmlns"; private const string xml = "xml"; private const string xmlnsNamespace = "http://www.w3.org/2000/xmlns/"; private const string xmlNamespace = "http://www.w3.org/XML/1998/namespace"; private static BinHexEncoding BinHexEncoding { get { if (binhexEncoding == null) { binhexEncoding = new BinHexEncoding(); } return binhexEncoding; } } private static Base64Encoding Base64Encoding { get { if (base64Encoding == null) { base64Encoding = new Base64Encoding(); } return base64Encoding; } } protected XmlBufferReader BufferReader => bufferReader; public override XmlDictionaryReaderQuotas Quotas => quotas; protected XmlNode Node => node; protected XmlElementNode ElementNode { get { if (depth == 0) { return rootElementNode; } return elementNodes[depth]; } } protected bool OutsideRootElement => depth == 0; public override bool CanReadBinaryContent => true; public override bool CanReadValueChunk => true; public override string BaseURI => string.Empty; public override bool HasValue => node.HasValue; public override bool IsDefault => false; public override string this[int index] => GetAttribute(index); public override string this[string name] => GetAttribute(name); public override string this[string localName, string namespaceUri] => GetAttribute(localName, namespaceUri); public override int AttributeCount { get { if (node.CanGetAttribute) { return attributeCount; } return 0; } } public sealed override int Depth => depth + node.DepthDelta; public override bool EOF => node.ReadState == ReadState.EndOfFile; public sealed override bool IsEmptyElement => node.IsEmptyElement; public override string LocalName { get { if (localName == null) { localName = GetLocalName(enforceAtomization: true); } return localName; } } public override string NamespaceURI { get { if (ns == null) { ns = GetNamespaceUri(enforceAtomization: true); } return ns; } } public override XmlNameTable NameTable { get { if (nameTable == null) { nameTable = new QuotaNameTable(this, quotas.MaxNameTableCharCount); nameTable.Add("xml"); nameTable.Add("xmlns"); nameTable.Add("http://www.w3.org/2000/xmlns/"); nameTable.Add("http://www.w3.org/XML/1998/namespace"); for (PrefixHandleType prefixHandleType = PrefixHandleType.A; prefixHandleType <= PrefixHandleType.Z; prefixHandleType++) { nameTable.Add(PrefixHandle.GetString(prefixHandleType)); } } return nameTable; } } public sealed override XmlNodeType NodeType => node.NodeType; public override string Prefix { get { if (prefix == null) { switch (node.QNameType) { case QNameType.Normal: prefix = node.Prefix.GetString(NameTable); break; case QNameType.Xmlns: if (node.Namespace.Prefix.IsEmpty) { prefix = string.Empty; } else { prefix = "xmlns"; } break; default: prefix = "xml"; break; } } return prefix; } } public override char QuoteChar => node.QuoteChar; public override ReadState ReadState => node.ReadState; public override string Value { get { if (value == null) { value = node.ValueAsString; } return value; } } public override Type ValueType { get { if (value == null && node.QNameType == QNameType.Normal) { Type type = node.Value.ToType(); if (node.IsAtomicValue) { return type; } if (type == typeof(byte[])) { return type; } } return typeof(string); } } public override string XmlLang => nsMgr.XmlLang; public override XmlSpace XmlSpace => nsMgr.XmlSpace; public override bool CanCanonicalize => true; protected bool Signing => signing; protected XmlBaseReader() { bufferReader = new XmlBufferReader(this); nsMgr = new NamespaceManager(bufferReader); quotas = new XmlDictionaryReaderQuotas(); rootElementNode = new XmlElementNode(bufferReader); atomicTextNode = new XmlAtomicTextNode(bufferReader); node = closedNode; } protected void MoveToNode(XmlNode node) { this.node = node; ns = null; localName = null; prefix = null; value = null; } protected void MoveToInitial(XmlDictionaryReaderQuotas quotas) { if (quotas == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("quotas"); } quotas.InternalCopyTo(this.quotas); this.quotas.MakeReadOnly(); nsMgr.Clear(); depth = 0; attributeCount = 0; attributeStart = -1; attributeIndex = -1; rootElement = false; readingElement = false; signing = false; MoveToNode(initialNode); } protected XmlDeclarationNode MoveToDeclaration() { if (attributeCount < 1) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(System.Runtime.Serialization.SR.GetString("Version not found in XML declaration."))); } if (attributeCount > 3) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(System.Runtime.Serialization.SR.GetString("Malformed XML declaration."))); } if (!CheckDeclAttribute(0, "version", "1.0", checkLower: false, "XML version must be '1.0'.")) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(System.Runtime.Serialization.SR.GetString("Version not found in XML declaration."))); } if (attributeCount > 1) { if (CheckDeclAttribute(1, "encoding", null, checkLower: true, "XML encoding must be 'UTF-8'.")) { if (attributeCount == 3 && !CheckStandalone(2)) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(System.Runtime.Serialization.SR.GetString("Malformed XML declaration."))); } } else if (!CheckStandalone(1) || attributeCount > 2) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(System.Runtime.Serialization.SR.GetString("Malformed XML declaration."))); } } if (declarationNode == null) { declarationNode = new XmlDeclarationNode(bufferReader); } MoveToNode(declarationNode); return declarationNode; } private bool CheckStandalone(int attr) { XmlAttributeNode xmlAttributeNode = attributeNodes[attr]; if (!xmlAttributeNode.Prefix.IsEmpty) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(System.Runtime.Serialization.SR.GetString("Malformed XML declaration."))); } if (xmlAttributeNode.LocalName != "standalone") { return false; } if (!xmlAttributeNode.Value.Equals2("yes", checkLower: false) && !xmlAttributeNode.Value.Equals2("no", checkLower: false)) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(System.Runtime.Serialization.SR.GetString("'standalone' value in declaration must be 'yes' or 'no'."))); } return true; } private bool CheckDeclAttribute(int index, string localName, string value, bool checkLower, string valueSR) { XmlAttributeNode xmlAttributeNode = attributeNodes[index]; if (!xmlAttributeNode.Prefix.IsEmpty) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(System.Runtime.Serialization.SR.GetString("Malformed XML declaration."))); } if (xmlAttributeNode.LocalName != localName) { return false; } if (value != null && !xmlAttributeNode.Value.Equals2(value, checkLower)) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(System.Runtime.Serialization.SR.GetString(valueSR))); } return true; } protected XmlCommentNode MoveToComment() { if (commentNode == null) { commentNode = new XmlCommentNode(bufferReader); } MoveToNode(commentNode); return commentNode; } protected XmlCDataNode MoveToCData() { if (cdataNode == null) { cdataNode = new XmlCDataNode(bufferReader); } MoveToNode(cdataNode); return cdataNode; } protected XmlAtomicTextNode MoveToAtomicText() { XmlAtomicTextNode result = atomicTextNode; MoveToNode(result); return result; } protected XmlComplexTextNode MoveToComplexText() { if (complexTextNode == null) { complexTextNode = new XmlComplexTextNode(bufferReader); } MoveToNode(complexTextNode); return complexTextNode; } protected XmlTextNode MoveToWhitespaceText() { if (whitespaceTextNode == null) { whitespaceTextNode = new XmlWhitespaceTextNode(bufferReader); } if (nsMgr.XmlSpace == XmlSpace.Preserve) { whitespaceTextNode.NodeType = XmlNodeType.SignificantWhitespace; } else { whitespaceTextNode.NodeType = XmlNodeType.Whitespace; } MoveToNode(whitespaceTextNode); return whitespaceTextNode; } protected void MoveToEndElement() { if (depth == 0) { XmlExceptionHelper.ThrowInvalidBinaryFormat(this); } XmlElementNode xmlElementNode = elementNodes[depth]; XmlEndElementNode endElement = xmlElementNode.EndElement; endElement.Namespace = xmlElementNode.Namespace; MoveToNode(endElement); } protected void MoveToEndOfFile() { if (depth != 0) { XmlExceptionHelper.ThrowUnexpectedEndOfFile(this); } MoveToNode(endOfFileNode); } protected XmlElementNode EnterScope() { if (depth == 0) { if (rootElement) { XmlExceptionHelper.ThrowMultipleRootElements(this); } rootElement = true; } nsMgr.EnterScope(); depth++; if (depth > quotas.MaxDepth) { XmlExceptionHelper.ThrowMaxDepthExceeded(this, quotas.MaxDepth); } if (elementNodes == null) { elementNodes = new XmlElementNode[4]; } else if (elementNodes.Length == depth) { XmlElementNode[] destinationArray = new XmlElementNode[depth * 2]; Array.Copy(elementNodes, destinationArray, depth); elementNodes = destinationArray; } XmlElementNode xmlElementNode = elementNodes[depth]; if (xmlElementNode == null) { xmlElementNode = new XmlElementNode(bufferReader); elementNodes[depth] = xmlElementNode; } attributeCount = 0; attributeStart = -1; attributeIndex = -1; MoveToNode(xmlElementNode); return xmlElementNode; } protected void ExitScope() { if (depth == 0) { XmlExceptionHelper.ThrowUnexpectedEndElement(this); } depth--; nsMgr.ExitScope(); } private XmlAttributeNode AddAttribute(QNameType qnameType, bool isAtomicValue) { int num = attributeCount; if (attributeNodes == null) { attributeNodes = new XmlAttributeNode[4]; } else if (attributeNodes.Length == num) { XmlAttributeNode[] destinationArray = new XmlAttributeNode[num * 2]; Array.Copy(attributeNodes, destinationArray, num); attributeNodes = destinationArray; } XmlAttributeNode xmlAttributeNode = attributeNodes[num]; if (xmlAttributeNode == null) { xmlAttributeNode = new XmlAttributeNode(bufferReader); attributeNodes[num] = xmlAttributeNode; } xmlAttributeNode.QNameType = qnameType; xmlAttributeNode.IsAtomicValue = isAtomicValue; xmlAttributeNode.AttributeText.QNameType = qnameType; xmlAttributeNode.AttributeText.IsAtomicValue = isAtomicValue; attributeCount++; return xmlAttributeNode; } protected Namespace AddNamespace() { return nsMgr.AddNamespace(); } protected XmlAttributeNode AddAttribute() { return AddAttribute(QNameType.Normal, isAtomicValue: true); } protected XmlAttributeNode AddXmlAttribute() { return AddAttribute(QNameType.Normal, isAtomicValue: true); } protected XmlAttributeNode AddXmlnsAttribute(Namespace ns) { if (!ns.Prefix.IsEmpty && ns.Uri.IsEmpty) { XmlExceptionHelper.ThrowEmptyNamespace(this); } if (ns.Prefix.IsXml && ns.Uri != "http://www.w3.org/XML/1998/namespace") { XmlExceptionHelper.ThrowXmlException(this, new XmlException(System.Runtime.Serialization.SR.GetString("The prefix '{0}' can only be bound to the namespace '{1}'.", "xml", "http://www.w3.org/XML/1998/namespace"))); } else if (ns.Prefix.IsXmlns && ns.Uri != "http://www.w3.org/2000/xmlns/") { XmlExceptionHelper.ThrowXmlException(this, new XmlException(System.Runtime.Serialization.SR.GetString("The prefix '{0}' can only be bound to the namespace '{1}'.", "xmlns", "http://www.w3.org/2000/xmlns/"))); } nsMgr.Register(ns); XmlAttributeNode xmlAttributeNode = AddAttribute(QNameType.Xmlns, isAtomicValue: false); xmlAttributeNode.Namespace = ns; xmlAttributeNode.AttributeText.Namespace = ns; return xmlAttributeNode; } protected void FixXmlAttribute(XmlAttributeNode attributeNode) { if (!(attributeNode.Prefix == "xml")) { return; } if (attributeNode.LocalName == "lang") { nsMgr.AddLangAttribute(attributeNode.Value.GetString()); } else if (attributeNode.LocalName == "space") { string @string = attributeNode.Value.GetString(); if (@string == "preserve") { nsMgr.AddSpaceAttribute(XmlSpace.Preserve); } else if (@string == "default") { nsMgr.AddSpaceAttribute(XmlSpace.Default); } } } public override void Close() { MoveToNode(closedNode); nameTable = null; if (attributeNodes != null && attributeNodes.Length > 16) { attributeNodes = null; } if (elementNodes != null && elementNodes.Length > 16) { elementNodes = null; } nsMgr.Close(); bufferReader.Close(); if (signingWriter != null) { signingWriter.Close(); } if (attributeSorter != null) { attributeSorter.Close(); } } private XmlAttributeNode GetAttributeNode(int index) { if (!node.CanGetAttribute) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", System.Runtime.Serialization.SR.GetString("Only Element nodes have attributes."))); } if (index < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (index >= attributeCount) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", attributeCount))); } return attributeNodes[index]; } private XmlAttributeNode GetAttributeNode(string name) { if (name == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("name")); } if (!node.CanGetAttribute) { return null; } int num = name.IndexOf(':'); string text; string text2; if (num == -1) { if (name == "xmlns") { text = "xmlns"; text2 = string.Empty; } else { text = string.Empty; text2 = name; } } else { text = name.Substring(0, num); text2 = name.Substring(num + 1); } XmlAttributeNode[] array = attributeNodes; int num2 = attributeCount; int num3 = attributeStart; for (int i = 0; i < num2; i++) { if (++num3 >= num2) { num3 = 0; } XmlAttributeNode xmlAttributeNode = array[num3]; if (xmlAttributeNode.IsPrefixAndLocalName(text, text2)) { attributeStart = num3; return xmlAttributeNode; } } return null; } private XmlAttributeNode GetAttributeNode(string localName, string namespaceUri) { if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localName")); } if (namespaceUri == null) { namespaceUri = string.Empty; } if (!node.CanGetAttribute) { return null; } XmlAttributeNode[] array = attributeNodes; int num = attributeCount; int num2 = attributeStart; for (int i = 0; i < num; i++) { if (++num2 >= num) { num2 = 0; } XmlAttributeNode xmlAttributeNode = array[num2]; if (xmlAttributeNode.IsLocalNameAndNamespaceUri(localName, namespaceUri)) { attributeStart = num2; return xmlAttributeNode; } } return null; } private XmlAttributeNode GetAttributeNode(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localName")); } if (namespaceUri == null) { namespaceUri = XmlDictionaryString.Empty; } if (!node.CanGetAttribute) { return null; } XmlAttributeNode[] array = attributeNodes; int num = attributeCount; int num2 = attributeStart; for (int i = 0; i < num; i++) { if (++num2 >= num) { num2 = 0; } XmlAttributeNode xmlAttributeNode = array[num2]; if (xmlAttributeNode.IsLocalNameAndNamespaceUri(localName, namespaceUri)) { attributeStart = num2; return xmlAttributeNode; } } return null; } public override string GetAttribute(int index) { return GetAttributeNode(index).ValueAsString; } public override string GetAttribute(string name) { return GetAttributeNode(name)?.ValueAsString; } public override string GetAttribute(string localName, string namespaceUri) { return GetAttributeNode(localName, namespaceUri)?.ValueAsString; } public override string GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return GetAttributeNode(localName, namespaceUri)?.ValueAsString; } public override string LookupNamespace(string prefix) { Namespace @namespace = nsMgr.LookupNamespace(prefix); if (@namespace != null) { return @namespace.Uri.GetString(NameTable); } if (prefix == "xmlns") { return "http://www.w3.org/2000/xmlns/"; } return null; } protected Namespace LookupNamespace(PrefixHandleType prefix) { Namespace @namespace = nsMgr.LookupNamespace(prefix); if (@namespace == null) { XmlExceptionHelper.ThrowUndefinedPrefix(this, PrefixHandle.GetString(prefix)); } return @namespace; } protected Namespace LookupNamespace(PrefixHandle prefix) { Namespace @namespace = nsMgr.LookupNamespace(prefix); if (@namespace == null) { XmlExceptionHelper.ThrowUndefinedPrefix(this, prefix.GetString()); } return @namespace; } protected void ProcessAttributes() { if (attributeCount > 0) { ProcessAttributes(attributeNodes, attributeCount); } } private void ProcessAttributes(XmlAttributeNode[] attributeNodes, int attributeCount) { for (int i = 0; i < attributeCount; i++) { XmlAttributeNode xmlAttributeNode = attributeNodes[i]; if (xmlAttributeNode.QNameType == QNameType.Normal) { PrefixHandle prefixHandle = xmlAttributeNode.Prefix; if (!prefixHandle.IsEmpty) { xmlAttributeNode.Namespace = LookupNamespace(prefixHandle); } else { xmlAttributeNode.Namespace = NamespaceManager.EmptyNamespace; } xmlAttributeNode.AttributeText.Namespace = xmlAttributeNode.Namespace; } } if (attributeCount <= 1) { return; } if (attributeCount < 12) { for (int j = 0; j < attributeCount - 1; j++) { XmlAttributeNode xmlAttributeNode2 = attributeNodes[j]; if (xmlAttributeNode2.QNameType == QNameType.Normal) { for (int k = j + 1; k < attributeCount; k++) { XmlAttributeNode xmlAttributeNode3 = attributeNodes[k]; if (xmlAttributeNode3.QNameType == QNameType.Normal && xmlAttributeNode2.LocalName == xmlAttributeNode3.LocalName && xmlAttributeNode2.Namespace.Uri == xmlAttributeNode3.Namespace.Uri) { XmlExceptionHelper.ThrowDuplicateAttribute(this, xmlAttributeNode2.Prefix.GetString(), xmlAttributeNode3.Prefix.GetString(), xmlAttributeNode2.LocalName.GetString(), xmlAttributeNode2.Namespace.Uri.GetString()); } } continue; } for (int l = j + 1; l < attributeCount; l++) { XmlAttributeNode xmlAttributeNode4 = attributeNodes[l]; if (xmlAttributeNode4.QNameType == QNameType.Xmlns && xmlAttributeNode2.Namespace.Prefix == xmlAttributeNode4.Namespace.Prefix) { XmlExceptionHelper.ThrowDuplicateAttribute(this, "xmlns", "xmlns", xmlAttributeNode2.Namespace.Prefix.GetString(), "http://www.w3.org/2000/xmlns/"); } } } } else { CheckAttributes(attributeNodes, attributeCount); } } private void CheckAttributes(XmlAttributeNode[] attributeNodes, int attributeCount) { if (attributeSorter == null) { attributeSorter = new AttributeSorter(); } if (!attributeSorter.Sort(attributeNodes, attributeCount)) { attributeSorter.GetIndeces(out var attributeIndex, out var attributeIndex2); if (attributeNodes[attributeIndex].QNameType == QNameType.Xmlns) { XmlExceptionHelper.ThrowDuplicateXmlnsAttribute(this, attributeNodes[attributeIndex].Namespace.Prefix.GetString(), "http://www.w3.org/2000/xmlns/"); } else { XmlExceptionHelper.ThrowDuplicateAttribute(this, attributeNodes[attributeIndex].Prefix.GetString(), attributeNodes[attributeIndex2].Prefix.GetString(), attributeNodes[attributeIndex].LocalName.GetString(), attributeNodes[attributeIndex].Namespace.Uri.GetString()); } } } public override void MoveToAttribute(int index) { MoveToNode(GetAttributeNode(index)); attributeIndex = index; } public override bool MoveToAttribute(string name) { XmlNode attributeNode = GetAttributeNode(name); if (attributeNode == null) { return false; } MoveToNode(attributeNode); attributeIndex = attributeStart; return true; } public override bool MoveToAttribute(string localName, string namespaceUri) { XmlNode attributeNode = GetAttributeNode(localName, namespaceUri); if (attributeNode == null) { return false; } MoveToNode(attributeNode); attributeIndex = attributeStart; return true; } public override bool MoveToElement() { if (!node.CanMoveToElement) { return false; } if (depth == 0) { MoveToDeclaration(); } else { MoveToNode(elementNodes[depth]); } attributeIndex = -1; return true; } public override XmlNodeType MoveToContent() { do { if (node.HasContent) { if ((node.NodeType != XmlNodeType.Text && node.NodeType != XmlNodeType.CDATA) || trailByteCount > 0) { break; } if (value == null) { if (!node.Value.IsWhitespace()) { break; } } else if (!XmlConverter.IsWhitespace(value)) { break; } } else if (node.NodeType == XmlNodeType.Attribute) { MoveToElement(); break; } } while (Read()); return node.NodeType; } public override bool MoveToFirstAttribute() { if (!node.CanGetAttribute || attributeCount == 0) { return false; } MoveToNode(GetAttributeNode(0)); attributeIndex = 0; return true; } public override bool MoveToNextAttribute() { if (!node.CanGetAttribute) { return false; } int num = attributeIndex + 1; if (num >= attributeCount) { return false; } MoveToNode(GetAttributeNode(num)); attributeIndex = num; return true; } private string GetLocalName(bool enforceAtomization) { if (localName != null) { return localName; } if (node.QNameType == QNameType.Normal) { if (enforceAtomization || nameTable != null) { return node.LocalName.GetString(NameTable); } return node.LocalName.GetString(); } if (node.Namespace.Prefix.IsEmpty) { return "xmlns"; } if (enforceAtomization || nameTable != null) { return node.Namespace.Prefix.GetString(NameTable); } return node.Namespace.Prefix.GetString(); } private string GetNamespaceUri(bool enforceAtomization) { if (ns != null) { return ns; } if (node.QNameType == QNameType.Normal) { if (enforceAtomization || nameTable != null) { return node.Namespace.Uri.GetString(NameTable); } return node.Namespace.Uri.GetString(); } return "http://www.w3.org/2000/xmlns/"; } public override void GetNonAtomizedNames(out string localName, out string namespaceUri) { localName = GetLocalName(enforceAtomization: false); namespaceUri = GetNamespaceUri(enforceAtomization: false); } public override bool IsLocalName(string localName) { if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localName")); } return node.IsLocalName(localName); } public override bool IsLocalName(XmlDictionaryString localName) { if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localName")); } return node.IsLocalName(localName); } public override bool IsNamespaceUri(string namespaceUri) { if (namespaceUri == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri"); } return node.IsNamespaceUri(namespaceUri); } public override bool IsNamespaceUri(XmlDictionaryString namespaceUri) { if (namespaceUri == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri"); } return node.IsNamespaceUri(namespaceUri); } public sealed override bool IsStartElement() { switch (node.NodeType) { case XmlNodeType.Element: return true; case XmlNodeType.EndElement: return false; case XmlNodeType.None: Read(); if (node.NodeType == XmlNodeType.Element) { return true; } break; } return MoveToContent() == XmlNodeType.Element; } public override bool IsStartElement(string name) { if (name == null) { return false; } int num = name.IndexOf(':'); string text; string text2; if (num == -1) { text = string.Empty; text2 = name; } else { text = name.Substring(0, num); text2 = name.Substring(num + 1); } if ((node.NodeType == XmlNodeType.Element || IsStartElement()) && node.Prefix == text) { return node.LocalName == text2; } return false; } public override bool IsStartElement(string localName, string namespaceUri) { if (localName == null) { return false; } if (namespaceUri == null) { return false; } if ((node.NodeType == XmlNodeType.Element || IsStartElement()) && node.LocalName == localName) { return node.IsNamespaceUri(namespaceUri); } return false; } public override bool IsStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localName"); } if (namespaceUri == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri"); } if ((node.NodeType == XmlNodeType.Element || IsStartElement()) && node.LocalName == localName) { return node.IsNamespaceUri(namespaceUri); } return false; } public override int IndexOfLocalName(string[] localNames, string namespaceUri) { if (localNames == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localNames"); } if (namespaceUri == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri"); } QNameType qNameType = node.QNameType; if (node.IsNamespaceUri(namespaceUri)) { if (qNameType == QNameType.Normal) { StringHandle stringHandle = node.LocalName; for (int i = 0; i < localNames.Length; i++) { string text = localNames[i]; if (text == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i)); } if (stringHandle == text) { return i; } } } else { PrefixHandle prefixHandle = node.Namespace.Prefix; for (int j = 0; j < localNames.Length; j++) { string text2 = localNames[j]; if (text2 == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", j)); } if (prefixHandle == text2) { return j; } } } } return -1; } public override int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictionaryString namespaceUri) { if (localNames == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localNames"); } if (namespaceUri == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri"); } QNameType qNameType = node.QNameType; if (node.IsNamespaceUri(namespaceUri)) { if (qNameType == QNameType.Normal) { StringHandle stringHandle = node.LocalName; for (int i = 0; i < localNames.Length; i++) { XmlDictionaryString xmlDictionaryString = localNames[i]; if (xmlDictionaryString == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i)); } if (stringHandle == xmlDictionaryString) { return i; } } } else { PrefixHandle prefixHandle = node.Namespace.Prefix; for (int j = 0; j < localNames.Length; j++) { XmlDictionaryString xmlDictionaryString2 = localNames[j]; if (xmlDictionaryString2 == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", j)); } if (prefixHandle == xmlDictionaryString2) { return j; } } } } return -1; } public override int ReadValueChunk(char[] chars, int offset, int count) { if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > chars.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > chars.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", chars.Length - offset))); } if (value == null && node.QNameType == QNameType.Normal && node.Value.TryReadChars(chars, offset, count, out var actual)) { return actual; } string text = Value; actual = Math.Min(count, text.Length); text.CopyTo(0, chars, offset, actual); value = text.Substring(actual); return actual; } public override int ReadValueAsBase64(byte[] buffer, int offset, int count) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("buffer")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > buffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", buffer.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", buffer.Length - offset))); } if (count == 0) { return 0; } if (value == null && trailByteCount == 0 && trailCharCount == 0 && node.QNameType == QNameType.Normal && node.Value.TryReadBase64(buffer, offset, count, out var actual)) { return actual; } return ReadBytes(Base64Encoding, 3, 4, buffer, offset, Math.Min(count, 512), readContent: false); } public override string ReadElementContentAsString() { if (node.NodeType != XmlNodeType.Element) { MoveToStartElement(); } if (node.IsEmptyElement) { Read(); return string.Empty; } Read(); string result = ReadContentAsString(); ReadEndElement(); return result; } public override string ReadElementString() { MoveToStartElement(); if (IsEmptyElement) { Read(); return string.Empty; } Read(); string result = ReadString(); ReadEndElement(); return result; } public override string ReadElementString(string name) { MoveToStartElement(name); return ReadElementString(); } public override string ReadElementString(string localName, string namespaceUri) { MoveToStartElement(localName, namespaceUri); return ReadElementString(); } public override void ReadStartElement() { if (node.NodeType != XmlNodeType.Element) { MoveToStartElement(); } Read(); } public override void ReadStartElement(string name) { MoveToStartElement(name); Read(); } public override void ReadStartElement(string localName, string namespaceUri) { MoveToStartElement(localName, namespaceUri); Read(); } public override void ReadEndElement() { if (node.NodeType != XmlNodeType.EndElement && MoveToContent() != XmlNodeType.EndElement) { int num = ((node.NodeType == XmlNodeType.Element) ? (depth - 1) : depth); if (num == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("No corresponding start element is open."))); } XmlElementNode xmlElementNode = elementNodes[num]; XmlExceptionHelper.ThrowEndElementExpected(this, xmlElementNode.LocalName.GetString(), xmlElementNode.Namespace.Uri.GetString()); } Read(); } public override bool ReadAttributeValue() { XmlAttributeTextNode attributeText = node.AttributeText; if (attributeText == null) { return false; } MoveToNode(attributeText); return true; } private void SkipValue(XmlNode node) { if (node.SkipValue) { Read(); } } public override bool TryGetBase64ContentLength(out int length) { if (trailByteCount == 0 && trailCharCount == 0 && value == null) { XmlNode xmlNode = Node; if (xmlNode.IsAtomicValue) { return xmlNode.Value.TryGetByteArrayLength(out length); } } return base.TryGetBase64ContentLength(out length); } public override byte[] ReadContentAsBase64() { if (trailByteCount == 0 && trailCharCount == 0 && value == null) { XmlNode xmlNode = Node; if (xmlNode.IsAtomicValue) { byte[] array = xmlNode.Value.ToByteArray(); if (array.Length > quotas.MaxArrayLength) { XmlExceptionHelper.ThrowMaxArrayLengthExceeded(this, quotas.MaxArrayLength); } SkipValue(xmlNode); return array; } } if (!bufferReader.IsStreamed) { return ReadContentAsBase64(quotas.MaxArrayLength, bufferReader.Buffer.Length); } return ReadContentAsBase64(quotas.MaxArrayLength, 65535); } public override int ReadElementContentAsBase64(byte[] buffer, int offset, int count) { if (!readingElement) { if (IsEmptyElement) { Read(); return 0; } ReadStartElement(); readingElement = true; } int num = ReadContentAsBase64(buffer, offset, count); if (num == 0) { ReadEndElement(); readingElement = false; } return num; } public override int ReadContentAsBase64(byte[] buffer, int offset, int count) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("buffer")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > buffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", buffer.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", buffer.Length - offset))); } if (count == 0) { return 0; } if (trailByteCount == 0 && trailCharCount == 0 && value == null && node.QNameType == QNameType.Normal) { int actual; while (node.NodeType != XmlNodeType.Comment && node.Value.TryReadBase64(buffer, offset, count, out actual)) { if (actual != 0) { return actual; } Read(); } } XmlNodeType nodeType = node.NodeType; if (nodeType == XmlNodeType.Element || nodeType == XmlNodeType.EndElement) { return 0; } return ReadBytes(Base64Encoding, 3, 4, buffer, offset, Math.Min(count, 512), readContent: true); } public override byte[] ReadContentAsBinHex() { return ReadContentAsBinHex(quotas.MaxArrayLength); } public override int ReadElementContentAsBinHex(byte[] buffer, int offset, int count) { if (!readingElement) { if (IsEmptyElement) { Read(); return 0; } ReadStartElement(); readingElement = true; } int num = ReadContentAsBinHex(buffer, offset, count); if (num == 0) { ReadEndElement(); readingElement = false; } return num; } public override int ReadContentAsBinHex(byte[] buffer, int offset, int count) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("buffer")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > buffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", buffer.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", buffer.Length - offset))); } if (count == 0) { return 0; } return ReadBytes(BinHexEncoding, 1, 2, buffer, offset, Math.Min(count, 512), readContent: true); } private int ReadBytes(Encoding encoding, int byteBlock, int charBlock, byte[] buffer, int offset, int byteCount, bool readContent) { if (trailByteCount > 0) { int num = Math.Min(trailByteCount, byteCount); Array.Copy(trailBytes, 0, buffer, offset, num); trailByteCount -= num; Array.Copy(trailBytes, num, trailBytes, 0, trailByteCount); return num; } XmlNodeType nodeType = node.NodeType; if (nodeType == XmlNodeType.Element || nodeType == XmlNodeType.EndElement) { return 0; } int num2 = ((byteCount >= byteBlock) ? (byteCount / byteBlock * charBlock) : charBlock); char[] charBuffer = GetCharBuffer(num2); int num3 = 0; while (true) { if (trailCharCount > 0) { Array.Copy(trailChars, 0, charBuffer, num3, trailCharCount); num3 += trailCharCount; trailCharCount = 0; } while (num3 < charBlock) { int num4; if (readContent) { num4 = ReadContentAsChars(charBuffer, num3, num2 - num3); if (num4 == 1 && charBuffer[num3] == '\n') { continue; } } else { num4 = ReadValueChunk(charBuffer, num3, num2 - num3); } if (num4 == 0) { break; } num3 += num4; } if (num3 >= charBlock) { trailCharCount = num3 % charBlock; if (trailCharCount > 0) { if (trailChars == null) { trailChars = new char[4]; } num3 -= trailCharCount; Array.Copy(charBuffer, num3, trailChars, 0, trailCharCount); } } try { if (byteCount < byteBlock) { if (trailBytes == null) { trailBytes = new byte[3]; } trailByteCount = encoding.GetBytes(charBuffer, 0, num3, trailBytes, 0); int num5 = Math.Min(trailByteCount, byteCount); Array.Copy(trailBytes, 0, buffer, offset, num5); trailByteCount -= num5; Array.Copy(trailBytes, num5, trailBytes, 0, trailByteCount); return num5; } return encoding.GetBytes(charBuffer, 0, num3, buffer, offset); } catch (FormatException ex) { int num6 = 0; int num7 = 0; while (true) { if (num7 < num3 && XmlConverter.IsWhitespace(charBuffer[num7])) { num7++; continue; } if (num7 == num3) { break; } charBuffer[num6++] = charBuffer[num7++]; } if (num6 == num3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(ex.Message, ex.InnerException)); } num3 = num6; } } } public override string ReadContentAsString() { XmlNode xmlNode = Node; if (xmlNode.IsAtomicValue) { string @string; if (value != null) { @string = value; if (xmlNode.AttributeText == null) { value = string.Empty; } } else { @string = xmlNode.Value.GetString(); SkipValue(xmlNode); if (@string.Length > quotas.MaxStringContentLength) { XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, quotas.MaxStringContentLength); } } return @string; } return ReadContentAsString(quotas.MaxStringContentLength); } public override bool ReadContentAsBoolean() { XmlNode xmlNode = Node; if (value == null && xmlNode.IsAtomicValue) { bool result = xmlNode.Value.ToBoolean(); SkipValue(xmlNode); return result; } return XmlConverter.ToBoolean(ReadContentAsString()); } public override long ReadContentAsLong() { XmlNode xmlNode = Node; if (value == null && xmlNode.IsAtomicValue) { long result = xmlNode.Value.ToLong(); SkipValue(xmlNode); return result; } return XmlConverter.ToInt64(ReadContentAsString()); } public override int ReadContentAsInt() { XmlNode xmlNode = Node; if (value == null && xmlNode.IsAtomicValue) { int result = xmlNode.Value.ToInt(); SkipValue(xmlNode); return result; } return XmlConverter.ToInt32(ReadContentAsString()); } public override DateTime ReadContentAsDateTime() { XmlNode xmlNode = Node; if (value == null && xmlNode.IsAtomicValue) { DateTime result = xmlNode.Value.ToDateTime(); SkipValue(xmlNode); return result; } return XmlConverter.ToDateTime(ReadContentAsString()); } public override double ReadContentAsDouble() { XmlNode xmlNode = Node; if (value == null && xmlNode.IsAtomicValue) { double result = xmlNode.Value.ToDouble(); SkipValue(xmlNode); return result; } return XmlConverter.ToDouble(ReadContentAsString()); } public override float ReadContentAsFloat() { XmlNode xmlNode = Node; if (value == null && xmlNode.IsAtomicValue) { float result = xmlNode.Value.ToSingle(); SkipValue(xmlNode); return result; } return XmlConverter.ToSingle(ReadContentAsString()); } public override decimal ReadContentAsDecimal() { XmlNode xmlNode = Node; if (value == null && xmlNode.IsAtomicValue) { decimal result = xmlNode.Value.ToDecimal(); SkipValue(xmlNode); return result; } return XmlConverter.ToDecimal(ReadContentAsString()); } public override UniqueId ReadContentAsUniqueId() { XmlNode xmlNode = Node; if (value == null && xmlNode.IsAtomicValue) { UniqueId result = xmlNode.Value.ToUniqueId(); SkipValue(xmlNode); return result; } return XmlConverter.ToUniqueId(ReadContentAsString()); } public override TimeSpan ReadContentAsTimeSpan() { XmlNode xmlNode = Node; if (value == null && xmlNode.IsAtomicValue) { TimeSpan result = xmlNode.Value.ToTimeSpan(); SkipValue(xmlNode); return result; } return XmlConverter.ToTimeSpan(ReadContentAsString()); } public override Guid ReadContentAsGuid() { XmlNode xmlNode = Node; if (value == null && xmlNode.IsAtomicValue) { Guid result = xmlNode.Value.ToGuid(); SkipValue(xmlNode); return result; } return XmlConverter.ToGuid(ReadContentAsString()); } public override object ReadContentAsObject() { XmlNode xmlNode = Node; if (value == null && xmlNode.IsAtomicValue) { object result = xmlNode.Value.ToObject(); SkipValue(xmlNode); return result; } return ReadContentAsString(); } public override object ReadContentAs(Type type, IXmlNamespaceResolver namespaceResolver) { if (type == typeof(ulong)) { if (value == null && node.IsAtomicValue) { ulong num = node.Value.ToULong(); SkipValue(node); return num; } return XmlConverter.ToUInt64(ReadContentAsString()); } if (type == typeof(bool)) { return ReadContentAsBoolean(); } if (type == typeof(int)) { return ReadContentAsInt(); } if (type == typeof(long)) { return ReadContentAsLong(); } if (type == typeof(float)) { return ReadContentAsFloat(); } if (type == typeof(double)) { return ReadContentAsDouble(); } if (type == typeof(decimal)) { return ReadContentAsDecimal(); } if (type == typeof(DateTime)) { return ReadContentAsDateTime(); } if (type == typeof(UniqueId)) { return ReadContentAsUniqueId(); } if (type == typeof(Guid)) { return ReadContentAsGuid(); } if (type == typeof(TimeSpan)) { return ReadContentAsTimeSpan(); } if (type == typeof(object)) { return ReadContentAsObject(); } return base.ReadContentAs(type, namespaceResolver); } public override void ResolveEntity() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("The reader cannot be advanced."))); } public override void Skip() { if (node.ReadState != ReadState.Interactive) { return; } if ((node.NodeType == XmlNodeType.Element || MoveToElement()) && !IsEmptyElement) { int num = Depth; while (Read() && num < Depth) { } if (node.NodeType == XmlNodeType.EndElement) { Read(); } } else { Read(); } } public override bool TryGetLocalNameAsDictionaryString(out XmlDictionaryString localName) { return node.TryGetLocalNameAsDictionaryString(out localName); } public override bool TryGetNamespaceUriAsDictionaryString(out XmlDictionaryString localName) { return node.TryGetNamespaceUriAsDictionaryString(out localName); } public override bool TryGetValueAsDictionaryString(out XmlDictionaryString value) { return node.TryGetValueAsDictionaryString(out value); } public override short[] ReadInt16Array(string localName, string namespaceUri) { return Int16ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, quotas.MaxArrayLength); } public override short[] ReadInt16Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return Int16ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, quotas.MaxArrayLength); } public override int[] ReadInt32Array(string localName, string namespaceUri) { return Int32ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, quotas.MaxArrayLength); } public override int[] ReadInt32Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return Int32ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, quotas.MaxArrayLength); } public override long[] ReadInt64Array(string localName, string namespaceUri) { return Int64ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, quotas.MaxArrayLength); } public override long[] ReadInt64Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return Int64ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, quotas.MaxArrayLength); } public override float[] ReadSingleArray(string localName, string namespaceUri) { return SingleArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, quotas.MaxArrayLength); } public override float[] ReadSingleArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return SingleArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, quotas.MaxArrayLength); } public override double[] ReadDoubleArray(string localName, string namespaceUri) { return DoubleArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, quotas.MaxArrayLength); } public override double[] ReadDoubleArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return DoubleArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, quotas.MaxArrayLength); } public override decimal[] ReadDecimalArray(string localName, string namespaceUri) { return DecimalArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, quotas.MaxArrayLength); } public override decimal[] ReadDecimalArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return DecimalArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, quotas.MaxArrayLength); } public override DateTime[] ReadDateTimeArray(string localName, string namespaceUri) { return DateTimeArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, quotas.MaxArrayLength); } public override DateTime[] ReadDateTimeArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return DateTimeArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, quotas.MaxArrayLength); } public override Guid[] ReadGuidArray(string localName, string namespaceUri) { return GuidArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, quotas.MaxArrayLength); } public override Guid[] ReadGuidArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return GuidArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, quotas.MaxArrayLength); } public override TimeSpan[] ReadTimeSpanArray(string localName, string namespaceUri) { return TimeSpanArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, quotas.MaxArrayLength); } public override TimeSpan[] ReadTimeSpanArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return TimeSpanArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, quotas.MaxArrayLength); } public string GetOpenElements() { string text = string.Empty; for (int num = depth; num > 0; num--) { string @string = elementNodes[num].LocalName.GetString(); if (num != depth) { text += ", "; } text += @string; } return text; } private char[] GetCharBuffer(int count) { if (count > 1024) { return new char[count]; } if (chars == null || chars.Length < count) { chars = new char[count]; } return chars; } private void SignStartElement(XmlSigningNodeWriter writer) { int offset; int length; byte[] @string = node.Prefix.GetString(out offset, out length); int offset2; int length2; byte[] string2 = node.LocalName.GetString(out offset2, out length2); writer.WriteStartElement(@string, offset, length, string2, offset2, length2); } private void SignAttribute(XmlSigningNodeWriter writer, XmlAttributeNode attributeNode) { if (attributeNode.QNameType == QNameType.Normal) { int offset; int length; byte[] @string = attributeNode.Prefix.GetString(out offset, out length); int offset2; int length2; byte[] string2 = attributeNode.LocalName.GetString(out offset2, out length2); writer.WriteStartAttribute(@string, offset, length, string2, offset2, length2); attributeNode.Value.Sign(writer); writer.WriteEndAttribute(); } else { int offset3; int length3; byte[] string3 = attributeNode.Namespace.Prefix.GetString(out offset3, out length3); int offset4; int length4; byte[] string4 = attributeNode.Namespace.Uri.GetString(out offset4, out length4); writer.WriteXmlnsAttribute(string3, offset3, length3, string4, offset4, length4); } } private void SignEndElement(XmlSigningNodeWriter writer) { int offset; int length; byte[] @string = node.Prefix.GetString(out offset, out length); int offset2; int length2; byte[] string2 = node.LocalName.GetString(out offset2, out length2); writer.WriteEndElement(@string, offset, length, string2, offset2, length2); } private void SignNode(XmlSigningNodeWriter writer) { switch (node.NodeType) { case XmlNodeType.Element: { SignStartElement(writer); for (int i = 0; i < attributeCount; i++) { SignAttribute(writer, attributeNodes[i]); } writer.WriteEndStartElement(node.IsEmptyElement); break; } case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: node.Value.Sign(writer); break; case XmlNodeType.XmlDeclaration: writer.WriteDeclaration(); break; case XmlNodeType.Comment: writer.WriteComment(node.Value.GetString()); break; case XmlNodeType.EndElement: SignEndElement(writer); break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); case XmlNodeType.None: break; } } protected void SignNode() { if (signing) { SignNode(signingWriter); } } public override void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes) { if (signing) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("XML canonicalization started"))); } if (signingWriter == null) { signingWriter = CreateSigningNodeWriter(); } signingWriter.SetOutput(XmlNodeWriter.Null, stream, includeComments, inclusivePrefixes); nsMgr.Sign(signingWriter); signing = true; } public override void EndCanonicalization() { if (!signing) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("XML canonicalization was not started."))); } signingWriter.Flush(); signingWriter.Close(); signing = false; } protected abstract XmlSigningNodeWriter CreateSigningNodeWriter(); } internal abstract class XmlBaseWriter : XmlDictionaryWriter, IFragmentCapableXmlDictionaryWriter { private class WriteBase64AsyncResult : AsyncResult { private static AsyncCompletion onComplete = new AsyncCompletion(OnComplete); private XmlBaseWriter writer; private byte[] buffer; private int offset; private int count; private int actualByteCount; private int totalByteCount; public WriteBase64AsyncResult(byte[] buffer, int offset, int count, XmlBaseWriter writer, AsyncCallback callback, object state) : base(callback, state) { this.writer = writer; this.buffer = buffer; this.offset = offset; this.count = count; bool flag = true; if (this.count > 0) { if (writer.trailByteCount > 0) { while (writer.trailByteCount < 3 && this.count > 0) { writer.trailBytes[writer.trailByteCount++] = buffer[this.offset++]; this.count--; } } totalByteCount = writer.trailByteCount + this.count; actualByteCount = totalByteCount - totalByteCount % 3; if (writer.trailBytes == null) { writer.trailBytes = new byte[3]; } if (actualByteCount >= 3) { if (writer.attributeValue != null) { writer.WriteAttributeText(XmlConverter.Base64Encoding.GetString(writer.trailBytes, 0, writer.trailByteCount)); writer.WriteAttributeText(XmlConverter.Base64Encoding.GetString(buffer, this.offset, actualByteCount - writer.trailByteCount)); } flag = HandleWriteBase64Text(null); } else { Buffer.BlockCopy(buffer, this.offset, writer.trailBytes, writer.trailByteCount, this.count); writer.trailByteCount += this.count; } } if (flag) { ((AsyncResult)this).Complete(true); } } private static bool OnComplete(IAsyncResult result) { return ((WriteBase64AsyncResult)result.AsyncState).HandleWriteBase64Text(result); } private bool HandleWriteBase64Text(IAsyncResult result) { if (!writer.isXmlnsAttribute) { if (result == null) { writer.StartContent(); result = writer.writer.BeginWriteBase64Text(writer.trailBytes, writer.trailByteCount, buffer, offset, actualByteCount - writer.trailByteCount, ((AsyncResult)this).PrepareAsyncCompletion(onComplete), this); if (!result.CompletedSynchronously) { return false; } } writer.writer.EndWriteBase64Text(result); writer.EndContent(); } writer.trailByteCount = totalByteCount - actualByteCount; if (writer.trailByteCount > 0) { int num = offset + count - writer.trailByteCount; for (int i = 0; i < writer.trailByteCount; i++) { writer.trailBytes[i] = buffer[num++]; } } return true; } public static void End(IAsyncResult result) { AsyncResult.End(result); } } private class Element { private string prefix; private string localName; private int prefixId; public string Prefix { get { return prefix; } set { prefix = value; } } public string LocalName { get { return localName; } set { localName = value; } } public int PrefixId { get { return prefixId; } set { prefixId = value; } } public void Clear() { prefix = null; localName = null; prefixId = 0; } } private enum DocumentState : byte { None, Document, Epilog, End } private class NamespaceManager { private class XmlAttribute { private XmlSpace space; private string lang; private int depth; public int Depth { get { return depth; } set { depth = value; } } public string XmlLang { get { return lang; } set { lang = value; } } public XmlSpace XmlSpace { get { return space; } set { space = value; } } public void Clear() { lang = null; } } private class Namespace { private string prefix; private string ns; private XmlDictionaryString xNs; private int depth; private char prefixChar; public int Depth { get { return depth; } set { depth = value; } } public char PrefixChar => prefixChar; public string Prefix { get { return prefix; } set { if (value.Length == 1) { prefixChar = value[0]; } else { prefixChar = '\0'; } prefix = value; } } public string Uri { get { return ns; } set { ns = value; } } public XmlDictionaryString UriDictionaryString { get { return xNs; } set { xNs = value; } } public void Clear() { prefix = null; prefixChar = '\0'; ns = null; xNs = null; depth = 0; } } private Namespace[] namespaces; private Namespace lastNameSpace; private int nsCount; private int depth; private XmlAttribute[] attributes; private int attributeCount; private XmlSpace space; private string lang; private int namespaceBoundary; private int nsTop; private Namespace defaultNamespace; public string XmlLang => lang; public XmlSpace XmlSpace => space; public int NamespaceBoundary { get { return namespaceBoundary; } set { int i; for (i = 0; i < nsCount && namespaces[i].Depth < value; i++) { } nsTop = i; namespaceBoundary = value; lastNameSpace = null; } } public NamespaceManager() { defaultNamespace = new Namespace(); defaultNamespace.Depth = 0; defaultNamespace.Prefix = string.Empty; defaultNamespace.Uri = string.Empty; defaultNamespace.UriDictionaryString = null; } public void Clear() { if (namespaces == null) { namespaces = new Namespace[4]; namespaces[0] = defaultNamespace; } nsCount = 1; nsTop = 0; depth = 0; attributeCount = 0; space = XmlSpace.None; lang = null; lastNameSpace = null; namespaceBoundary = 0; } public void Close() { if (depth == 0) { if (namespaces != null && namespaces.Length > 32) { namespaces = null; } if (attributes != null && attributes.Length > 4) { attributes = null; } } else { namespaces = null; attributes = null; } lang = null; } public void DeclareNamespaces(XmlNodeWriter writer) { int i = nsCount; while (i > 0 && namespaces[i - 1].Depth == depth) { i--; } for (; i < nsCount; i++) { Namespace @namespace = namespaces[i]; if (@namespace.UriDictionaryString != null) { writer.WriteXmlnsAttribute(@namespace.Prefix, @namespace.UriDictionaryString); } else { writer.WriteXmlnsAttribute(@namespace.Prefix, @namespace.Uri); } } } public void EnterScope() { depth++; } public void ExitScope() { while (nsCount > 0) { Namespace @namespace = namespaces[nsCount - 1]; if (@namespace.Depth != depth) { break; } if (lastNameSpace == @namespace) { lastNameSpace = null; } @namespace.Clear(); nsCount--; } while (attributeCount > 0) { XmlAttribute xmlAttribute = attributes[attributeCount - 1]; if (xmlAttribute.Depth != depth) { break; } space = xmlAttribute.XmlSpace; lang = xmlAttribute.XmlLang; xmlAttribute.Clear(); attributeCount--; } depth--; } public void AddLangAttribute(string lang) { AddAttribute(); this.lang = lang; } public void AddSpaceAttribute(XmlSpace space) { AddAttribute(); this.space = space; } private void AddAttribute() { if (attributes == null) { attributes = new XmlAttribute[1]; } else if (attributes.Length == attributeCount) { XmlAttribute[] destinationArray = new XmlAttribute[attributeCount * 2]; Array.Copy(attributes, destinationArray, attributeCount); attributes = destinationArray; } XmlAttribute xmlAttribute = attributes[attributeCount]; if (xmlAttribute == null) { xmlAttribute = new XmlAttribute(); attributes[attributeCount] = xmlAttribute; } xmlAttribute.XmlLang = lang; xmlAttribute.XmlSpace = space; xmlAttribute.Depth = depth; attributeCount++; } public string AddNamespace(string uri, XmlDictionaryString uriDictionaryString) { if (uri.Length == 0) { AddNamespaceIfNotDeclared(string.Empty, uri, uriDictionaryString); return string.Empty; } for (int i = 0; i < prefixes.Length; i++) { string text = prefixes[i]; bool flag = false; for (int num = nsCount - 1; num >= nsTop; num--) { if (namespaces[num].Prefix == text) { flag = true; break; } } if (!flag) { AddNamespace(text, uri, uriDictionaryString); return text; } } return null; } public void AddNamespaceIfNotDeclared(string prefix, string uri, XmlDictionaryString uriDictionaryString) { if (LookupNamespace(prefix) != uri) { AddNamespace(prefix, uri, uriDictionaryString); } } public void AddNamespace(string prefix, string uri, XmlDictionaryString uriDictionaryString) { if (prefix.Length >= 3 && (prefix[0] & -33) == 88 && (prefix[1] & -33) == 77 && (prefix[2] & -33) == 76) { if ((!(prefix == "xml") || !(uri == "http://www.w3.org/XML/1998/namespace")) && (!(prefix == "xmlns") || !(uri == "http://www.w3.org/2000/xmlns/"))) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Prefixes beginning with \"xml\" (regardless of casing) are reserved for use by XML."), "prefix")); } return; } Namespace @namespace; for (int num = nsCount - 1; num >= 0; num--) { @namespace = namespaces[num]; if (@namespace.Depth != depth) { break; } if (@namespace.Prefix == prefix) { if (@namespace.Uri == uri) { return; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("The prefix '{0}' is bound to the namespace '{1}' and cannot be changed to '{2}'.", prefix, @namespace.Uri, uri), "prefix")); } } if (prefix.Length != 0 && uri.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("The empty namespace requires a null or empty prefix."), "prefix")); } if (uri.Length == "http://www.w3.org/2000/xmlns/".Length && uri == "http://www.w3.org/2000/xmlns/") { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("The namespace '{1}' can only be bound to the prefix '{0}'.", "xmlns", uri))); } if (uri.Length == "http://www.w3.org/XML/1998/namespace".Length && uri[18] == 'X' && uri == "http://www.w3.org/XML/1998/namespace") { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("The namespace '{1}' can only be bound to the prefix '{0}'.", "xml", uri))); } if (namespaces.Length == nsCount) { Namespace[] destinationArray = new Namespace[nsCount * 2]; Array.Copy(namespaces, destinationArray, nsCount); namespaces = destinationArray; } @namespace = namespaces[nsCount]; if (@namespace == null) { @namespace = new Namespace(); namespaces[nsCount] = @namespace; } @namespace.Depth = depth; @namespace.Prefix = prefix; @namespace.Uri = uri; @namespace.UriDictionaryString = uriDictionaryString; nsCount++; lastNameSpace = null; } public string LookupPrefix(string ns) { if (lastNameSpace != null && lastNameSpace.Uri == ns) { return lastNameSpace.Prefix; } int num = nsCount; for (int num2 = num - 1; num2 >= nsTop; num2--) { Namespace @namespace = namespaces[num2]; if ((object)@namespace.Uri == ns) { string prefix = @namespace.Prefix; bool flag = false; for (int i = num2 + 1; i < num; i++) { if (namespaces[i].Prefix == prefix) { flag = true; break; } } if (!flag) { lastNameSpace = @namespace; return prefix; } } } for (int num3 = num - 1; num3 >= nsTop; num3--) { Namespace namespace2 = namespaces[num3]; if (namespace2.Uri == ns) { string prefix2 = namespace2.Prefix; bool flag2 = false; for (int j = num3 + 1; j < num; j++) { if (namespaces[j].Prefix == prefix2) { flag2 = true; break; } } if (!flag2) { lastNameSpace = namespace2; return prefix2; } } } if (ns.Length == 0) { bool flag3 = true; for (int num4 = num - 1; num4 >= nsTop; num4--) { if (namespaces[num4].Prefix.Length == 0) { flag3 = false; break; } } if (flag3) { return string.Empty; } } if (ns == "http://www.w3.org/2000/xmlns/") { return "xmlns"; } if (ns == "http://www.w3.org/XML/1998/namespace") { return "xml"; } return null; } public string LookupAttributePrefix(string ns) { if (lastNameSpace != null && lastNameSpace.Uri == ns && lastNameSpace.Prefix.Length != 0) { return lastNameSpace.Prefix; } int num = nsCount; for (int num2 = num - 1; num2 >= nsTop; num2--) { Namespace @namespace = namespaces[num2]; if ((object)@namespace.Uri == ns) { string prefix = @namespace.Prefix; if (prefix.Length != 0) { bool flag = false; for (int i = num2 + 1; i < num; i++) { if (namespaces[i].Prefix == prefix) { flag = true; break; } } if (!flag) { lastNameSpace = @namespace; return prefix; } } } } for (int num3 = num - 1; num3 >= nsTop; num3--) { Namespace namespace2 = namespaces[num3]; if (namespace2.Uri == ns) { string prefix2 = namespace2.Prefix; if (prefix2.Length != 0) { bool flag2 = false; for (int j = num3 + 1; j < num; j++) { if (namespaces[j].Prefix == prefix2) { flag2 = true; break; } } if (!flag2) { lastNameSpace = namespace2; return prefix2; } } } } if (ns.Length == 0) { return string.Empty; } return null; } public string LookupNamespace(string prefix) { int num = nsCount; if (prefix.Length == 0) { for (int num2 = num - 1; num2 >= nsTop; num2--) { Namespace @namespace = namespaces[num2]; if (@namespace.Prefix.Length == 0) { return @namespace.Uri; } } return string.Empty; } if (prefix.Length == 1) { char c = prefix[0]; for (int num3 = num - 1; num3 >= nsTop; num3--) { Namespace namespace2 = namespaces[num3]; if (namespace2.PrefixChar == c) { return namespace2.Uri; } } return null; } for (int num4 = num - 1; num4 >= nsTop; num4--) { Namespace namespace3 = namespaces[num4]; if (namespace3.Prefix == prefix) { return namespace3.Uri; } } if (prefix == "xmlns") { return "http://www.w3.org/2000/xmlns/"; } if (prefix == "xml") { return "http://www.w3.org/XML/1998/namespace"; } return null; } public void Sign(XmlCanonicalWriter signingWriter) { int num = nsCount; for (int i = 1; i < num; i++) { Namespace @namespace = namespaces[i]; bool flag = false; for (int j = i + 1; j < num; j++) { if (flag) { break; } flag = @namespace.Prefix == namespaces[j].Prefix; } if (!flag) { signingWriter.WriteXmlnsAttribute(@namespace.Prefix, @namespace.Uri); } } } } private class XmlBaseWriterNodeWriterAsyncHelper { private static AsyncEventArgsCallback onWriteComplete; private XmlBaseWriter writer; private byte[] buffer; private int offset; private int count; private int actualByteCount; private int totalByteCount; private AsyncEventArgs nodeWriterAsyncState; private XmlNodeWriterWriteBase64TextArgs nodeWriterArgs; private AsyncEventArgs inputState; public XmlBaseWriterNodeWriterAsyncHelper(XmlBaseWriter writer) { this.writer = writer; } public void SetArguments(AsyncEventArgs inputState) { this.inputState = inputState; buffer = inputState.Arguments.Buffer; offset = inputState.Arguments.Offset; count = inputState.Arguments.Count; } public AsyncCompletionResult StartAsync() { bool flag = true; if (count > 0) { if (writer.trailByteCount > 0) { while (writer.trailByteCount < 3 && count > 0) { writer.trailBytes[writer.trailByteCount++] = buffer[offset++]; count--; } } totalByteCount = writer.trailByteCount + count; actualByteCount = totalByteCount - totalByteCount % 3; if (writer.trailBytes == null) { writer.trailBytes = new byte[3]; } if (actualByteCount >= 3) { if (writer.attributeValue != null) { writer.WriteAttributeText(XmlConverter.Base64Encoding.GetString(writer.trailBytes, 0, writer.trailByteCount)); writer.WriteAttributeText(XmlConverter.Base64Encoding.GetString(buffer, offset, actualByteCount - writer.trailByteCount)); } flag = HandleWriteBase64Text(isAsyncCallback: false); } else { Buffer.BlockCopy(buffer, offset, writer.trailBytes, writer.trailByteCount, count); writer.trailByteCount += count; } } if (flag) { Clear(); return (AsyncCompletionResult)1; } return (AsyncCompletionResult)0; } private static void OnWriteComplete(IAsyncEventArgs asyncEventArgs) { bool flag = false; Exception ex = null; XmlBaseWriterNodeWriterAsyncHelper xmlBaseWriterNodeWriterAsyncHelper = (XmlBaseWriterNodeWriterAsyncHelper)asyncEventArgs.AsyncState; AsyncEventArgs val = xmlBaseWriterNodeWriterAsyncHelper.inputState; try { if (asyncEventArgs.Exception != null) { ex = asyncEventArgs.Exception; flag = true; } else { flag = xmlBaseWriterNodeWriterAsyncHelper.HandleWriteBase64Text(isAsyncCallback: true); } } catch (Exception ex2) { if (Fx.IsFatal(ex2)) { throw; } ex = ex2; flag = true; } if (flag) { xmlBaseWriterNodeWriterAsyncHelper.Clear(); ((AsyncEventArgs)val).Complete(false, ex); } } private bool HandleWriteBase64Text(bool isAsyncCallback) { //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Invalid comparison between Unknown and I4 //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown if (!writer.isXmlnsAttribute) { if (!isAsyncCallback) { if (nodeWriterAsyncState == null) { nodeWriterAsyncState = new AsyncEventArgs(); nodeWriterArgs = new XmlNodeWriterWriteBase64TextArgs(); } if (onWriteComplete == null) { onWriteComplete = new AsyncEventArgsCallback(OnWriteComplete); } writer.StartContent(); nodeWriterArgs.TrailBuffer = writer.trailBytes; nodeWriterArgs.TrailCount = writer.trailByteCount; nodeWriterArgs.Buffer = buffer; nodeWriterArgs.Offset = offset; nodeWriterArgs.Count = actualByteCount - writer.trailByteCount; nodeWriterAsyncState.Set(onWriteComplete, nodeWriterArgs, (object)this); if ((int)writer.writer.WriteBase64TextAsync(nodeWriterAsyncState) != 1) { return false; } ((AsyncEventArgs)nodeWriterAsyncState).Complete(true); } writer.EndContent(); } writer.trailByteCount = totalByteCount - actualByteCount; if (writer.trailByteCount > 0) { int num = offset + count - writer.trailByteCount; for (int i = 0; i < writer.trailByteCount; i++) { writer.trailBytes[i] = buffer[num++]; } } return true; } private void Clear() { inputState = null; buffer = null; offset = 0; count = 0; actualByteCount = 0; totalByteCount = 0; } } private XmlNodeWriter writer; private NamespaceManager nsMgr; private Element[] elements; private int depth; private string attributeLocalName; private string attributeValue; private bool isXmlAttribute; private bool isXmlnsAttribute; private WriteState writeState; private DocumentState documentState; private byte[] trailBytes; private int trailByteCount; private XmlStreamNodeWriter nodeWriter; private XmlSigningNodeWriter signingWriter; private XmlUTF8NodeWriter textFragmentWriter; private XmlNodeWriter oldWriter; private Stream oldStream; private int oldNamespaceBoundary; private bool inList; private const string xmlnsNamespace = "http://www.w3.org/2000/xmlns/"; private const string xmlNamespace = "http://www.w3.org/XML/1998/namespace"; private static BinHexEncoding binhexEncoding; private static string[] prefixes = new string[26] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; private XmlBaseWriterNodeWriterAsyncHelper nodeWriterAsyncHelper; protected bool IsClosed => writeState == WriteState.Closed; private static BinHexEncoding BinHexEncoding { get { if (binhexEncoding == null) { binhexEncoding = new BinHexEncoding(); } return binhexEncoding; } } public override string XmlLang => nsMgr.XmlLang; public override XmlSpace XmlSpace => nsMgr.XmlSpace; public override WriteState WriteState => writeState; protected int NamespaceBoundary { get { return nsMgr.NamespaceBoundary; } set { nsMgr.NamespaceBoundary = value; } } public override bool CanCanonicalize => true; protected bool Signing => writer == signingWriter; public virtual bool CanFragment => true; protected XmlBaseWriter() { nsMgr = new NamespaceManager(); writeState = WriteState.Start; documentState = DocumentState.None; } protected void SetOutput(XmlStreamNodeWriter writer) { inList = false; this.writer = writer; nodeWriter = writer; writeState = WriteState.Start; documentState = DocumentState.None; nsMgr.Clear(); if (depth != 0) { elements = null; depth = 0; } attributeLocalName = null; attributeValue = null; oldWriter = null; oldStream = null; } public override void Flush() { if (IsClosed) { ThrowClosed(); } writer.Flush(); } public override void Close() { if (IsClosed) { return; } try { FinishDocument(); AutoComplete(WriteState.Closed); writer.Flush(); } finally { nsMgr.Close(); if (depth != 0) { elements = null; depth = 0; } attributeValue = null; attributeLocalName = null; nodeWriter.Close(); if (signingWriter != null) { signingWriter.Close(); } if (textFragmentWriter != null) { textFragmentWriter.Close(); } oldWriter = null; oldStream = null; } } protected void ThrowClosed() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("The XmlWriter is closed."))); } public override void WriteXmlnsAttribute(string prefix, string ns) { if (IsClosed) { ThrowClosed(); } if (ns == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ns"); } if (writeState != WriteState.Element) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("'{0}' cannot be called while WriteState is '{1}'.", "WriteXmlnsAttribute", WriteState.ToString()))); } if (prefix == null) { prefix = nsMgr.LookupPrefix(ns); if (prefix == null) { GeneratePrefix(ns, null); } } else { nsMgr.AddNamespaceIfNotDeclared(prefix, ns, null); } } public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) { if (IsClosed) { ThrowClosed(); } if (ns == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ns"); } if (writeState != WriteState.Element) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("'{0}' cannot be called while WriteState is '{1}'.", "WriteXmlnsAttribute", WriteState.ToString()))); } if (prefix == null) { prefix = nsMgr.LookupPrefix(ns.Value); if (prefix == null) { GeneratePrefix(ns.Value, ns); } } else { nsMgr.AddNamespaceIfNotDeclared(prefix, ns.Value, ns); } } private void StartAttribute(ref string prefix, string localName, string ns, XmlDictionaryString xNs) { if (IsClosed) { ThrowClosed(); } if (writeState == WriteState.Attribute) { WriteEndAttribute(); } if (localName == null || (localName.Length == 0 && prefix != "xmlns")) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localName")); } if (writeState != WriteState.Element) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("'{0}' cannot be called while WriteState is '{1}'.", "WriteStartAttribute", WriteState.ToString()))); } if (prefix == null) { if (ns == "http://www.w3.org/2000/xmlns/" && localName != "xmlns") { prefix = "xmlns"; } else if (ns == "http://www.w3.org/XML/1998/namespace") { prefix = "xml"; } else { prefix = string.Empty; } } if (prefix.Length == 0 && localName == "xmlns") { prefix = "xmlns"; localName = string.Empty; } isXmlnsAttribute = false; isXmlAttribute = false; if (prefix == "xml") { if (ns != null && ns != "http://www.w3.org/XML/1998/namespace") { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("The prefix '{0}' is bound to the namespace '{1}' and cannot be changed to '{2}'.", "xml", "http://www.w3.org/XML/1998/namespace", ns), "ns")); } isXmlAttribute = true; attributeValue = string.Empty; attributeLocalName = localName; } else if (prefix == "xmlns") { if (ns != null && ns != "http://www.w3.org/2000/xmlns/") { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("The prefix '{0}' is bound to the namespace '{1}' and cannot be changed to '{2}'.", "xmlns", "http://www.w3.org/2000/xmlns/", ns), "ns")); } isXmlnsAttribute = true; attributeValue = string.Empty; attributeLocalName = localName; } else if (ns == null) { if (prefix.Length == 0) { ns = string.Empty; } else { ns = nsMgr.LookupNamespace(prefix); if (ns == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("The prefix '{0}' is not defined.", prefix), "prefix")); } } } else if (ns.Length == 0) { if (prefix.Length != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("The empty namespace requires a null or empty prefix."), "prefix")); } } else if (prefix.Length == 0) { prefix = nsMgr.LookupAttributePrefix(ns); if (prefix == null) { if (ns.Length == "http://www.w3.org/2000/xmlns/".Length && ns == "http://www.w3.org/2000/xmlns/") { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("The namespace '{1}' can only be bound to the prefix '{0}'.", "xmlns", ns))); } if (ns.Length == "http://www.w3.org/XML/1998/namespace".Length && ns == "http://www.w3.org/XML/1998/namespace") { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("The namespace '{1}' can only be bound to the prefix '{0}'.", "xml", ns))); } prefix = GeneratePrefix(ns, xNs); } } else { nsMgr.AddNamespaceIfNotDeclared(prefix, ns, xNs); } writeState = WriteState.Attribute; } public override void WriteStartAttribute(string prefix, string localName, string namespaceUri) { StartAttribute(ref prefix, localName, namespaceUri, null); if (!isXmlnsAttribute) { writer.WriteStartAttribute(prefix, localName); } } public override void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri) { StartAttribute(ref prefix, localName?.Value, namespaceUri?.Value, namespaceUri); if (!isXmlnsAttribute) { writer.WriteStartAttribute(prefix, localName); } } public override void WriteEndAttribute() { if (IsClosed) { ThrowClosed(); } if (writeState != WriteState.Attribute) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("'{0}' cannot be called while WriteState is '{1}'.", "WriteEndAttribute", WriteState.ToString()))); } FlushBase64(); try { if (isXmlAttribute) { if (attributeLocalName == "lang") { nsMgr.AddLangAttribute(attributeValue); } else if (attributeLocalName == "space") { if (attributeValue == "preserve") { nsMgr.AddSpaceAttribute(XmlSpace.Preserve); } else { if (!(attributeValue == "default")) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("'{0}' is not a valid xml:space value. Valid values are 'default' and 'preserve'.", attributeValue))); } nsMgr.AddSpaceAttribute(XmlSpace.Default); } } isXmlAttribute = false; attributeLocalName = null; attributeValue = null; } if (isXmlnsAttribute) { nsMgr.AddNamespaceIfNotDeclared(attributeLocalName, attributeValue, null); isXmlnsAttribute = false; attributeLocalName = null; attributeValue = null; } else { writer.WriteEndAttribute(); } } finally { writeState = WriteState.Element; } } public override void WriteComment(string text) { if (IsClosed) { ThrowClosed(); } if (writeState == WriteState.Attribute) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("'{0}' cannot be called while WriteState is '{1}'.", "WriteComment", WriteState.ToString()))); } if (text == null) { text = string.Empty; } else if (text.IndexOf("--", StringComparison.Ordinal) != -1 || (text.Length > 0 && text[text.Length - 1] == '-')) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("XML comments cannot contain '--' or end with '-'."), "text")); } StartComment(); FlushBase64(); writer.WriteComment(text); EndComment(); } public override void WriteFullEndElement() { if (IsClosed) { ThrowClosed(); } if (writeState == WriteState.Attribute) { WriteEndAttribute(); } if (writeState != WriteState.Element && writeState != WriteState.Content) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("'{0}' cannot be called while WriteState is '{1}'.", "WriteFullEndElement", WriteState.ToString()))); } AutoComplete(WriteState.Content); WriteEndElement(); } public override void WriteCData(string text) { if (IsClosed) { ThrowClosed(); } if (writeState == WriteState.Attribute) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("'{0}' cannot be called while WriteState is '{1}'.", "WriteCData", WriteState.ToString()))); } if (text == null) { text = string.Empty; } if (text.Length > 0) { StartContent(); FlushBase64(); writer.WriteCData(text); EndContent(); } } public override void WriteDocType(string name, string pubid, string sysid, string subset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("This XmlWriter implementation does not support the '{0}' method.", "WriteDocType"))); } private void StartElement(ref string prefix, string localName, string ns, XmlDictionaryString xNs) { if (IsClosed) { ThrowClosed(); } if (documentState == DocumentState.Epilog) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("Only one root element is permitted per document."))); } if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localName")); } if (localName.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("The empty string is not a valid local name."), "localName")); } if (writeState == WriteState.Attribute) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("'{0}' cannot be called while WriteState is '{1}'.", "WriteStartElement", WriteState.ToString()))); } FlushBase64(); AutoComplete(WriteState.Element); Element element = EnterScope(); if (ns == null) { if (prefix == null) { prefix = string.Empty; } ns = nsMgr.LookupNamespace(prefix); if (ns == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("The prefix '{0}' is not defined.", prefix), "prefix")); } } else if (prefix == null) { prefix = nsMgr.LookupPrefix(ns); if (prefix == null) { prefix = string.Empty; nsMgr.AddNamespace(string.Empty, ns, xNs); } } else { nsMgr.AddNamespaceIfNotDeclared(prefix, ns, xNs); } element.Prefix = prefix; element.LocalName = localName; } public override void WriteStartElement(string prefix, string localName, string namespaceUri) { StartElement(ref prefix, localName, namespaceUri, null); writer.WriteStartElement(prefix, localName); } public override void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri) { StartElement(ref prefix, localName?.Value, namespaceUri?.Value, namespaceUri); writer.WriteStartElement(prefix, localName); } public override void WriteEndElement() { if (IsClosed) { ThrowClosed(); } if (depth == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("Cannot call '{0}' while Depth is '{1}'.", "WriteEndElement", depth.ToString(CultureInfo.InvariantCulture)))); } if (writeState == WriteState.Attribute) { WriteEndAttribute(); } FlushBase64(); if (writeState == WriteState.Element) { nsMgr.DeclareNamespaces(writer); writer.WriteEndStartElement(isEmpty: true); } else { Element element = elements[depth]; writer.WriteEndElement(element.Prefix, element.LocalName); } ExitScope(); writeState = WriteState.Content; } private Element EnterScope() { nsMgr.EnterScope(); depth++; if (elements == null) { elements = new Element[4]; } else if (elements.Length == depth) { Element[] destinationArray = new Element[depth * 2]; Array.Copy(elements, destinationArray, depth); elements = destinationArray; } Element element = elements[depth]; if (element == null) { element = new Element(); elements[depth] = element; } return element; } private void ExitScope() { elements[depth].Clear(); depth--; if (depth == 0 && documentState == DocumentState.Document) { documentState = DocumentState.Epilog; } nsMgr.ExitScope(); } protected void FlushElement() { if (writeState == WriteState.Element) { AutoComplete(WriteState.Content); } } protected void StartComment() { FlushElement(); } protected void EndComment() { } protected void StartContent() { FlushElement(); if (depth == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("Text cannot be written outside the root element."))); } } protected void StartContent(char ch) { FlushElement(); if (depth == 0) { VerifyWhitespace(ch); } } protected void StartContent(string s) { FlushElement(); if (depth == 0) { VerifyWhitespace(s); } } protected void StartContent(char[] chars, int offset, int count) { FlushElement(); if (depth == 0) { VerifyWhitespace(chars, offset, count); } } private void VerifyWhitespace(char ch) { if (!IsWhitespace(ch)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("Text cannot be written outside the root element."))); } } private void VerifyWhitespace(string s) { for (int i = 0; i < s.Length; i++) { if (!IsWhitespace(s[i])) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("Text cannot be written outside the root element."))); } } } private void VerifyWhitespace(char[] chars, int offset, int count) { for (int i = 0; i < count; i++) { if (!IsWhitespace(chars[offset + i])) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("Text cannot be written outside the root element."))); } } } private bool IsWhitespace(char ch) { if (ch != ' ' && ch != '\n' && ch != '\r') { return ch == 't'; } return true; } protected void EndContent() { } private void AutoComplete(WriteState writeState) { if (this.writeState == WriteState.Element) { EndStartElement(); } this.writeState = writeState; } private void EndStartElement() { nsMgr.DeclareNamespaces(writer); writer.WriteEndStartElement(isEmpty: false); } public override string LookupPrefix(string ns) { if (ns == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("ns")); } if (IsClosed) { ThrowClosed(); } return nsMgr.LookupPrefix(ns); } internal string LookupNamespace(string prefix) { if (prefix == null) { return null; } return nsMgr.LookupNamespace(prefix); } private string GetQualifiedNamePrefix(string namespaceUri, XmlDictionaryString xNs) { string text = nsMgr.LookupPrefix(namespaceUri); if (text == null) { if (writeState != WriteState.Attribute) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("The namespace '{0}' is not defined.", namespaceUri), "namespaceUri")); } text = GeneratePrefix(namespaceUri, xNs); } return text; } public override void WriteQualifiedName(string localName, string namespaceUri) { if (IsClosed) { ThrowClosed(); } if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localName")); } if (localName.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("The empty string is not a valid local name."), "localName")); } if (namespaceUri == null) { namespaceUri = string.Empty; } string qualifiedNamePrefix = GetQualifiedNamePrefix(namespaceUri, null); if (qualifiedNamePrefix.Length != 0) { WriteString(qualifiedNamePrefix); WriteString(":"); } WriteString(localName); } public override void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { if (IsClosed) { ThrowClosed(); } if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localName")); } if (localName.Value.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("The empty string is not a valid local name."), "localName")); } if (namespaceUri == null) { namespaceUri = XmlDictionaryString.Empty; } string qualifiedNamePrefix = GetQualifiedNamePrefix(namespaceUri.Value, namespaceUri); FlushBase64(); if (attributeValue != null) { WriteAttributeText(qualifiedNamePrefix + ":" + namespaceUri.Value); } if (!isXmlnsAttribute) { StartContent(); writer.WriteQualifiedName(qualifiedNamePrefix, localName); EndContent(); } } public override void WriteStartDocument() { if (IsClosed) { ThrowClosed(); } if (writeState != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("'{0}' cannot be called while WriteState is '{1}'.", "WriteStartDocument", WriteState.ToString()))); } writeState = WriteState.Prolog; documentState = DocumentState.Document; writer.WriteDeclaration(); } public override void WriteStartDocument(bool standalone) { if (IsClosed) { ThrowClosed(); } WriteStartDocument(); } public override void WriteProcessingInstruction(string name, string text) { if (IsClosed) { ThrowClosed(); } if (name != "xml") { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Processing instructions (other than the XML declaration) and DTDs are not supported."), "name")); } if (writeState != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("XML declaration can only be written at the beginning of the document."))); } writer.WriteDeclaration(); } private void FinishDocument() { if (writeState == WriteState.Attribute) { WriteEndAttribute(); } while (depth > 0) { WriteEndElement(); } } public override void WriteEndDocument() { if (IsClosed) { ThrowClosed(); } if (writeState == WriteState.Start || writeState == WriteState.Prolog) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("The document does not have a root element."))); } FinishDocument(); writeState = WriteState.Start; documentState = DocumentState.End; } public override void WriteEntityRef(string name) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("This XmlWriter implementation does not support the '{0}' method.", "WriteEntityRef"))); } public override void WriteName(string name) { if (IsClosed) { ThrowClosed(); } WriteString(name); } public override void WriteNmToken(string name) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("This XmlWriter implementation does not support the '{0}' method.", "WriteNmToken"))); } public override void WriteWhitespace(string whitespace) { if (IsClosed) { ThrowClosed(); } if (whitespace == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("whitespace"); } foreach (char c in whitespace) { if (c != ' ' && c != '\t' && c != '\n' && c != '\r') { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Only white space characters can be written with this method."), "whitespace")); } } WriteString(whitespace); } public override void WriteString(string value) { if (IsClosed) { ThrowClosed(); } if (value == null) { value = string.Empty; } if (value.Length > 0 || inList) { FlushBase64(); if (attributeValue != null) { WriteAttributeText(value); } if (!isXmlnsAttribute) { StartContent(value); writer.WriteEscapedText(value); EndContent(); } } } public override void WriteString(XmlDictionaryString value) { if (IsClosed) { ThrowClosed(); } if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } if (value.Value.Length > 0) { FlushBase64(); if (attributeValue != null) { WriteAttributeText(value.Value); } if (!isXmlnsAttribute) { StartContent(value.Value); writer.WriteEscapedText(value); EndContent(); } } } public override void WriteChars(char[] chars, int offset, int count) { if (IsClosed) { ThrowClosed(); } if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > chars.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", chars.Length - offset))); } if (count > 0) { FlushBase64(); if (attributeValue != null) { WriteAttributeText(new string(chars, offset, count)); } if (!isXmlnsAttribute) { StartContent(chars, offset, count); writer.WriteEscapedText(chars, offset, count); EndContent(); } } } public override void WriteRaw(string value) { if (IsClosed) { ThrowClosed(); } if (value == null) { value = string.Empty; } if (value.Length > 0) { FlushBase64(); if (attributeValue != null) { WriteAttributeText(value); } if (!isXmlnsAttribute) { StartContent(value); writer.WriteText(value); EndContent(); } } } public override void WriteRaw(char[] chars, int offset, int count) { if (IsClosed) { ThrowClosed(); } if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > chars.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", chars.Length - offset))); } if (count > 0) { FlushBase64(); if (attributeValue != null) { WriteAttributeText(new string(chars, offset, count)); } if (!isXmlnsAttribute) { StartContent(chars, offset, count); writer.WriteText(chars, offset, count); EndContent(); } } } public override void WriteCharEntity(char ch) { if (IsClosed) { ThrowClosed(); } if (ch >= '\ud800' && ch <= '\udfff') { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("The surrogate pair is invalid. Missing a low surrogate character."), "ch")); } if (attributeValue != null) { WriteAttributeText(ch.ToString()); } if (!isXmlnsAttribute) { StartContent(ch); FlushBase64(); writer.WriteCharEntity(ch); EndContent(); } } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { if (IsClosed) { ThrowClosed(); } SurrogateChar surrogateChar = new SurrogateChar(lowChar, highChar); if (attributeValue != null) { char[] value = new char[2] { highChar, lowChar }; WriteAttributeText(new string(value)); } if (!isXmlnsAttribute) { StartContent(); FlushBase64(); writer.WriteCharEntity(surrogateChar.Char); EndContent(); } } public override void WriteValue(object value) { if (IsClosed) { ThrowClosed(); } if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } if (value is object[]) { WriteValue((object[])value); } else if (value is Array) { WriteValue((Array)value); } else if (value is IStreamProvider) { WriteValue((IStreamProvider)value); } else { WritePrimitiveValue(value); } } protected void WritePrimitiveValue(object value) { if (IsClosed) { ThrowClosed(); } if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } if (value is ulong) { WriteValue((ulong)value); return; } if (value is string) { WriteValue((string)value); return; } if (value is int) { WriteValue((int)value); return; } if (value is long) { WriteValue((long)value); return; } if (value is bool) { WriteValue((bool)value); return; } if (value is double) { WriteValue((double)value); return; } if (value is DateTime) { WriteValue((DateTime)value); return; } if (value is float) { WriteValue((float)value); return; } if (value is decimal) { WriteValue((decimal)value); return; } if (value is XmlDictionaryString) { WriteValue((XmlDictionaryString)value); return; } if (value is UniqueId) { WriteValue((UniqueId)value); return; } if (value is Guid) { WriteValue((Guid)value); return; } if (value is TimeSpan) { WriteValue((TimeSpan)value); return; } if (value.GetType().IsArray) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Nested arrays are not supported."), "value")); } base.WriteValue(value); } public override void WriteValue(string value) { if (IsClosed) { ThrowClosed(); } WriteString(value); } public override void WriteValue(int value) { if (IsClosed) { ThrowClosed(); } FlushBase64(); if (attributeValue != null) { WriteAttributeText(XmlConverter.ToString(value)); } if (!isXmlnsAttribute) { StartContent(); writer.WriteInt32Text(value); EndContent(); } } public override void WriteValue(long value) { if (IsClosed) { ThrowClosed(); } FlushBase64(); if (attributeValue != null) { WriteAttributeText(XmlConverter.ToString(value)); } if (!isXmlnsAttribute) { StartContent(); writer.WriteInt64Text(value); EndContent(); } } private void WriteValue(ulong value) { if (IsClosed) { ThrowClosed(); } FlushBase64(); if (attributeValue != null) { WriteAttributeText(XmlConverter.ToString(value)); } if (!isXmlnsAttribute) { StartContent(); writer.WriteUInt64Text(value); EndContent(); } } public override void WriteValue(bool value) { if (IsClosed) { ThrowClosed(); } FlushBase64(); if (attributeValue != null) { WriteAttributeText(XmlConverter.ToString(value)); } if (!isXmlnsAttribute) { StartContent(); writer.WriteBoolText(value); EndContent(); } } public override void WriteValue(decimal value) { if (IsClosed) { ThrowClosed(); } FlushBase64(); if (attributeValue != null) { WriteAttributeText(XmlConverter.ToString(value)); } if (!isXmlnsAttribute) { StartContent(); writer.WriteDecimalText(value); EndContent(); } } public override void WriteValue(float value) { if (IsClosed) { ThrowClosed(); } FlushBase64(); if (attributeValue != null) { WriteAttributeText(XmlConverter.ToString(value)); } if (!isXmlnsAttribute) { StartContent(); writer.WriteFloatText(value); EndContent(); } } public override void WriteValue(double value) { if (IsClosed) { ThrowClosed(); } FlushBase64(); if (attributeValue != null) { WriteAttributeText(XmlConverter.ToString(value)); } if (!isXmlnsAttribute) { StartContent(); writer.WriteDoubleText(value); EndContent(); } } public override void WriteValue(XmlDictionaryString value) { WriteString(value); } public override void WriteValue(DateTime value) { if (IsClosed) { ThrowClosed(); } FlushBase64(); if (attributeValue != null) { WriteAttributeText(XmlConverter.ToString(value)); } if (!isXmlnsAttribute) { StartContent(); writer.WriteDateTimeText(value); EndContent(); } } public override void WriteValue(UniqueId value) { if (IsClosed) { ThrowClosed(); } if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } FlushBase64(); if (attributeValue != null) { WriteAttributeText(XmlConverter.ToString(value)); } if (!isXmlnsAttribute) { StartContent(); writer.WriteUniqueIdText(value); EndContent(); } } public override void WriteValue(Guid value) { if (IsClosed) { ThrowClosed(); } FlushBase64(); if (attributeValue != null) { WriteAttributeText(XmlConverter.ToString(value)); } if (!isXmlnsAttribute) { StartContent(); writer.WriteGuidText(value); EndContent(); } } public override void WriteValue(TimeSpan value) { if (IsClosed) { ThrowClosed(); } FlushBase64(); if (attributeValue != null) { WriteAttributeText(XmlConverter.ToString(value)); } if (!isXmlnsAttribute) { StartContent(); writer.WriteTimeSpanText(value); EndContent(); } } public override void WriteBase64(byte[] buffer, int offset, int count) { if (IsClosed) { ThrowClosed(); } EnsureBufferBounds(buffer, offset, count); if (count <= 0) { return; } if (trailByteCount > 0) { while (trailByteCount < 3 && count > 0) { trailBytes[trailByteCount++] = buffer[offset++]; count--; } } int num = trailByteCount + count; int num2 = num - num % 3; if (trailBytes == null) { trailBytes = new byte[3]; } if (num2 >= 3) { if (attributeValue != null) { WriteAttributeText(XmlConverter.Base64Encoding.GetString(trailBytes, 0, trailByteCount)); WriteAttributeText(XmlConverter.Base64Encoding.GetString(buffer, offset, num2 - trailByteCount)); } if (!isXmlnsAttribute) { StartContent(); writer.WriteBase64Text(trailBytes, trailByteCount, buffer, offset, num2 - trailByteCount); EndContent(); } trailByteCount = num - num2; if (trailByteCount > 0) { int num3 = offset + count - trailByteCount; for (int i = 0; i < trailByteCount; i++) { trailBytes[i] = buffer[num3++]; } } } else { Buffer.BlockCopy(buffer, offset, trailBytes, trailByteCount, count); trailByteCount += count; } } internal override IAsyncResult BeginWriteBase64(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { if (IsClosed) { ThrowClosed(); } EnsureBufferBounds(buffer, offset, count); return (IAsyncResult)new WriteBase64AsyncResult(buffer, offset, count, this, callback, state); } internal override void EndWriteBase64(IAsyncResult result) { WriteBase64AsyncResult.End(result); } internal override AsyncCompletionResult WriteBase64Async(AsyncEventArgs state) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Invalid comparison between Unknown and I4 if (nodeWriterAsyncHelper == null) { nodeWriterAsyncHelper = new XmlBaseWriterNodeWriterAsyncHelper(this); } nodeWriterAsyncHelper.SetArguments(state); if ((int)nodeWriterAsyncHelper.StartAsync() != 1) { return (AsyncCompletionResult)0; } return (AsyncCompletionResult)1; } public override void WriteBinHex(byte[] buffer, int offset, int count) { if (IsClosed) { ThrowClosed(); } EnsureBufferBounds(buffer, offset, count); WriteRaw(BinHexEncoding.GetString(buffer, offset, count)); } public override void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes) { if (IsClosed) { ThrowClosed(); } if (Signing) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("XML canonicalization started"))); } FlushElement(); if (signingWriter == null) { signingWriter = CreateSigningNodeWriter(); } signingWriter.SetOutput(writer, stream, includeComments, inclusivePrefixes); writer = signingWriter; SignScope(signingWriter.CanonicalWriter); } public override void EndCanonicalization() { if (IsClosed) { ThrowClosed(); } if (!Signing) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("XML canonicalization was not started."))); } signingWriter.Flush(); writer = signingWriter.NodeWriter; } protected abstract XmlSigningNodeWriter CreateSigningNodeWriter(); public void StartFragment(Stream stream, bool generateSelfContainedTextFragment) { if (!CanFragment) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } if (IsClosed) { ThrowClosed(); } if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("stream")); } if (oldStream != null || oldWriter != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); } if (WriteState == WriteState.Attribute) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("'{0}' cannot be called while WriteState is '{1}'.", "StartFragment", WriteState.ToString()))); } FlushElement(); writer.Flush(); oldNamespaceBoundary = NamespaceBoundary; XmlStreamNodeWriter xmlStreamNodeWriter = null; if (generateSelfContainedTextFragment) { NamespaceBoundary = depth + 1; if (textFragmentWriter == null) { textFragmentWriter = new XmlUTF8NodeWriter(); } textFragmentWriter.SetOutput(stream, ownsStream: false, Encoding.UTF8); xmlStreamNodeWriter = textFragmentWriter; } if (Signing) { if (xmlStreamNodeWriter != null) { oldWriter = signingWriter.NodeWriter; signingWriter.NodeWriter = xmlStreamNodeWriter; } else { oldStream = ((XmlStreamNodeWriter)signingWriter.NodeWriter).Stream; ((XmlStreamNodeWriter)signingWriter.NodeWriter).Stream = stream; } } else if (xmlStreamNodeWriter != null) { oldWriter = writer; writer = xmlStreamNodeWriter; } else { oldStream = nodeWriter.Stream; nodeWriter.Stream = stream; } } public void EndFragment() { if (IsClosed) { ThrowClosed(); } if (oldStream == null && oldWriter == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); } if (WriteState == WriteState.Attribute) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("'{0}' cannot be called while WriteState is '{1}'.", "EndFragment", WriteState.ToString()))); } FlushElement(); writer.Flush(); if (Signing) { if (oldWriter != null) { signingWriter.NodeWriter = oldWriter; } else { ((XmlStreamNodeWriter)signingWriter.NodeWriter).Stream = oldStream; } } else if (oldWriter != null) { writer = oldWriter; } else { nodeWriter.Stream = oldStream; } NamespaceBoundary = oldNamespaceBoundary; oldWriter = null; oldStream = null; } public void WriteFragment(byte[] buffer, int offset, int count) { if (!CanFragment) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } if (IsClosed) { ThrowClosed(); } if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("buffer")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", buffer.Length - offset))); } if (WriteState == WriteState.Attribute) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("'{0}' cannot be called while WriteState is '{1}'.", "WriteFragment", WriteState.ToString()))); } if (writer != nodeWriter) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); } FlushElement(); FlushBase64(); nodeWriter.Flush(); nodeWriter.Stream.Write(buffer, offset, count); } private void FlushBase64() { if (trailByteCount > 0) { FlushTrailBytes(); } } private void FlushTrailBytes() { if (attributeValue != null) { WriteAttributeText(XmlConverter.Base64Encoding.GetString(trailBytes, 0, trailByteCount)); } if (!isXmlnsAttribute) { StartContent(); writer.WriteBase64Text(trailBytes, trailByteCount, trailBytes, 0, 0); EndContent(); } trailByteCount = 0; } private void WriteValue(object[] array) { FlushBase64(); StartContent(); writer.WriteStartListText(); inList = true; for (int i = 0; i < array.Length; i++) { if (i != 0) { writer.WriteListSeparator(); } WritePrimitiveValue(array[i]); } inList = false; writer.WriteEndListText(); EndContent(); } private void WriteValue(Array array) { FlushBase64(); StartContent(); writer.WriteStartListText(); inList = true; for (int i = 0; i < array.Length; i++) { if (i != 0) { writer.WriteListSeparator(); } WritePrimitiveValue(array.GetValue(i)); } inList = false; writer.WriteEndListText(); EndContent(); } protected void StartArray(int count) { FlushBase64(); if (documentState == DocumentState.Epilog) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("Only one root element is permitted per document."))); } if (documentState == DocumentState.Document && count > 1 && depth == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("Only one root element is permitted per document."))); } if (writeState == WriteState.Attribute) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("'{0}' cannot be called while WriteState is '{1}'.", "WriteStartElement", WriteState.ToString()))); } AutoComplete(WriteState.Content); } protected void EndArray() { } private void EnsureBufferBounds(byte[] buffer, int offset, int count) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", buffer.Length - offset))); } } private string GeneratePrefix(string ns, XmlDictionaryString xNs) { if (writeState != WriteState.Element && writeState != WriteState.Attribute) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("A prefix cannot be defined while WriteState is '{0}'.", WriteState.ToString()))); } string text = nsMgr.AddNamespace(ns, xNs); if (text != null) { return text; } do { int num = elements[depth].PrefixId++; text = "d" + depth.ToString(CultureInfo.InvariantCulture) + "p" + num.ToString(CultureInfo.InvariantCulture); } while (nsMgr.LookupNamespace(text) != null); nsMgr.AddNamespace(text, ns, xNs); return text; } protected void SignScope(XmlCanonicalWriter signingWriter) { nsMgr.Sign(signingWriter); } private void WriteAttributeText(string value) { if (attributeValue.Length == 0) { attributeValue = value; } else { attributeValue += value; } } } internal enum XmlBinaryNodeType { EndElement = 1, Comment = 2, Array = 3, MinAttribute = 4, ShortAttribute = 4, Attribute = 5, ShortDictionaryAttribute = 6, DictionaryAttribute = 7, ShortXmlnsAttribute = 8, XmlnsAttribute = 9, ShortDictionaryXmlnsAttribute = 10, DictionaryXmlnsAttribute = 11, PrefixDictionaryAttributeA = 12, PrefixDictionaryAttributeB = 13, PrefixDictionaryAttributeC = 14, PrefixDictionaryAttributeD = 15, PrefixDictionaryAttributeE = 16, PrefixDictionaryAttributeF = 17, PrefixDictionaryAttributeG = 18, PrefixDictionaryAttributeH = 19, PrefixDictionaryAttributeI = 20, PrefixDictionaryAttributeJ = 21, PrefixDictionaryAttributeK = 22, PrefixDictionaryAttributeL = 23, PrefixDictionaryAttributeM = 24, PrefixDictionaryAttributeN = 25, PrefixDictionaryAttributeO = 26, PrefixDictionaryAttributeP = 27, PrefixDictionaryAttributeQ = 28, PrefixDictionaryAttributeR = 29, PrefixDictionaryAttributeS = 30, PrefixDictionaryAttributeT = 31, PrefixDictionaryAttributeU = 32, PrefixDictionaryAttributeV = 33, PrefixDictionaryAttributeW = 34, PrefixDictionaryAttributeX = 35, PrefixDictionaryAttributeY = 36, PrefixDictionaryAttributeZ = 37, PrefixAttributeA = 38, PrefixAttributeB = 39, PrefixAttributeC = 40, PrefixAttributeD = 41, PrefixAttributeE = 42, PrefixAttributeF = 43, PrefixAttributeG = 44, PrefixAttributeH = 45, PrefixAttributeI = 46, PrefixAttributeJ = 47, PrefixAttributeK = 48, PrefixAttributeL = 49, PrefixAttributeM = 50, PrefixAttributeN = 51, PrefixAttributeO = 52, PrefixAttributeP = 53, PrefixAttributeQ = 54, PrefixAttributeR = 55, PrefixAttributeS = 56, PrefixAttributeT = 57, PrefixAttributeU = 58, PrefixAttributeV = 59, PrefixAttributeW = 60, PrefixAttributeX = 61, PrefixAttributeY = 62, PrefixAttributeZ = 63, MaxAttribute = 63, MinElement = 64, ShortElement = 64, Element = 65, ShortDictionaryElement = 66, DictionaryElement = 67, PrefixDictionaryElementA = 68, PrefixDictionaryElementB = 69, PrefixDictionaryElementC = 70, PrefixDictionaryElementD = 71, PrefixDictionaryElementE = 72, PrefixDictionaryElementF = 73, PrefixDictionaryElementG = 74, PrefixDictionaryElementH = 75, PrefixDictionaryElementI = 76, PrefixDictionaryElementJ = 77, PrefixDictionaryElementK = 78, PrefixDictionaryElementL = 79, PrefixDictionaryElementM = 80, PrefixDictionaryElementN = 81, PrefixDictionaryElementO = 82, PrefixDictionaryElementP = 83, PrefixDictionaryElementQ = 84, PrefixDictionaryElementR = 85, PrefixDictionaryElementS = 86, PrefixDictionaryElementT = 87, PrefixDictionaryElementU = 88, PrefixDictionaryElementV = 89, PrefixDictionaryElementW = 90, PrefixDictionaryElementX = 91, PrefixDictionaryElementY = 92, PrefixDictionaryElementZ = 93, PrefixElementA = 94, PrefixElementB = 95, PrefixElementC = 96, PrefixElementD = 97, PrefixElementE = 98, PrefixElementF = 99, PrefixElementG = 100, PrefixElementH = 101, PrefixElementI = 102, PrefixElementJ = 103, PrefixElementK = 104, PrefixElementL = 105, PrefixElementM = 106, PrefixElementN = 107, PrefixElementO = 108, PrefixElementP = 109, PrefixElementQ = 110, PrefixElementR = 111, PrefixElementS = 112, PrefixElementT = 113, PrefixElementU = 114, PrefixElementV = 115, PrefixElementW = 116, PrefixElementX = 117, PrefixElementY = 118, PrefixElementZ = 119, MaxElement = 119, MinText = 128, ZeroText = 128, OneText = 130, FalseText = 132, TrueText = 134, Int8Text = 136, Int16Text = 138, Int32Text = 140, Int64Text = 142, FloatText = 144, DoubleText = 146, DecimalText = 148, DateTimeText = 150, Chars8Text = 152, Chars16Text = 154, Chars32Text = 156, Bytes8Text = 158, Bytes16Text = 160, Bytes32Text = 162, StartListText = 164, EndListText = 166, EmptyText = 168, DictionaryText = 170, UniqueIdText = 172, TimeSpanText = 174, GuidText = 176, UInt64Text = 178, BoolText = 180, UnicodeChars8Text = 182, UnicodeChars16Text = 184, UnicodeChars32Text = 186, QNameDictionaryText = 188, ZeroTextWithEndElement = 129, OneTextWithEndElement = 131, FalseTextWithEndElement = 133, TrueTextWithEndElement = 135, Int8TextWithEndElement = 137, Int16TextWithEndElement = 139, Int32TextWithEndElement = 141, Int64TextWithEndElement = 143, FloatTextWithEndElement = 145, DoubleTextWithEndElement = 147, DecimalTextWithEndElement = 149, DateTimeTextWithEndElement = 151, Chars8TextWithEndElement = 153, Chars16TextWithEndElement = 155, Chars32TextWithEndElement = 157, Bytes8TextWithEndElement = 159, Bytes16TextWithEndElement = 161, Bytes32TextWithEndElement = 163, StartListTextWithEndElement = 165, EndListTextWithEndElement = 167, EmptyTextWithEndElement = 169, DictionaryTextWithEndElement = 171, UniqueIdTextWithEndElement = 173, TimeSpanTextWithEndElement = 175, GuidTextWithEndElement = 177, UInt64TextWithEndElement = 179, BoolTextWithEndElement = 181, UnicodeChars8TextWithEndElement = 183, UnicodeChars16TextWithEndElement = 185, UnicodeChars32TextWithEndElement = 187, QNameDictionaryTextWithEndElement = 189, MaxText = 189 } public interface IXmlBinaryReaderInitializer { void SetInput(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose); void SetInput(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose); } internal class XmlBinaryReader : XmlBaseReader, IXmlBinaryReaderInitializer { private enum ArrayState { None, Element, Content } private bool isTextWithEndElement; private bool buffered; private ArrayState arrayState; private int arrayCount; private int maxBytesPerRead; private XmlBinaryNodeType arrayNodeType; private OnXmlDictionaryReaderClose onClose; public void SetInput(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > buffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", buffer.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", buffer.Length - offset))); } MoveToInitial(quotas, session, onClose); base.BufferReader.SetBuffer(buffer, offset, count, dictionary, session); buffered = true; } public void SetInput(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose) { if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream"); } MoveToInitial(quotas, session, onClose); base.BufferReader.SetBuffer(stream, dictionary, session); buffered = false; } private void MoveToInitial(XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose) { MoveToInitial(quotas); maxBytesPerRead = quotas.MaxBytesPerRead; arrayState = ArrayState.None; this.onClose = onClose; isTextWithEndElement = false; } public override void Close() { base.Close(); OnXmlDictionaryReaderClose onXmlDictionaryReaderClose = onClose; onClose = null; if (onXmlDictionaryReaderClose == null) { return; } try { onXmlDictionaryReaderClose(this); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(ex); } } public override string ReadElementContentAsString() { if (base.Node.NodeType != XmlNodeType.Element) { MoveToStartElement(); } if (!CanOptimizeReadElementContent()) { return base.ReadElementContentAsString(); } string text; switch (GetNodeType()) { case XmlBinaryNodeType.Chars8TextWithEndElement: SkipNodeType(); text = base.BufferReader.ReadUTF8String(ReadUInt8()); ReadTextWithEndElement(); break; case XmlBinaryNodeType.DictionaryTextWithEndElement: SkipNodeType(); text = base.BufferReader.GetDictionaryString(ReadDictionaryKey()).Value; ReadTextWithEndElement(); break; default: text = base.ReadElementContentAsString(); break; } if (text.Length > Quotas.MaxStringContentLength) { XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, Quotas.MaxStringContentLength); } return text; } public override bool ReadElementContentAsBoolean() { if (base.Node.NodeType != XmlNodeType.Element) { MoveToStartElement(); } if (!CanOptimizeReadElementContent()) { return base.ReadElementContentAsBoolean(); } bool result; switch (GetNodeType()) { case XmlBinaryNodeType.TrueTextWithEndElement: SkipNodeType(); result = true; ReadTextWithEndElement(); break; case XmlBinaryNodeType.FalseTextWithEndElement: SkipNodeType(); result = false; ReadTextWithEndElement(); break; case XmlBinaryNodeType.BoolTextWithEndElement: SkipNodeType(); result = base.BufferReader.ReadUInt8() != 0; ReadTextWithEndElement(); break; default: result = base.ReadElementContentAsBoolean(); break; } return result; } public override int ReadElementContentAsInt() { if (base.Node.NodeType != XmlNodeType.Element) { MoveToStartElement(); } if (!CanOptimizeReadElementContent()) { return base.ReadElementContentAsInt(); } int result; switch (GetNodeType()) { case XmlBinaryNodeType.ZeroTextWithEndElement: SkipNodeType(); result = 0; ReadTextWithEndElement(); break; case XmlBinaryNodeType.OneTextWithEndElement: SkipNodeType(); result = 1; ReadTextWithEndElement(); break; case XmlBinaryNodeType.Int8TextWithEndElement: SkipNodeType(); result = base.BufferReader.ReadInt8(); ReadTextWithEndElement(); break; case XmlBinaryNodeType.Int16TextWithEndElement: SkipNodeType(); result = base.BufferReader.ReadInt16(); ReadTextWithEndElement(); break; case XmlBinaryNodeType.Int32TextWithEndElement: SkipNodeType(); result = base.BufferReader.ReadInt32(); ReadTextWithEndElement(); break; default: result = base.ReadElementContentAsInt(); break; } return result; } private bool CanOptimizeReadElementContent() { if (arrayState == ArrayState.None) { return !base.Signing; } return false; } public override float ReadElementContentAsFloat() { if (base.Node.NodeType != XmlNodeType.Element) { MoveToStartElement(); } if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.FloatTextWithEndElement) { SkipNodeType(); float result = base.BufferReader.ReadSingle(); ReadTextWithEndElement(); return result; } return base.ReadElementContentAsFloat(); } public override double ReadElementContentAsDouble() { if (base.Node.NodeType != XmlNodeType.Element) { MoveToStartElement(); } if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DoubleTextWithEndElement) { SkipNodeType(); double result = base.BufferReader.ReadDouble(); ReadTextWithEndElement(); return result; } return base.ReadElementContentAsDouble(); } public override decimal ReadElementContentAsDecimal() { if (base.Node.NodeType != XmlNodeType.Element) { MoveToStartElement(); } if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DecimalTextWithEndElement) { SkipNodeType(); decimal result = base.BufferReader.ReadDecimal(); ReadTextWithEndElement(); return result; } return base.ReadElementContentAsDecimal(); } public override DateTime ReadElementContentAsDateTime() { if (base.Node.NodeType != XmlNodeType.Element) { MoveToStartElement(); } if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.DateTimeTextWithEndElement) { SkipNodeType(); DateTime result = base.BufferReader.ReadDateTime(); ReadTextWithEndElement(); return result; } return base.ReadElementContentAsDateTime(); } public override TimeSpan ReadElementContentAsTimeSpan() { if (base.Node.NodeType != XmlNodeType.Element) { MoveToStartElement(); } if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.TimeSpanTextWithEndElement) { SkipNodeType(); TimeSpan result = base.BufferReader.ReadTimeSpan(); ReadTextWithEndElement(); return result; } return base.ReadElementContentAsTimeSpan(); } public override Guid ReadElementContentAsGuid() { if (base.Node.NodeType != XmlNodeType.Element) { MoveToStartElement(); } if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.GuidTextWithEndElement) { SkipNodeType(); Guid result = base.BufferReader.ReadGuid(); ReadTextWithEndElement(); return result; } return base.ReadElementContentAsGuid(); } public override UniqueId ReadElementContentAsUniqueId() { if (base.Node.NodeType != XmlNodeType.Element) { MoveToStartElement(); } if (CanOptimizeReadElementContent() && GetNodeType() == XmlBinaryNodeType.UniqueIdTextWithEndElement) { SkipNodeType(); UniqueId result = base.BufferReader.ReadUniqueId(); ReadTextWithEndElement(); return result; } return base.ReadElementContentAsUniqueId(); } public override bool TryGetBase64ContentLength(out int length) { length = 0; if (!buffered) { return false; } if (arrayState != 0) { return false; } if (!base.Node.Value.TryGetByteArrayLength(out var length2)) { return false; } int offset = base.BufferReader.Offset; try { bool flag = false; while (!flag && !base.BufferReader.EndOfFile) { XmlBinaryNodeType nodeType = GetNodeType(); SkipNodeType(); int num; switch (nodeType) { case XmlBinaryNodeType.Bytes8TextWithEndElement: num = base.BufferReader.ReadUInt8(); flag = true; break; case XmlBinaryNodeType.Bytes16TextWithEndElement: num = base.BufferReader.ReadUInt16(); flag = true; break; case XmlBinaryNodeType.Bytes32TextWithEndElement: num = base.BufferReader.ReadUInt31(); flag = true; break; case XmlBinaryNodeType.EndElement: num = 0; flag = true; break; case XmlBinaryNodeType.Bytes8Text: num = base.BufferReader.ReadUInt8(); break; case XmlBinaryNodeType.Bytes16Text: num = base.BufferReader.ReadUInt16(); break; case XmlBinaryNodeType.Bytes32Text: num = base.BufferReader.ReadUInt31(); break; default: return false; } base.BufferReader.Advance(num); if (length2 > int.MaxValue - num) { return false; } length2 += num; } length = length2; return true; } finally { base.BufferReader.Offset = offset; } } private void ReadTextWithEndElement() { ExitScope(); ReadNode(); } private XmlAtomicTextNode MoveToAtomicTextWithEndElement() { isTextWithEndElement = true; return MoveToAtomicText(); } public override bool Read() { if (base.Node.ReadState == ReadState.Closed) { return false; } SignNode(); if (isTextWithEndElement) { isTextWithEndElement = false; MoveToEndElement(); return true; } if (arrayState == ArrayState.Content) { if (arrayCount != 0) { MoveToArrayElement(); return true; } arrayState = ArrayState.None; } if (base.Node.ExitScope) { ExitScope(); } return ReadNode(); } private bool ReadNode() { if (!buffered) { base.BufferReader.SetWindow(base.ElementNode.BufferOffset, maxBytesPerRead); } if (base.BufferReader.EndOfFile) { MoveToEndOfFile(); return false; } XmlBinaryNodeType nodeType; if (arrayState == ArrayState.None) { nodeType = GetNodeType(); SkipNodeType(); } else { nodeType = arrayNodeType; arrayCount--; arrayState = ArrayState.Content; } switch (nodeType) { case XmlBinaryNodeType.MinElement: { XmlElementNode xmlElementNode = EnterScope(); xmlElementNode.Prefix.SetValue(PrefixHandleType.Empty); ReadName(xmlElementNode.LocalName); ReadAttributes(); xmlElementNode.Namespace = LookupNamespace(PrefixHandleType.Empty); xmlElementNode.BufferOffset = base.BufferReader.Offset; return true; } case XmlBinaryNodeType.Element: { XmlElementNode xmlElementNode = EnterScope(); ReadName(xmlElementNode.Prefix); ReadName(xmlElementNode.LocalName); ReadAttributes(); xmlElementNode.Namespace = LookupNamespace(xmlElementNode.Prefix); xmlElementNode.BufferOffset = base.BufferReader.Offset; return true; } case XmlBinaryNodeType.ShortDictionaryElement: { XmlElementNode xmlElementNode = EnterScope(); xmlElementNode.Prefix.SetValue(PrefixHandleType.Empty); ReadDictionaryName(xmlElementNode.LocalName); ReadAttributes(); xmlElementNode.Namespace = LookupNamespace(PrefixHandleType.Empty); xmlElementNode.BufferOffset = base.BufferReader.Offset; return true; } case XmlBinaryNodeType.DictionaryElement: { XmlElementNode xmlElementNode = EnterScope(); ReadName(xmlElementNode.Prefix); ReadDictionaryName(xmlElementNode.LocalName); ReadAttributes(); xmlElementNode.Namespace = LookupNamespace(xmlElementNode.Prefix); xmlElementNode.BufferOffset = base.BufferReader.Offset; return true; } case XmlBinaryNodeType.PrefixElementA: case XmlBinaryNodeType.PrefixElementB: case XmlBinaryNodeType.PrefixElementC: case XmlBinaryNodeType.PrefixElementD: case XmlBinaryNodeType.PrefixElementE: case XmlBinaryNodeType.PrefixElementF: case XmlBinaryNodeType.PrefixElementG: case XmlBinaryNodeType.PrefixElementH: case XmlBinaryNodeType.PrefixElementI: case XmlBinaryNodeType.PrefixElementJ: case XmlBinaryNodeType.PrefixElementK: case XmlBinaryNodeType.PrefixElementL: case XmlBinaryNodeType.PrefixElementM: case XmlBinaryNodeType.PrefixElementN: case XmlBinaryNodeType.PrefixElementO: case XmlBinaryNodeType.PrefixElementP: case XmlBinaryNodeType.PrefixElementQ: case XmlBinaryNodeType.PrefixElementR: case XmlBinaryNodeType.PrefixElementS: case XmlBinaryNodeType.PrefixElementT: case XmlBinaryNodeType.PrefixElementU: case XmlBinaryNodeType.PrefixElementV: case XmlBinaryNodeType.PrefixElementW: case XmlBinaryNodeType.PrefixElementX: case XmlBinaryNodeType.PrefixElementY: case XmlBinaryNodeType.PrefixElementZ: { XmlElementNode xmlElementNode = EnterScope(); PrefixHandleType alphaPrefix = PrefixHandle.GetAlphaPrefix((int)(nodeType - 94)); xmlElementNode.Prefix.SetValue(alphaPrefix); ReadName(xmlElementNode.LocalName); ReadAttributes(); xmlElementNode.Namespace = LookupNamespace(alphaPrefix); xmlElementNode.BufferOffset = base.BufferReader.Offset; return true; } case XmlBinaryNodeType.PrefixDictionaryElementA: case XmlBinaryNodeType.PrefixDictionaryElementB: case XmlBinaryNodeType.PrefixDictionaryElementC: case XmlBinaryNodeType.PrefixDictionaryElementD: case XmlBinaryNodeType.PrefixDictionaryElementE: case XmlBinaryNodeType.PrefixDictionaryElementF: case XmlBinaryNodeType.PrefixDictionaryElementG: case XmlBinaryNodeType.PrefixDictionaryElementH: case XmlBinaryNodeType.PrefixDictionaryElementI: case XmlBinaryNodeType.PrefixDictionaryElementJ: case XmlBinaryNodeType.PrefixDictionaryElementK: case XmlBinaryNodeType.PrefixDictionaryElementL: case XmlBinaryNodeType.PrefixDictionaryElementM: case XmlBinaryNodeType.PrefixDictionaryElementN: case XmlBinaryNodeType.PrefixDictionaryElementO: case XmlBinaryNodeType.PrefixDictionaryElementP: case XmlBinaryNodeType.PrefixDictionaryElementQ: case XmlBinaryNodeType.PrefixDictionaryElementR: case XmlBinaryNodeType.PrefixDictionaryElementS: case XmlBinaryNodeType.PrefixDictionaryElementT: case XmlBinaryNodeType.PrefixDictionaryElementU: case XmlBinaryNodeType.PrefixDictionaryElementV: case XmlBinaryNodeType.PrefixDictionaryElementW: case XmlBinaryNodeType.PrefixDictionaryElementX: case XmlBinaryNodeType.PrefixDictionaryElementY: case XmlBinaryNodeType.PrefixDictionaryElementZ: { XmlElementNode xmlElementNode = EnterScope(); PrefixHandleType alphaPrefix = PrefixHandle.GetAlphaPrefix((int)(nodeType - 68)); xmlElementNode.Prefix.SetValue(alphaPrefix); ReadDictionaryName(xmlElementNode.LocalName); ReadAttributes(); xmlElementNode.Namespace = LookupNamespace(alphaPrefix); xmlElementNode.BufferOffset = base.BufferReader.Offset; return true; } case XmlBinaryNodeType.EndElement: MoveToEndElement(); return true; case XmlBinaryNodeType.Comment: ReadName(MoveToComment().Value); return true; case XmlBinaryNodeType.EmptyTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.Empty); if (base.OutsideRootElement) { VerifyWhitespace(); } return true; case XmlBinaryNodeType.ZeroTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.Zero); if (base.OutsideRootElement) { VerifyWhitespace(); } return true; case XmlBinaryNodeType.OneTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.One); if (base.OutsideRootElement) { VerifyWhitespace(); } return true; case XmlBinaryNodeType.TrueTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.True); if (base.OutsideRootElement) { VerifyWhitespace(); } return true; case XmlBinaryNodeType.FalseTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue(ValueHandleType.False); if (base.OutsideRootElement) { VerifyWhitespace(); } return true; case XmlBinaryNodeType.BoolTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetValue((ReadUInt8() != 0) ? ValueHandleType.True : ValueHandleType.False); if (base.OutsideRootElement) { VerifyWhitespace(); } return true; case XmlBinaryNodeType.Chars8TextWithEndElement: if (buffered) { ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt8()); } else { ReadPartialUTF8Text(withEndElement: true, ReadUInt8()); } return true; case XmlBinaryNodeType.Chars8Text: if (buffered) { ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt8()); } else { ReadPartialUTF8Text(withEndElement: false, ReadUInt8()); } return true; case XmlBinaryNodeType.Chars16TextWithEndElement: if (buffered) { ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt16()); } else { ReadPartialUTF8Text(withEndElement: true, ReadUInt16()); } return true; case XmlBinaryNodeType.Chars16Text: if (buffered) { ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt16()); } else { ReadPartialUTF8Text(withEndElement: false, ReadUInt16()); } return true; case XmlBinaryNodeType.Chars32TextWithEndElement: if (buffered) { ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, ReadUInt31()); } else { ReadPartialUTF8Text(withEndElement: true, ReadUInt31()); } return true; case XmlBinaryNodeType.Chars32Text: if (buffered) { ReadText(MoveToComplexText(), ValueHandleType.UTF8, ReadUInt31()); } else { ReadPartialUTF8Text(withEndElement: false, ReadUInt31()); } return true; case XmlBinaryNodeType.UnicodeChars8TextWithEndElement: ReadUnicodeText(withEndElement: true, ReadUInt8()); return true; case XmlBinaryNodeType.UnicodeChars8Text: ReadUnicodeText(withEndElement: false, ReadUInt8()); return true; case XmlBinaryNodeType.UnicodeChars16TextWithEndElement: ReadUnicodeText(withEndElement: true, ReadUInt16()); return true; case XmlBinaryNodeType.UnicodeChars16Text: ReadUnicodeText(withEndElement: false, ReadUInt16()); return true; case XmlBinaryNodeType.UnicodeChars32TextWithEndElement: ReadUnicodeText(withEndElement: true, ReadUInt31()); return true; case XmlBinaryNodeType.UnicodeChars32Text: ReadUnicodeText(withEndElement: false, ReadUInt31()); return true; case XmlBinaryNodeType.Bytes8TextWithEndElement: if (buffered) { ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt8()); } else { ReadPartialBinaryText(withEndElement: true, ReadUInt8()); } return true; case XmlBinaryNodeType.Bytes8Text: if (buffered) { ReadBinaryText(MoveToComplexText(), ReadUInt8()); } else { ReadPartialBinaryText(withEndElement: false, ReadUInt8()); } return true; case XmlBinaryNodeType.Bytes16TextWithEndElement: if (buffered) { ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt16()); } else { ReadPartialBinaryText(withEndElement: true, ReadUInt16()); } return true; case XmlBinaryNodeType.Bytes16Text: if (buffered) { ReadBinaryText(MoveToComplexText(), ReadUInt16()); } else { ReadPartialBinaryText(withEndElement: false, ReadUInt16()); } return true; case XmlBinaryNodeType.Bytes32TextWithEndElement: if (buffered) { ReadBinaryText(MoveToAtomicTextWithEndElement(), ReadUInt31()); } else { ReadPartialBinaryText(withEndElement: true, ReadUInt31()); } return true; case XmlBinaryNodeType.Bytes32Text: if (buffered) { ReadBinaryText(MoveToComplexText(), ReadUInt31()); } else { ReadPartialBinaryText(withEndElement: false, ReadUInt31()); } return true; case XmlBinaryNodeType.DictionaryTextWithEndElement: MoveToAtomicTextWithEndElement().Value.SetDictionaryValue(ReadDictionaryKey()); return true; case XmlBinaryNodeType.UniqueIdTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UniqueId, 16); return true; case XmlBinaryNodeType.GuidTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Guid, 16); return true; case XmlBinaryNodeType.DecimalTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Decimal, 16); return true; case XmlBinaryNodeType.Int8TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int8, 1); return true; case XmlBinaryNodeType.Int16TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int16, 2); return true; case XmlBinaryNodeType.Int32TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int32, 4); return true; case XmlBinaryNodeType.Int64TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Int64, 8); return true; case XmlBinaryNodeType.UInt64TextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UInt64, 8); return true; case XmlBinaryNodeType.FloatTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Single, 4); return true; case XmlBinaryNodeType.DoubleTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Double, 8); return true; case XmlBinaryNodeType.TimeSpanTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.TimeSpan, 8); return true; case XmlBinaryNodeType.DateTimeTextWithEndElement: ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.DateTime, 8); return true; case XmlBinaryNodeType.QNameDictionaryTextWithEndElement: base.BufferReader.ReadQName(MoveToAtomicTextWithEndElement().Value); return true; case XmlBinaryNodeType.Array: ReadArray(); return true; default: base.BufferReader.ReadValue(nodeType, MoveToComplexText().Value); return true; } } private void VerifyWhitespace() { if (!base.Node.Value.IsWhitespace()) { XmlExceptionHelper.ThrowInvalidBinaryFormat(this); } } private void ReadAttributes() { XmlBinaryNodeType nodeType = GetNodeType(); if (nodeType >= XmlBinaryNodeType.MinAttribute && nodeType <= XmlBinaryNodeType.PrefixAttributeZ) { ReadAttributes2(); } } private void ReadAttributes2() { int num = 0; if (buffered) { num = base.BufferReader.Offset; } while (true) { XmlBinaryNodeType nodeType = GetNodeType(); switch (nodeType) { case XmlBinaryNodeType.MinAttribute: { SkipNodeType(); XmlAttributeNode xmlAttributeNode = AddAttribute(); xmlAttributeNode.Prefix.SetValue(PrefixHandleType.Empty); ReadName(xmlAttributeNode.LocalName); ReadAttributeText(xmlAttributeNode.AttributeText); break; } case XmlBinaryNodeType.Attribute: { SkipNodeType(); XmlAttributeNode xmlAttributeNode = AddAttribute(); ReadName(xmlAttributeNode.Prefix); ReadName(xmlAttributeNode.LocalName); ReadAttributeText(xmlAttributeNode.AttributeText); FixXmlAttribute(xmlAttributeNode); break; } case XmlBinaryNodeType.ShortDictionaryAttribute: { SkipNodeType(); XmlAttributeNode xmlAttributeNode = AddAttribute(); xmlAttributeNode.Prefix.SetValue(PrefixHandleType.Empty); ReadDictionaryName(xmlAttributeNode.LocalName); ReadAttributeText(xmlAttributeNode.AttributeText); break; } case XmlBinaryNodeType.DictionaryAttribute: { SkipNodeType(); XmlAttributeNode xmlAttributeNode = AddAttribute(); ReadName(xmlAttributeNode.Prefix); ReadDictionaryName(xmlAttributeNode.LocalName); ReadAttributeText(xmlAttributeNode.AttributeText); break; } case XmlBinaryNodeType.XmlnsAttribute: { SkipNodeType(); Namespace @namespace = AddNamespace(); ReadName(@namespace.Prefix); ReadName(@namespace.Uri); XmlAttributeNode xmlAttributeNode = AddXmlnsAttribute(@namespace); break; } case XmlBinaryNodeType.ShortXmlnsAttribute: { SkipNodeType(); Namespace @namespace = AddNamespace(); @namespace.Prefix.SetValue(PrefixHandleType.Empty); ReadName(@namespace.Uri); XmlAttributeNode xmlAttributeNode = AddXmlnsAttribute(@namespace); break; } case XmlBinaryNodeType.ShortDictionaryXmlnsAttribute: { SkipNodeType(); Namespace @namespace = AddNamespace(); @namespace.Prefix.SetValue(PrefixHandleType.Empty); ReadDictionaryName(@namespace.Uri); XmlAttributeNode xmlAttributeNode = AddXmlnsAttribute(@namespace); break; } case XmlBinaryNodeType.DictionaryXmlnsAttribute: { SkipNodeType(); Namespace @namespace = AddNamespace(); ReadName(@namespace.Prefix); ReadDictionaryName(@namespace.Uri); XmlAttributeNode xmlAttributeNode = AddXmlnsAttribute(@namespace); break; } case XmlBinaryNodeType.PrefixDictionaryAttributeA: case XmlBinaryNodeType.PrefixDictionaryAttributeB: case XmlBinaryNodeType.PrefixDictionaryAttributeC: case XmlBinaryNodeType.PrefixDictionaryAttributeD: case XmlBinaryNodeType.PrefixDictionaryAttributeE: case XmlBinaryNodeType.PrefixDictionaryAttributeF: case XmlBinaryNodeType.PrefixDictionaryAttributeG: case XmlBinaryNodeType.PrefixDictionaryAttributeH: case XmlBinaryNodeType.PrefixDictionaryAttributeI: case XmlBinaryNodeType.PrefixDictionaryAttributeJ: case XmlBinaryNodeType.PrefixDictionaryAttributeK: case XmlBinaryNodeType.PrefixDictionaryAttributeL: case XmlBinaryNodeType.PrefixDictionaryAttributeM: case XmlBinaryNodeType.PrefixDictionaryAttributeN: case XmlBinaryNodeType.PrefixDictionaryAttributeO: case XmlBinaryNodeType.PrefixDictionaryAttributeP: case XmlBinaryNodeType.PrefixDictionaryAttributeQ: case XmlBinaryNodeType.PrefixDictionaryAttributeR: case XmlBinaryNodeType.PrefixDictionaryAttributeS: case XmlBinaryNodeType.PrefixDictionaryAttributeT: case XmlBinaryNodeType.PrefixDictionaryAttributeU: case XmlBinaryNodeType.PrefixDictionaryAttributeV: case XmlBinaryNodeType.PrefixDictionaryAttributeW: case XmlBinaryNodeType.PrefixDictionaryAttributeX: case XmlBinaryNodeType.PrefixDictionaryAttributeY: case XmlBinaryNodeType.PrefixDictionaryAttributeZ: { SkipNodeType(); XmlAttributeNode xmlAttributeNode = AddAttribute(); PrefixHandleType alphaPrefix = PrefixHandle.GetAlphaPrefix((int)(nodeType - 12)); xmlAttributeNode.Prefix.SetValue(alphaPrefix); ReadDictionaryName(xmlAttributeNode.LocalName); ReadAttributeText(xmlAttributeNode.AttributeText); break; } case XmlBinaryNodeType.PrefixAttributeA: case XmlBinaryNodeType.PrefixAttributeB: case XmlBinaryNodeType.PrefixAttributeC: case XmlBinaryNodeType.PrefixAttributeD: case XmlBinaryNodeType.PrefixAttributeE: case XmlBinaryNodeType.PrefixAttributeF: case XmlBinaryNodeType.PrefixAttributeG: case XmlBinaryNodeType.PrefixAttributeH: case XmlBinaryNodeType.PrefixAttributeI: case XmlBinaryNodeType.PrefixAttributeJ: case XmlBinaryNodeType.PrefixAttributeK: case XmlBinaryNodeType.PrefixAttributeL: case XmlBinaryNodeType.PrefixAttributeM: case XmlBinaryNodeType.PrefixAttributeN: case XmlBinaryNodeType.PrefixAttributeO: case XmlBinaryNodeType.PrefixAttributeP: case XmlBinaryNodeType.PrefixAttributeQ: case XmlBinaryNodeType.PrefixAttributeR: case XmlBinaryNodeType.PrefixAttributeS: case XmlBinaryNodeType.PrefixAttributeT: case XmlBinaryNodeType.PrefixAttributeU: case XmlBinaryNodeType.PrefixAttributeV: case XmlBinaryNodeType.PrefixAttributeW: case XmlBinaryNodeType.PrefixAttributeX: case XmlBinaryNodeType.PrefixAttributeY: case XmlBinaryNodeType.PrefixAttributeZ: { SkipNodeType(); XmlAttributeNode xmlAttributeNode = AddAttribute(); PrefixHandleType alphaPrefix = PrefixHandle.GetAlphaPrefix((int)(nodeType - 38)); xmlAttributeNode.Prefix.SetValue(alphaPrefix); ReadName(xmlAttributeNode.LocalName); ReadAttributeText(xmlAttributeNode.AttributeText); break; } default: if (buffered && base.BufferReader.Offset - num > maxBytesPerRead) { XmlExceptionHelper.ThrowMaxBytesPerReadExceeded(this, maxBytesPerRead); } ProcessAttributes(); return; } } } private void ReadText(XmlTextNode textNode, ValueHandleType type, int length) { int offset = base.BufferReader.ReadBytes(length); textNode.Value.SetValue(type, offset, length); if (base.OutsideRootElement) { VerifyWhitespace(); } } private void ReadBinaryText(XmlTextNode textNode, int length) { ReadText(textNode, ValueHandleType.Base64, length); } private void ReadPartialUTF8Text(bool withEndElement, int length) { int num = Math.Max(maxBytesPerRead - 5, 0); if (length <= num) { if (withEndElement) { ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.UTF8, length); } else { ReadText(MoveToComplexText(), ValueHandleType.UTF8, length); } return; } int num2 = Math.Max(num - 5, 0); int num3 = base.BufferReader.ReadBytes(num2); int num4; for (num4 = num3 + num2 - 1; num4 >= num3; num4--) { byte @byte = base.BufferReader.GetByte(num4); if ((@byte & 0x80) == 0 || (@byte & 0xC0) == 192) { break; } } int num5 = num3 + num2 - num4; base.BufferReader.Offset = base.BufferReader.Offset - num5; num2 -= num5; MoveToComplexText().Value.SetValue(ValueHandleType.UTF8, num3, num2); if (base.OutsideRootElement) { VerifyWhitespace(); } XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.Chars32TextWithEndElement : XmlBinaryNodeType.Chars32Text); InsertNode(nodeType, length - num2); } private void ReadUnicodeText(bool withEndElement, int length) { if (((uint)length & (true ? 1u : 0u)) != 0) { XmlExceptionHelper.ThrowInvalidBinaryFormat(this); } if (buffered) { if (withEndElement) { ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Unicode, length); } else { ReadText(MoveToComplexText(), ValueHandleType.Unicode, length); } } else { ReadPartialUnicodeText(withEndElement, length); } } private void ReadPartialUnicodeText(bool withEndElement, int length) { int num = Math.Max(maxBytesPerRead - 5, 0); if (length <= num) { if (withEndElement) { ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Unicode, length); } else { ReadText(MoveToComplexText(), ValueHandleType.Unicode, length); } return; } int num2 = Math.Max(num - 5, 0); if (((uint)num2 & (true ? 1u : 0u)) != 0) { num2--; } int num3 = base.BufferReader.ReadBytes(num2); int num4 = 0; char c = (char)base.BufferReader.GetInt16(num3 + num2 - 2); if (c >= '\ud800' && c < '\udc00') { num4 = 2; } base.BufferReader.Offset = base.BufferReader.Offset - num4; num2 -= num4; MoveToComplexText().Value.SetValue(ValueHandleType.Unicode, num3, num2); if (base.OutsideRootElement) { VerifyWhitespace(); } XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.UnicodeChars32TextWithEndElement : XmlBinaryNodeType.UnicodeChars32Text); InsertNode(nodeType, length - num2); } private void ReadPartialBinaryText(bool withEndElement, int length) { int num = Math.Max(maxBytesPerRead - 5, 0); if (length <= num) { if (withEndElement) { ReadText(MoveToAtomicTextWithEndElement(), ValueHandleType.Base64, length); } else { ReadText(MoveToComplexText(), ValueHandleType.Base64, length); } return; } int num2 = num; if (num2 > 3) { num2 -= num2 % 3; } ReadText(MoveToComplexText(), ValueHandleType.Base64, num2); XmlBinaryNodeType nodeType = (withEndElement ? XmlBinaryNodeType.Bytes32TextWithEndElement : XmlBinaryNodeType.Bytes32Text); InsertNode(nodeType, length - num2); } private void InsertNode(XmlBinaryNodeType nodeType, int length) { byte[] array = new byte[5] { (byte)nodeType, (byte)length, 0, 0, 0 }; length >>= 8; array[2] = (byte)length; length >>= 8; array[3] = (byte)length; length >>= 8; array[4] = (byte)length; base.BufferReader.InsertBytes(array, 0, array.Length); } private void ReadAttributeText(XmlAttributeTextNode textNode) { XmlBinaryNodeType nodeType = GetNodeType(); SkipNodeType(); base.BufferReader.ReadValue(nodeType, textNode.Value); } private void ReadName(ValueHandle value) { int num = ReadMultiByteUInt31(); int offset = base.BufferReader.ReadBytes(num); value.SetValue(ValueHandleType.UTF8, offset, num); } private void ReadName(StringHandle handle) { int num = ReadMultiByteUInt31(); int offset = base.BufferReader.ReadBytes(num); handle.SetValue(offset, num); } private void ReadName(PrefixHandle prefix) { int num = ReadMultiByteUInt31(); int offset = base.BufferReader.ReadBytes(num); prefix.SetValue(offset, num); } private void ReadDictionaryName(StringHandle s) { int num = ReadDictionaryKey(); s.SetValue(num); } private XmlBinaryNodeType GetNodeType() { return base.BufferReader.GetNodeType(); } private void SkipNodeType() { base.BufferReader.SkipNodeType(); } private int ReadDictionaryKey() { return base.BufferReader.ReadDictionaryKey(); } private int ReadMultiByteUInt31() { return base.BufferReader.ReadMultiByteUInt31(); } private int ReadUInt8() { return base.BufferReader.ReadUInt8(); } private int ReadUInt16() { return base.BufferReader.ReadUInt16(); } private int ReadUInt31() { return base.BufferReader.ReadUInt31(); } private bool IsValidArrayType(XmlBinaryNodeType nodeType) { switch (nodeType) { case XmlBinaryNodeType.Int16TextWithEndElement: case XmlBinaryNodeType.Int32TextWithEndElement: case XmlBinaryNodeType.Int64TextWithEndElement: case XmlBinaryNodeType.FloatTextWithEndElement: case XmlBinaryNodeType.DoubleTextWithEndElement: case XmlBinaryNodeType.DecimalTextWithEndElement: case XmlBinaryNodeType.DateTimeTextWithEndElement: case XmlBinaryNodeType.TimeSpanTextWithEndElement: case XmlBinaryNodeType.GuidTextWithEndElement: case XmlBinaryNodeType.BoolTextWithEndElement: return true; default: return false; } } private void ReadArray() { if (GetNodeType() == XmlBinaryNodeType.Array) { XmlExceptionHelper.ThrowInvalidBinaryFormat(this); } ReadNode(); if (base.Node.NodeType != XmlNodeType.Element) { XmlExceptionHelper.ThrowInvalidBinaryFormat(this); } if (GetNodeType() == XmlBinaryNodeType.Array) { XmlExceptionHelper.ThrowInvalidBinaryFormat(this); } ReadNode(); if (base.Node.NodeType != XmlNodeType.EndElement) { XmlExceptionHelper.ThrowInvalidBinaryFormat(this); } arrayState = ArrayState.Element; arrayNodeType = GetNodeType(); if (!IsValidArrayType(arrayNodeType)) { XmlExceptionHelper.ThrowInvalidBinaryFormat(this); } SkipNodeType(); arrayCount = ReadMultiByteUInt31(); if (arrayCount == 0) { XmlExceptionHelper.ThrowInvalidBinaryFormat(this); } MoveToArrayElement(); } private void MoveToArrayElement() { arrayState = ArrayState.Element; MoveToNode(base.ElementNode); } private void SkipArrayElements(int count) { arrayCount -= count; if (arrayCount == 0) { arrayState = ArrayState.None; ExitScope(); ReadNode(); } } public override bool IsStartArray(out Type type) { type = null; if (arrayState != ArrayState.Element) { return false; } switch (arrayNodeType) { case XmlBinaryNodeType.BoolTextWithEndElement: type = typeof(bool); break; case XmlBinaryNodeType.Int16TextWithEndElement: type = typeof(short); break; case XmlBinaryNodeType.Int32TextWithEndElement: type = typeof(int); break; case XmlBinaryNodeType.Int64TextWithEndElement: type = typeof(long); break; case XmlBinaryNodeType.FloatTextWithEndElement: type = typeof(float); break; case XmlBinaryNodeType.DoubleTextWithEndElement: type = typeof(double); break; case XmlBinaryNodeType.DecimalTextWithEndElement: type = typeof(decimal); break; case XmlBinaryNodeType.DateTimeTextWithEndElement: type = typeof(DateTime); break; case XmlBinaryNodeType.GuidTextWithEndElement: type = typeof(Guid); break; case XmlBinaryNodeType.TimeSpanTextWithEndElement: type = typeof(TimeSpan); break; case XmlBinaryNodeType.UniqueIdTextWithEndElement: type = typeof(UniqueId); break; default: return false; } return true; } public override bool TryGetArrayLength(out int count) { count = 0; if (!buffered) { return false; } if (arrayState != ArrayState.Element) { return false; } count = arrayCount; return true; } private bool IsStartArray(string localName, string namespaceUri, XmlBinaryNodeType nodeType) { if (IsStartElement(localName, namespaceUri) && arrayState == ArrayState.Element && arrayNodeType == nodeType) { return !base.Signing; } return false; } private bool IsStartArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, XmlBinaryNodeType nodeType) { if (IsStartElement(localName, namespaceUri) && arrayState == ArrayState.Element && arrayNodeType == nodeType) { return !base.Signing; } return false; } private void CheckArray(Array array, int offset, int count) { if (array == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("array")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > array.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", array.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > array.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", array.Length - offset))); } } [SecuritySafeCritical] private unsafe int ReadArray(bool[] array, int offset, int count) { CheckArray(array, offset, count); int num = Math.Min(count, arrayCount); fixed (bool* ptr = &array[offset]) { base.BufferReader.UnsafeReadArray((byte*)ptr, (byte*)(ptr + num)); } SkipArrayElements(num); return num; } public override int ReadArray(string localName, string namespaceUri, bool[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement)) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement)) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } [SecuritySafeCritical] private unsafe int ReadArray(short[] array, int offset, int count) { CheckArray(array, offset, count); int num = Math.Min(count, arrayCount); fixed (short* ptr = &array[offset]) { base.BufferReader.UnsafeReadArray((byte*)ptr, (byte*)(ptr + num)); } SkipArrayElements(num); return num; } public override int ReadArray(string localName, string namespaceUri, short[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement) && BitConverter.IsLittleEndian) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement) && BitConverter.IsLittleEndian) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } [SecuritySafeCritical] private unsafe int ReadArray(int[] array, int offset, int count) { CheckArray(array, offset, count); int num = Math.Min(count, arrayCount); fixed (int* ptr = &array[offset]) { base.BufferReader.UnsafeReadArray((byte*)ptr, (byte*)(ptr + num)); } SkipArrayElements(num); return num; } public override int ReadArray(string localName, string namespaceUri, int[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement) && BitConverter.IsLittleEndian) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement) && BitConverter.IsLittleEndian) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } [SecuritySafeCritical] private unsafe int ReadArray(long[] array, int offset, int count) { CheckArray(array, offset, count); int num = Math.Min(count, arrayCount); fixed (long* ptr = &array[offset]) { base.BufferReader.UnsafeReadArray((byte*)ptr, (byte*)(ptr + num)); } SkipArrayElements(num); return num; } public override int ReadArray(string localName, string namespaceUri, long[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement) && BitConverter.IsLittleEndian) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement) && BitConverter.IsLittleEndian) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } [SecuritySafeCritical] private unsafe int ReadArray(float[] array, int offset, int count) { CheckArray(array, offset, count); int num = Math.Min(count, arrayCount); fixed (float* ptr = &array[offset]) { base.BufferReader.UnsafeReadArray((byte*)ptr, (byte*)(ptr + num)); } SkipArrayElements(num); return num; } public override int ReadArray(string localName, string namespaceUri, float[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement)) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement)) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } [SecuritySafeCritical] private unsafe int ReadArray(double[] array, int offset, int count) { CheckArray(array, offset, count); int num = Math.Min(count, arrayCount); fixed (double* ptr = &array[offset]) { base.BufferReader.UnsafeReadArray((byte*)ptr, (byte*)(ptr + num)); } SkipArrayElements(num); return num; } public override int ReadArray(string localName, string namespaceUri, double[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement)) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement)) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } [SecuritySafeCritical] private unsafe int ReadArray(decimal[] array, int offset, int count) { CheckArray(array, offset, count); int num = Math.Min(count, arrayCount); fixed (decimal* ptr = &array[offset]) { base.BufferReader.UnsafeReadArray((byte*)ptr, (byte*)(ptr + num)); } SkipArrayElements(num); return num; } public override int ReadArray(string localName, string namespaceUri, decimal[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement)) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement)) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } private int ReadArray(DateTime[] array, int offset, int count) { CheckArray(array, offset, count); int num = Math.Min(count, arrayCount); for (int i = 0; i < num; i++) { array[offset + i] = base.BufferReader.ReadDateTime(); } SkipArrayElements(num); return num; } public override int ReadArray(string localName, string namespaceUri, DateTime[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DateTimeTextWithEndElement)) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.DateTimeTextWithEndElement)) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } private int ReadArray(Guid[] array, int offset, int count) { CheckArray(array, offset, count); int num = Math.Min(count, arrayCount); for (int i = 0; i < num; i++) { array[offset + i] = base.BufferReader.ReadGuid(); } SkipArrayElements(num); return num; } public override int ReadArray(string localName, string namespaceUri, Guid[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.GuidTextWithEndElement)) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.GuidTextWithEndElement)) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } private int ReadArray(TimeSpan[] array, int offset, int count) { CheckArray(array, offset, count); int num = Math.Min(count, arrayCount); for (int i = 0; i < num; i++) { array[offset + i] = base.BufferReader.ReadTimeSpan(); } SkipArrayElements(num); return num; } public override int ReadArray(string localName, string namespaceUri, TimeSpan[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.TimeSpanTextWithEndElement)) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } public override int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) { if (IsStartArray(localName, namespaceUri, XmlBinaryNodeType.TimeSpanTextWithEndElement)) { return ReadArray(array, offset, count); } return base.ReadArray(localName, namespaceUri, array, offset, count); } protected override XmlSigningNodeWriter CreateSigningNodeWriter() { return new XmlSigningNodeWriter(text: false); } } public class XmlBinaryReaderSession : IXmlDictionary { private const int MaxArrayEntries = 2048; private XmlDictionaryString[] strings; private Dictionary stringDict; public XmlDictionaryString Add(int id, string value) { if (id < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(System.Runtime.Serialization.SR.GetString("ID must be >= 0."))); } if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } if (TryLookup(id, out var result)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("ID already defined."))); } result = new XmlDictionaryString(this, value, id); if (id >= 2048) { if (stringDict == null) { stringDict = new Dictionary(); } stringDict.Add(id, result); } else { if (strings == null) { strings = new XmlDictionaryString[Math.Max(id + 1, 16)]; } else if (id >= strings.Length) { XmlDictionaryString[] destinationArray = new XmlDictionaryString[Math.Min(Math.Max(id + 1, strings.Length * 2), 2048)]; Array.Copy(strings, destinationArray, strings.Length); strings = destinationArray; } strings[id] = result; } return result; } public bool TryLookup(int key, out XmlDictionaryString result) { if (strings != null && key >= 0 && key < strings.Length) { result = strings[key]; return result != null; } if (key >= 2048 && stringDict != null) { return stringDict.TryGetValue(key, out result); } result = null; return false; } public bool TryLookup(string value, out XmlDictionaryString result) { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } if (strings != null) { for (int i = 0; i < strings.Length; i++) { XmlDictionaryString xmlDictionaryString = strings[i]; if (xmlDictionaryString != null && xmlDictionaryString.Value == value) { result = xmlDictionaryString; return true; } } } if (stringDict != null) { foreach (XmlDictionaryString value2 in stringDict.Values) { if (value2.Value == value) { result = value2; return true; } } } result = null; return false; } public bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result) { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } if (value.Dictionary != this) { result = null; return false; } result = value; return true; } public void Clear() { if (strings != null) { Array.Clear(strings, 0, strings.Length); } if (stringDict != null) { stringDict.Clear(); } } } public interface IXmlBinaryWriterInitializer { void SetOutput(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream); } internal class XmlBinaryNodeWriter : XmlStreamNodeWriter { private struct AttributeValue { private string captureText; private XmlDictionaryString captureXText; private MemoryStream captureStream; public void Clear() { captureText = null; captureXText = null; captureStream = null; } public void WriteText(string s) { if (captureStream != null) { captureText = XmlConverter.Base64Encoding.GetString(captureStream.GetBuffer(), 0, (int)captureStream.Length); captureStream = null; } if (captureXText != null) { captureText = captureXText.Value; captureXText = null; } if (captureText == null || captureText.Length == 0) { captureText = s; } else { captureText += s; } } public void WriteText(XmlDictionaryString s) { if (captureText != null || captureStream != null) { WriteText(s.Value); } else { captureXText = s; } } public void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count) { if (captureText != null || captureXText != null) { if (trailByteCount > 0) { WriteText(XmlConverter.Base64Encoding.GetString(trailBytes, 0, trailByteCount)); } WriteText(XmlConverter.Base64Encoding.GetString(buffer, offset, count)); return; } if (captureStream == null) { captureStream = new MemoryStream(); } if (trailByteCount > 0) { captureStream.Write(trailBytes, 0, trailByteCount); } captureStream.Write(buffer, offset, count); } public void WriteTo(XmlBinaryNodeWriter writer) { if (captureText != null) { writer.WriteText(captureText); captureText = null; } else if (captureXText != null) { writer.WriteText(captureXText); captureXText = null; } else if (captureStream != null) { writer.WriteBase64Text(null, 0, captureStream.GetBuffer(), 0, (int)captureStream.Length); captureStream = null; } else { writer.WriteEmptyText(); } } } private IXmlDictionary dictionary; private XmlBinaryWriterSession session; private bool inAttribute; private bool inList; private bool wroteAttributeValue; private AttributeValue attributeValue; private const int maxBytesPerChar = 3; private int textNodeOffset; public void SetOutput(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream) { this.dictionary = dictionary; this.session = session; inAttribute = false; inList = false; attributeValue.Clear(); textNodeOffset = -1; SetOutput(stream, ownsStream, null); } private void WriteNode(XmlBinaryNodeType nodeType) { WriteByte((byte)nodeType); textNodeOffset = -1; } private void WroteAttributeValue() { if (wroteAttributeValue && !inList) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("Only a single typed value may be written inside an attribute or content."))); } wroteAttributeValue = true; } private void WriteTextNode(XmlBinaryNodeType nodeType) { if (inAttribute) { WroteAttributeValue(); } WriteByte((byte)nodeType); textNodeOffset = base.BufferOffset - 1; } private byte[] GetTextNodeBuffer(int size, out int offset) { if (inAttribute) { WroteAttributeValue(); } byte[] result = GetBuffer(size, out offset); textNodeOffset = offset; return result; } private void WriteTextNodeWithLength(XmlBinaryNodeType nodeType, int length) { int num; byte[] textNodeBuffer = GetTextNodeBuffer(5, out num); if (length < 256) { textNodeBuffer[num] = (byte)nodeType; textNodeBuffer[num + 1] = (byte)length; Advance(2); } else if (length < 65536) { textNodeBuffer[num] = (byte)(nodeType + 2); textNodeBuffer[num + 1] = (byte)length; length >>= 8; textNodeBuffer[num + 2] = (byte)length; Advance(3); } else { textNodeBuffer[num] = (byte)(nodeType + 4); textNodeBuffer[num + 1] = (byte)length; length >>= 8; textNodeBuffer[num + 2] = (byte)length; length >>= 8; textNodeBuffer[num + 3] = (byte)length; length >>= 8; textNodeBuffer[num + 4] = (byte)length; Advance(5); } } private void WriteTextNodeWithInt64(XmlBinaryNodeType nodeType, long value) { int num; byte[] textNodeBuffer = GetTextNodeBuffer(9, out num); textNodeBuffer[num] = (byte)nodeType; textNodeBuffer[num + 1] = (byte)value; value >>= 8; textNodeBuffer[num + 2] = (byte)value; value >>= 8; textNodeBuffer[num + 3] = (byte)value; value >>= 8; textNodeBuffer[num + 4] = (byte)value; value >>= 8; textNodeBuffer[num + 5] = (byte)value; value >>= 8; textNodeBuffer[num + 6] = (byte)value; value >>= 8; textNodeBuffer[num + 7] = (byte)value; value >>= 8; textNodeBuffer[num + 8] = (byte)value; Advance(9); } public override void WriteDeclaration() { } public override void WriteStartElement(string prefix, string localName) { if (prefix.Length == 0) { WriteNode(XmlBinaryNodeType.MinElement); WriteName(localName); return; } char c = prefix[0]; if (prefix.Length == 1 && c >= 'a' && c <= 'z') { WritePrefixNode(XmlBinaryNodeType.PrefixElementA, c - 97); WriteName(localName); } else { WriteNode(XmlBinaryNodeType.Element); WriteName(prefix); WriteName(localName); } } private void WritePrefixNode(XmlBinaryNodeType nodeType, int ch) { WriteNode(nodeType + ch); } public override void WriteStartElement(string prefix, XmlDictionaryString localName) { if (!TryGetKey(localName, out var key)) { WriteStartElement(prefix, localName.Value); return; } if (prefix.Length == 0) { WriteNode(XmlBinaryNodeType.ShortDictionaryElement); WriteDictionaryString(localName, key); return; } char c = prefix[0]; if (prefix.Length == 1 && c >= 'a' && c <= 'z') { WritePrefixNode(XmlBinaryNodeType.PrefixDictionaryElementA, c - 97); WriteDictionaryString(localName, key); } else { WriteNode(XmlBinaryNodeType.DictionaryElement); WriteName(prefix); WriteDictionaryString(localName, key); } } public override void WriteEndStartElement(bool isEmpty) { if (isEmpty) { WriteEndElement(); } } public override void WriteEndElement(string prefix, string localName) { WriteEndElement(); } private void WriteEndElement() { if (textNodeOffset != -1) { byte[] streamBuffer = base.StreamBuffer; XmlBinaryNodeType xmlBinaryNodeType = (XmlBinaryNodeType)streamBuffer[textNodeOffset]; streamBuffer[textNodeOffset] = (byte)(xmlBinaryNodeType + 1); textNodeOffset = -1; } else { WriteNode(XmlBinaryNodeType.EndElement); } } public override void WriteStartAttribute(string prefix, string localName) { if (prefix.Length == 0) { WriteNode(XmlBinaryNodeType.MinAttribute); WriteName(localName); } else { char c = prefix[0]; if (prefix.Length == 1 && c >= 'a' && c <= 'z') { WritePrefixNode(XmlBinaryNodeType.PrefixAttributeA, c - 97); WriteName(localName); } else { WriteNode(XmlBinaryNodeType.Attribute); WriteName(prefix); WriteName(localName); } } inAttribute = true; wroteAttributeValue = false; } public override void WriteStartAttribute(string prefix, XmlDictionaryString localName) { if (!TryGetKey(localName, out var key)) { WriteStartAttribute(prefix, localName.Value); return; } if (prefix.Length == 0) { WriteNode(XmlBinaryNodeType.ShortDictionaryAttribute); WriteDictionaryString(localName, key); } else { char c = prefix[0]; if (prefix.Length == 1 && c >= 'a' && c <= 'z') { WritePrefixNode(XmlBinaryNodeType.PrefixDictionaryAttributeA, c - 97); WriteDictionaryString(localName, key); } else { WriteNode(XmlBinaryNodeType.DictionaryAttribute); WriteName(prefix); WriteDictionaryString(localName, key); } } inAttribute = true; wroteAttributeValue = false; } public override void WriteEndAttribute() { inAttribute = false; if (!wroteAttributeValue) { attributeValue.WriteTo(this); } textNodeOffset = -1; } public override void WriteXmlnsAttribute(string prefix, string ns) { if (prefix.Length == 0) { WriteNode(XmlBinaryNodeType.ShortXmlnsAttribute); WriteName(ns); } else { WriteNode(XmlBinaryNodeType.XmlnsAttribute); WriteName(prefix); WriteName(ns); } } public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) { if (!TryGetKey(ns, out var key)) { WriteXmlnsAttribute(prefix, ns.Value); } else if (prefix.Length == 0) { WriteNode(XmlBinaryNodeType.ShortDictionaryXmlnsAttribute); WriteDictionaryString(ns, key); } else { WriteNode(XmlBinaryNodeType.DictionaryXmlnsAttribute); WriteName(prefix); WriteDictionaryString(ns, key); } } private bool TryGetKey(XmlDictionaryString s, out int key) { key = -1; if (s.Dictionary == dictionary) { key = s.Key * 2; return true; } if (dictionary != null && dictionary.TryLookup(s, out var result)) { key = result.Key * 2; return true; } if (session == null) { return false; } if (!session.TryLookup(s, out var key2) && !session.TryAdd(s, out key2)) { return false; } key = key2 * 2 + 1; return true; } private void WriteDictionaryString(XmlDictionaryString s, int key) { WriteMultiByteInt32(key); } [SecuritySafeCritical] private unsafe void WriteName(string s) { int length = s.Length; if (length == 0) { WriteByte(0); return; } fixed (char* chars = s) { UnsafeWriteName(chars, length); } } [SecurityCritical] private unsafe void UnsafeWriteName(char* chars, int charCount) { if (charCount < 42) { int num; byte[] array = GetBuffer(1 + charCount * 3, out num); int num2 = UnsafeGetUTF8Chars(chars, charCount, array, num + 1); array[num] = (byte)num2; Advance(1 + num2); } else { int i = UnsafeGetUTF8Length(chars, charCount); WriteMultiByteInt32(i); UnsafeWriteUTF8Chars(chars, charCount); } } private void WriteMultiByteInt32(int i) { int num; byte[] array = GetBuffer(5, out num); int num2 = num; while ((i & 0xFFFFFF80u) != 0L) { array[num++] = (byte)(((uint)i & 0x7Fu) | 0x80u); i >>= 7; } array[num++] = (byte)i; Advance(num - num2); } public override void WriteComment(string value) { WriteNode(XmlBinaryNodeType.Comment); WriteName(value); } public override void WriteCData(string value) { WriteText(value); } private void WriteEmptyText() { WriteTextNode(XmlBinaryNodeType.EmptyText); } public override void WriteBoolText(bool value) { if (value) { WriteTextNode(XmlBinaryNodeType.TrueText); } else { WriteTextNode(XmlBinaryNodeType.FalseText); } } public override void WriteInt32Text(int value) { if (value >= -128 && value < 128) { switch (value) { case 0: WriteTextNode(XmlBinaryNodeType.MinText); return; case 1: WriteTextNode(XmlBinaryNodeType.OneText); return; } int num; byte[] textNodeBuffer = GetTextNodeBuffer(2, out num); textNodeBuffer[num] = 136; textNodeBuffer[num + 1] = (byte)value; Advance(2); } else if (value >= -32768 && value < 32768) { int num2; byte[] textNodeBuffer2 = GetTextNodeBuffer(3, out num2); textNodeBuffer2[num2] = 138; textNodeBuffer2[num2 + 1] = (byte)value; value >>= 8; textNodeBuffer2[num2 + 2] = (byte)value; Advance(3); } else { int num3; byte[] textNodeBuffer3 = GetTextNodeBuffer(5, out num3); textNodeBuffer3[num3] = 140; textNodeBuffer3[num3 + 1] = (byte)value; value >>= 8; textNodeBuffer3[num3 + 2] = (byte)value; value >>= 8; textNodeBuffer3[num3 + 3] = (byte)value; value >>= 8; textNodeBuffer3[num3 + 4] = (byte)value; Advance(5); } } public override void WriteInt64Text(long value) { if (value >= int.MinValue && value <= int.MaxValue) { WriteInt32Text((int)value); } else { WriteTextNodeWithInt64(XmlBinaryNodeType.Int64Text, value); } } public override void WriteUInt64Text(ulong value) { if (value <= long.MaxValue) { WriteInt64Text((long)value); } else { WriteTextNodeWithInt64(XmlBinaryNodeType.UInt64Text, (long)value); } } private void WriteInt64(long value) { int num; byte[] array = GetBuffer(8, out num); array[num] = (byte)value; value >>= 8; array[num + 1] = (byte)value; value >>= 8; array[num + 2] = (byte)value; value >>= 8; array[num + 3] = (byte)value; value >>= 8; array[num + 4] = (byte)value; value >>= 8; array[num + 5] = (byte)value; value >>= 8; array[num + 6] = (byte)value; value >>= 8; array[num + 7] = (byte)value; Advance(8); } public override void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] base64Buffer, int base64Offset, int base64Count) { if (inAttribute) { attributeValue.WriteBase64Text(trailBytes, trailByteCount, base64Buffer, base64Offset, base64Count); return; } int num = trailByteCount + base64Count; if (num > 0) { WriteTextNodeWithLength(XmlBinaryNodeType.Bytes8Text, num); if (trailByteCount > 0) { int num2; byte[] array = GetBuffer(trailByteCount, out num2); for (int i = 0; i < trailByteCount; i++) { array[num2 + i] = trailBytes[i]; } Advance(trailByteCount); } if (base64Count > 0) { WriteBytes(base64Buffer, base64Offset, base64Count); } } else { WriteEmptyText(); } } public override void WriteText(XmlDictionaryString value) { if (inAttribute) { attributeValue.WriteText(value); return; } if (!TryGetKey(value, out var key)) { WriteText(value.Value); return; } WriteTextNode(XmlBinaryNodeType.DictionaryText); WriteDictionaryString(value, key); } [SecuritySafeCritical] public unsafe override void WriteText(string value) { if (inAttribute) { attributeValue.WriteText(value); } else if (value.Length > 0) { fixed (char* chars = value) { UnsafeWriteText(chars, value.Length); } } else { WriteEmptyText(); } } [SecuritySafeCritical] public unsafe override void WriteText(char[] chars, int offset, int count) { if (inAttribute) { attributeValue.WriteText(new string(chars, offset, count)); } else if (count > 0) { fixed (char* chars2 = &chars[offset]) { UnsafeWriteText(chars2, count); } } else { WriteEmptyText(); } } public override void WriteText(byte[] chars, int charOffset, int charCount) { WriteTextNodeWithLength(XmlBinaryNodeType.Chars8Text, charCount); WriteBytes(chars, charOffset, charCount); } [SecurityCritical] private unsafe void UnsafeWriteText(char* chars, int charCount) { if (charCount == 1) { switch (*chars) { case '0': WriteTextNode(XmlBinaryNodeType.MinText); return; case '1': WriteTextNode(XmlBinaryNodeType.OneText); return; } } if (charCount <= 85) { int num; byte[] array = GetBuffer(2 + charCount * 3, out num); int num2 = UnsafeGetUTF8Chars(chars, charCount, array, num + 2); if (num2 / 2 <= charCount) { array[num] = 152; } else { array[num] = 182; num2 = UnsafeGetUnicodeChars(chars, charCount, array, num + 2); } textNodeOffset = num; array[num + 1] = (byte)num2; Advance(2 + num2); } else { int num3 = UnsafeGetUTF8Length(chars, charCount); if (num3 / 2 > charCount) { WriteTextNodeWithLength(XmlBinaryNodeType.UnicodeChars8Text, charCount * 2); UnsafeWriteUnicodeChars(chars, charCount); } else { WriteTextNodeWithLength(XmlBinaryNodeType.Chars8Text, num3); UnsafeWriteUTF8Chars(chars, charCount); } } } public override void WriteEscapedText(string value) { WriteText(value); } public override void WriteEscapedText(XmlDictionaryString value) { WriteText(value); } public override void WriteEscapedText(char[] chars, int offset, int count) { WriteText(chars, offset, count); } public override void WriteEscapedText(byte[] chars, int offset, int count) { WriteText(chars, offset, count); } public override void WriteCharEntity(int ch) { if (ch > 65535) { SurrogateChar surrogateChar = new SurrogateChar(ch); char[] chars = new char[2] { surrogateChar.HighChar, surrogateChar.LowChar }; WriteText(chars, 0, 2); } else { char[] chars2 = new char[1] { (char)ch }; WriteText(chars2, 0, 1); } } [SecuritySafeCritical] public unsafe override void WriteFloatText(float f) { long value; if (f >= -9.223372E+18f && f <= 9.223372E+18f && (float)(value = (long)f) == f) { WriteInt64Text(value); return; } int num; byte[] textNodeBuffer = GetTextNodeBuffer(5, out num); byte* ptr = (byte*)(&f); textNodeBuffer[num] = 144; textNodeBuffer[num + 1] = *ptr; textNodeBuffer[num + 2] = ptr[1]; textNodeBuffer[num + 3] = ptr[2]; textNodeBuffer[num + 4] = ptr[3]; Advance(5); } [SecuritySafeCritical] public unsafe override void WriteDoubleText(double d) { float value; if (d >= -3.4028234663852886E+38 && d <= 3.4028234663852886E+38 && (double)(value = (float)d) == d) { WriteFloatText(value); return; } int num; byte[] textNodeBuffer = GetTextNodeBuffer(9, out num); byte* ptr = (byte*)(&d); textNodeBuffer[num] = 146; textNodeBuffer[num + 1] = *ptr; textNodeBuffer[num + 2] = ptr[1]; textNodeBuffer[num + 3] = ptr[2]; textNodeBuffer[num + 4] = ptr[3]; textNodeBuffer[num + 5] = ptr[4]; textNodeBuffer[num + 6] = ptr[5]; textNodeBuffer[num + 7] = ptr[6]; textNodeBuffer[num + 8] = ptr[7]; Advance(9); } [SecuritySafeCritical] public unsafe override void WriteDecimalText(decimal d) { int num; byte[] textNodeBuffer = GetTextNodeBuffer(17, out num); byte* ptr = (byte*)(&d); textNodeBuffer[num++] = 148; for (int i = 0; i < 16; i++) { textNodeBuffer[num++] = ptr[i]; } Advance(17); } public override void WriteDateTimeText(DateTime dt) { WriteTextNodeWithInt64(XmlBinaryNodeType.DateTimeText, dt.ToBinary()); } public override void WriteUniqueIdText(UniqueId value) { if (value.IsGuid) { int num; byte[] textNodeBuffer = GetTextNodeBuffer(17, out num); textNodeBuffer[num] = 172; value.TryGetGuid(textNodeBuffer, num + 1); Advance(17); } else { WriteText(value.ToString()); } } public override void WriteGuidText(Guid guid) { int num; byte[] textNodeBuffer = GetTextNodeBuffer(17, out num); textNodeBuffer[num] = 176; Buffer.BlockCopy(guid.ToByteArray(), 0, textNodeBuffer, num + 1, 16); Advance(17); } public override void WriteTimeSpanText(TimeSpan value) { WriteTextNodeWithInt64(XmlBinaryNodeType.TimeSpanText, value.Ticks); } public override void WriteStartListText() { inList = true; WriteNode(XmlBinaryNodeType.StartListText); } public override void WriteListSeparator() { } public override void WriteEndListText() { inList = false; wroteAttributeValue = true; WriteNode(XmlBinaryNodeType.EndListText); } public void WriteArrayNode() { WriteNode(XmlBinaryNodeType.Array); } private void WriteArrayInfo(XmlBinaryNodeType nodeType, int count) { WriteNode(nodeType); WriteMultiByteInt32(count); } [SecurityCritical] public unsafe void UnsafeWriteArray(XmlBinaryNodeType nodeType, int count, byte* array, byte* arrayMax) { WriteArrayInfo(nodeType, count); UnsafeWriteArray(array, (int)(arrayMax - array)); } [SecurityCritical] private unsafe void UnsafeWriteArray(byte* array, int byteCount) { UnsafeWriteBytes(array, byteCount); } public void WriteDateTimeArray(DateTime[] array, int offset, int count) { WriteArrayInfo(XmlBinaryNodeType.DateTimeTextWithEndElement, count); for (int i = 0; i < count; i++) { WriteInt64(array[offset + i].ToBinary()); } } public void WriteGuidArray(Guid[] array, int offset, int count) { WriteArrayInfo(XmlBinaryNodeType.GuidTextWithEndElement, count); for (int i = 0; i < count; i++) { byte[] byteBuffer = array[offset + i].ToByteArray(); WriteBytes(byteBuffer, 0, 16); } } public void WriteTimeSpanArray(TimeSpan[] array, int offset, int count) { WriteArrayInfo(XmlBinaryNodeType.TimeSpanTextWithEndElement, count); for (int i = 0; i < count; i++) { WriteInt64(array[offset + i].Ticks); } } public override void WriteQualifiedName(string prefix, XmlDictionaryString localName) { if (prefix.Length == 0) { WriteText(localName); return; } char c = prefix[0]; if (prefix.Length == 1 && c >= 'a' && c <= 'z' && TryGetKey(localName, out var key)) { WriteTextNode(XmlBinaryNodeType.QNameDictionaryText); WriteByte((byte)(c - 97)); WriteDictionaryString(localName, key); } else { WriteText(prefix); WriteText(":"); WriteText(localName); } } protected override void FlushBuffer() { base.FlushBuffer(); textNodeOffset = -1; } public override void Close() { base.Close(); attributeValue.Clear(); } } internal class XmlBinaryWriter : XmlBaseWriter, IXmlBinaryWriterInitializer { private XmlBinaryNodeWriter writer; private char[] chars; private byte[] bytes; public void SetOutput(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream) { if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("stream")); } if (writer == null) { writer = new XmlBinaryNodeWriter(); } writer.SetOutput(stream, dictionary, session, ownsStream); SetOutput(writer); } protected override XmlSigningNodeWriter CreateSigningNodeWriter() { return new XmlSigningNodeWriter(text: false); } protected override void WriteTextNode(XmlDictionaryReader reader, bool attribute) { Type valueType = reader.ValueType; if (valueType == typeof(string)) { if (reader.TryGetValueAsDictionaryString(out var value)) { WriteString(value); } else if (reader.CanReadValueChunk) { if (chars == null) { chars = new char[256]; } int count; while ((count = reader.ReadValueChunk(chars, 0, chars.Length)) > 0) { WriteChars(chars, 0, count); } } else { WriteString(reader.Value); } if (!attribute) { reader.Read(); } } else if (valueType == typeof(byte[])) { if (reader.CanReadBinaryContent) { if (bytes == null) { bytes = new byte[384]; } int count2; while ((count2 = reader.ReadValueAsBase64(bytes, 0, bytes.Length)) > 0) { WriteBase64(bytes, 0, count2); } } else { WriteString(reader.Value); } if (!attribute) { reader.Read(); } } else if (valueType == typeof(int)) { WriteValue(reader.ReadContentAsInt()); } else if (valueType == typeof(long)) { WriteValue(reader.ReadContentAsLong()); } else if (valueType == typeof(bool)) { WriteValue(reader.ReadContentAsBoolean()); } else if (valueType == typeof(double)) { WriteValue(reader.ReadContentAsDouble()); } else if (valueType == typeof(DateTime)) { WriteValue(reader.ReadContentAsDateTime()); } else if (valueType == typeof(float)) { WriteValue(reader.ReadContentAsFloat()); } else if (valueType == typeof(decimal)) { WriteValue(reader.ReadContentAsDecimal()); } else if (valueType == typeof(UniqueId)) { WriteValue(reader.ReadContentAsUniqueId()); } else if (valueType == typeof(Guid)) { WriteValue(reader.ReadContentAsGuid()); } else if (valueType == typeof(TimeSpan)) { WriteValue(reader.ReadContentAsTimeSpan()); } else { WriteValue(reader.ReadContentAsObject()); } } private void WriteStartArray(string prefix, string localName, string namespaceUri, int count) { StartArray(count); writer.WriteArrayNode(); WriteStartElement(prefix, localName, namespaceUri); WriteEndElement(); } private void WriteStartArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int count) { StartArray(count); writer.WriteArrayNode(); WriteStartElement(prefix, localName, namespaceUri); WriteEndElement(); } private void WriteEndArray() { EndArray(); } [SecurityCritical] private unsafe void UnsafeWriteArray(string prefix, string localName, string namespaceUri, XmlBinaryNodeType nodeType, int count, byte* array, byte* arrayMax) { WriteStartArray(prefix, localName, namespaceUri, count); writer.UnsafeWriteArray(nodeType, count, array, arrayMax); WriteEndArray(); } [SecurityCritical] private unsafe void UnsafeWriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, XmlBinaryNodeType nodeType, int count, byte* array, byte* arrayMax) { WriteStartArray(prefix, localName, namespaceUri, count); writer.UnsafeWriteArray(nodeType, count, array, arrayMax); WriteEndArray(); } private void CheckArray(Array array, int offset, int count) { if (array == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("array")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > array.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", array.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > array.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", array.Length - offset))); } } [SecuritySafeCritical] public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { fixed (bool* ptr = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement, count, (byte*)ptr, (byte*)(ptr + count)); } } } [SecuritySafeCritical] public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { fixed (bool* ptr = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.BoolTextWithEndElement, count, (byte*)ptr, (byte*)(ptr + count)); } } } [SecuritySafeCritical] public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, short[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { fixed (short* ptr = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement, count, (byte*)ptr, (byte*)(ptr + count)); } } } [SecuritySafeCritical] public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { fixed (short* ptr = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.Int16TextWithEndElement, count, (byte*)ptr, (byte*)(ptr + count)); } } } [SecuritySafeCritical] public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, int[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { fixed (int* ptr = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement, count, (byte*)ptr, (byte*)(ptr + count)); } } } [SecuritySafeCritical] public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { fixed (int* ptr = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.Int32TextWithEndElement, count, (byte*)ptr, (byte*)(ptr + count)); } } } [SecuritySafeCritical] public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, long[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { fixed (long* ptr = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement, count, (byte*)ptr, (byte*)(ptr + count)); } } } [SecuritySafeCritical] public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { fixed (long* ptr = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.Int64TextWithEndElement, count, (byte*)ptr, (byte*)(ptr + count)); } } } [SecuritySafeCritical] public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { fixed (float* ptr = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement, count, (byte*)ptr, (byte*)(ptr + count)); } } } [SecuritySafeCritical] public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { fixed (float* ptr = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.FloatTextWithEndElement, count, (byte*)ptr, (byte*)(ptr + count)); } } } [SecuritySafeCritical] public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { fixed (double* ptr = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement, count, (byte*)ptr, (byte*)(ptr + count)); } } } [SecuritySafeCritical] public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { fixed (double* ptr = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.DoubleTextWithEndElement, count, (byte*)ptr, (byte*)(ptr + count)); } } } [SecuritySafeCritical] public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { fixed (decimal* ptr = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement, count, (byte*)ptr, (byte*)(ptr + count)); } } } [SecuritySafeCritical] public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { fixed (decimal* ptr = &array[offset]) { UnsafeWriteArray(prefix, localName, namespaceUri, XmlBinaryNodeType.DecimalTextWithEndElement, count, (byte*)ptr, (byte*)(ptr + count)); } } } public override void WriteArray(string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { WriteStartArray(prefix, localName, namespaceUri, count); writer.WriteDateTimeArray(array, offset, count); WriteEndArray(); } } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { WriteStartArray(prefix, localName, namespaceUri, count); writer.WriteDateTimeArray(array, offset, count); WriteEndArray(); } } public override void WriteArray(string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { WriteStartArray(prefix, localName, namespaceUri, count); writer.WriteGuidArray(array, offset, count); WriteEndArray(); } } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { WriteStartArray(prefix, localName, namespaceUri, count); writer.WriteGuidArray(array, offset, count); WriteEndArray(); } } public override void WriteArray(string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { WriteStartArray(prefix, localName, namespaceUri, count); writer.WriteTimeSpanArray(array, offset, count); WriteEndArray(); } } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) { if (base.Signing) { base.WriteArray(prefix, localName, namespaceUri, array, offset, count); return; } CheckArray(array, offset, count); if (count > 0) { WriteStartArray(prefix, localName, namespaceUri, count); writer.WriteTimeSpanArray(array, offset, count); WriteEndArray(); } } } public class XmlBinaryWriterSession { private class PriorityDictionary where K : class { private struct Entry { public K Key; public V Value; public int Time; } private Dictionary dictionary; private Entry[] list; private int listCount; private int now; private int Now { get { if (++now == int.MaxValue) { DecreaseAll(); } return now; } } public PriorityDictionary() { list = new Entry[16]; } public void Clear() { now = 0; listCount = 0; Array.Clear(list, 0, list.Length); if (dictionary != null) { dictionary.Clear(); } } public bool TryGetValue(K key, out V value) { for (int i = 0; i < listCount; i++) { if (list[i].Key == key) { value = list[i].Value; list[i].Time = Now; return true; } } for (int j = 0; j < listCount; j++) { if (list[j].Key.Equals(key)) { value = list[j].Value; list[j].Time = Now; return true; } } if (dictionary == null) { value = default(V); return false; } if (!dictionary.TryGetValue(key, out value)) { return false; } int num = 0; int time = list[0].Time; for (int k = 1; k < listCount; k++) { if (list[k].Time < time) { num = k; time = list[k].Time; } } list[num].Key = key; list[num].Value = value; list[num].Time = Now; return true; } public void Add(K key, V value) { if (listCount < list.Length) { list[listCount].Key = key; list[listCount].Value = value; listCount++; return; } if (dictionary == null) { dictionary = new Dictionary(); for (int i = 0; i < listCount; i++) { dictionary.Add(list[i].Key, list[i].Value); } } dictionary.Add(key, value); } private void DecreaseAll() { for (int i = 0; i < listCount; i++) { list[i].Time /= 2; } now /= 2; } } private class IntArray { private int[] array; public int this[int index] { get { if (index >= array.Length) { return 0; } return array[index]; } set { if (index >= array.Length) { int[] destinationArray = new int[Math.Max(index + 1, array.Length * 2)]; Array.Copy(array, destinationArray, array.Length); array = destinationArray; } array[index] = value; } } public IntArray(int size) { array = new int[size]; } } private PriorityDictionary strings; private PriorityDictionary maps; private int nextKey; public XmlBinaryWriterSession() { nextKey = 0; maps = new PriorityDictionary(); strings = new PriorityDictionary(); } public virtual bool TryAdd(XmlDictionaryString value, out int key) { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } if (maps.TryGetValue(value.Dictionary, out var value2)) { key = value2[value.Key] - 1; if (key != -1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("The specified key already exists in the dictionary."))); } key = Add(value.Value); value2[value.Key] = key + 1; return true; } key = Add(value.Value); value2 = AddKeys(value.Dictionary, value.Key + 1); value2[value.Key] = key + 1; return true; } private int Add(string s) { int num = nextKey++; strings.Add(s, num); return num; } private IntArray AddKeys(IXmlDictionary dictionary, int minCount) { IntArray intArray = new IntArray(Math.Max(minCount, 16)); maps.Add(dictionary, intArray); return intArray; } public void Reset() { nextKey = 0; maps.Clear(); strings.Clear(); } internal bool TryLookup(XmlDictionaryString s, out int key) { if (maps.TryGetValue(s.Dictionary, out var value)) { key = value[s.Key] - 1; if (key != -1) { return true; } } if (strings.TryGetValue(s.Value, out key)) { if (value == null) { value = AddKeys(s.Dictionary, s.Key + 1); } value[s.Key] = key + 1; return true; } key = -1; return false; } } internal class XmlBufferReader { private XmlDictionaryReader reader; private Stream stream; private byte[] streamBuffer; private byte[] buffer; private int offsetMin; private int offsetMax; private IXmlDictionary dictionary; private XmlBinaryReaderSession session; private byte[] guid; private int offset; private const int maxBytesPerChar = 3; private char[] chars; private int windowOffset; private int windowOffsetMax; private ValueHandle listValue; private static byte[] emptyByteArray = new byte[0]; private static XmlBufferReader empty = new XmlBufferReader(emptyByteArray); public static XmlBufferReader Empty => empty; public byte[] Buffer => buffer; public bool IsStreamed => stream != null; public bool EndOfFile { get { if (offset == offsetMax) { return !TryEnsureByte(); } return false; } } public int Offset { get { return offset; } set { offset = value; } } public XmlBufferReader(XmlDictionaryReader reader) { this.reader = reader; } public XmlBufferReader(byte[] buffer) { reader = null; this.buffer = buffer; } public void SetBuffer(Stream stream, IXmlDictionary dictionary, XmlBinaryReaderSession session) { if (streamBuffer == null) { streamBuffer = new byte[128]; } SetBuffer(stream, streamBuffer, 0, 0, dictionary, session); windowOffset = 0; windowOffsetMax = streamBuffer.Length; } public void SetBuffer(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlBinaryReaderSession session) { SetBuffer(null, buffer, offset, count, dictionary, session); } private void SetBuffer(Stream stream, byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlBinaryReaderSession session) { this.stream = stream; this.buffer = buffer; offsetMin = offset; this.offset = offset; offsetMax = offset + count; this.dictionary = dictionary; this.session = session; } public void Close() { if (streamBuffer != null && streamBuffer.Length > 4096) { streamBuffer = null; } if (stream != null) { stream.Close(); stream = null; } buffer = emptyByteArray; offset = 0; offsetMax = 0; windowOffset = 0; windowOffsetMax = 0; dictionary = null; session = null; } public byte GetByte() { int num = offset; if (num < offsetMax) { return buffer[num]; } return GetByteHard(); } public void SkipByte() { Advance(1); } private byte GetByteHard() { EnsureByte(); return buffer[offset]; } public byte[] GetBuffer(int count, out int offset) { offset = this.offset; if (offset <= offsetMax - count) { return buffer; } return GetBufferHard(count, out offset); } public byte[] GetBuffer(int count, out int offset, out int offsetMax) { offset = this.offset; if (offset <= this.offsetMax - count) { offsetMax = this.offset + count; } else { TryEnsureBytes(Math.Min(count, windowOffsetMax - offset)); offsetMax = this.offsetMax; } return buffer; } public byte[] GetBuffer(out int offset, out int offsetMax) { offset = this.offset; offsetMax = this.offsetMax; return buffer; } private byte[] GetBufferHard(int count, out int offset) { offset = this.offset; EnsureBytes(count); return buffer; } private void EnsureByte() { if (!TryEnsureByte()) { XmlExceptionHelper.ThrowUnexpectedEndOfFile(reader); } } private bool TryEnsureByte() { if (stream == null) { return false; } if (offsetMax >= windowOffsetMax) { XmlExceptionHelper.ThrowMaxBytesPerReadExceeded(reader, windowOffsetMax - windowOffset); } if (offsetMax >= buffer.Length) { return TryEnsureBytes(1); } int num = stream.ReadByte(); if (num == -1) { return false; } buffer[offsetMax++] = (byte)num; return true; } private void EnsureBytes(int count) { if (!TryEnsureBytes(count)) { XmlExceptionHelper.ThrowUnexpectedEndOfFile(reader); } } private bool TryEnsureBytes(int count) { if (stream == null) { return false; } if (offset > int.MaxValue - count) { XmlExceptionHelper.ThrowMaxBytesPerReadExceeded(reader, windowOffsetMax - windowOffset); } int num = offset + count; if (num < offsetMax) { return true; } if (num > windowOffsetMax) { XmlExceptionHelper.ThrowMaxBytesPerReadExceeded(reader, windowOffsetMax - windowOffset); } if (num > buffer.Length) { byte[] dst = new byte[Math.Max(num, buffer.Length * 2)]; System.Buffer.BlockCopy(buffer, 0, dst, 0, offsetMax); buffer = dst; streamBuffer = dst; } int num2 = num - offsetMax; while (num2 > 0) { int num3 = stream.Read(buffer, offsetMax, num2); if (num3 == 0) { return false; } offsetMax += num3; num2 -= num3; } return true; } public void Advance(int count) { offset += count; } public void InsertBytes(byte[] buffer, int offset, int count) { if (offsetMax > buffer.Length - count) { byte[] dst = new byte[offsetMax + count]; System.Buffer.BlockCopy(this.buffer, 0, dst, 0, offsetMax); this.buffer = dst; streamBuffer = dst; } System.Buffer.BlockCopy(this.buffer, this.offset, this.buffer, this.offset + count, offsetMax - this.offset); offsetMax += count; System.Buffer.BlockCopy(buffer, offset, this.buffer, this.offset, count); } public void SetWindow(int windowOffset, int windowLength) { if (windowOffset > int.MaxValue - windowLength) { windowLength = int.MaxValue - windowOffset; } if (offset != windowOffset) { System.Buffer.BlockCopy(buffer, offset, buffer, windowOffset, offsetMax - offset); offsetMax = windowOffset + (offsetMax - offset); offset = windowOffset; } this.windowOffset = windowOffset; windowOffsetMax = Math.Max(windowOffset + windowLength, offsetMax); } public int ReadBytes(int count) { int num = offset; if (num > offsetMax - count) { EnsureBytes(count); } offset += count; return num; } public int ReadMultiByteUInt31() { int @byte = GetByte(); Advance(1); if ((@byte & 0x80) == 0) { return @byte; } @byte &= 0x7F; int byte2 = GetByte(); Advance(1); @byte |= (byte2 & 0x7F) << 7; if ((byte2 & 0x80) == 0) { return @byte; } int byte3 = GetByte(); Advance(1); @byte |= (byte3 & 0x7F) << 14; if ((byte3 & 0x80) == 0) { return @byte; } int byte4 = GetByte(); Advance(1); @byte |= (byte4 & 0x7F) << 21; if ((byte4 & 0x80) == 0) { return @byte; } int byte5 = GetByte(); Advance(1); @byte |= byte5 << 28; if (((uint)byte5 & 0xF8u) != 0) { XmlExceptionHelper.ThrowInvalidBinaryFormat(reader); } return @byte; } public int ReadUInt8() { byte @byte = GetByte(); Advance(1); return @byte; } public int ReadInt8() { return (sbyte)ReadUInt8(); } public int ReadUInt16() { int num; byte[] array = GetBuffer(2, out num); int result = array[num] + (array[num + 1] << 8); Advance(2); return result; } public int ReadInt16() { return (short)ReadUInt16(); } public int ReadInt32() { int num; byte[] array = GetBuffer(4, out num); byte b = array[num]; byte b2 = array[num + 1]; byte b3 = array[num + 2]; byte num2 = array[num + 3]; Advance(4); return (((num2 << 8) + b3 << 8) + b2 << 8) + b; } public int ReadUInt31() { int num = ReadInt32(); if (num < 0) { XmlExceptionHelper.ThrowInvalidBinaryFormat(reader); } return num; } public long ReadInt64() { long num = (uint)ReadInt32(); return (long)((ulong)(uint)ReadInt32() << 32) + num; } [SecuritySafeCritical] public unsafe float ReadSingle() { int num; byte[] array = GetBuffer(4, out num); float result = default(float); byte* ptr = (byte*)(&result); *ptr = array[num]; ptr[1] = array[num + 1]; ptr[2] = array[num + 2]; ptr[3] = array[num + 3]; Advance(4); return result; } [SecuritySafeCritical] public unsafe double ReadDouble() { int num; byte[] array = GetBuffer(8, out num); double result = default(double); byte* ptr = (byte*)(&result); *ptr = array[num]; ptr[1] = array[num + 1]; ptr[2] = array[num + 2]; ptr[3] = array[num + 3]; ptr[4] = array[num + 4]; ptr[5] = array[num + 5]; ptr[6] = array[num + 6]; ptr[7] = array[num + 7]; Advance(8); return result; } [SecuritySafeCritical] public unsafe decimal ReadDecimal() { int num; byte[] array = GetBuffer(16, out num); byte b = array[num]; byte b2 = array[num + 1]; byte b3 = array[num + 2]; int num2 = (((array[num + 3] << 8) + b3 << 8) + b2 << 8) + b; if ((num2 & 0x7F00FFFF) == 0 && (num2 & 0xFF0000) <= 1835008) { decimal result = default(decimal); byte* ptr = (byte*)(&result); for (int i = 0; i < 16; i++) { ptr[i] = array[num + i]; } Advance(16); return result; } XmlExceptionHelper.ThrowInvalidBinaryFormat(reader); return 0m; } public UniqueId ReadUniqueId() { int num; UniqueId result = new UniqueId(GetBuffer(16, out num), num); Advance(16); return result; } public DateTime ReadDateTime() { long dateData = 0L; try { dateData = ReadInt64(); return DateTime.FromBinary(dateData); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(dateData.ToString(CultureInfo.InvariantCulture), "DateTime", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(dateData.ToString(CultureInfo.InvariantCulture), "DateTime", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(dateData.ToString(CultureInfo.InvariantCulture), "DateTime", exception3)); } } public TimeSpan ReadTimeSpan() { long value = 0L; try { value = ReadInt64(); return TimeSpan.FromTicks(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value.ToString(CultureInfo.InvariantCulture), "TimeSpan", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value.ToString(CultureInfo.InvariantCulture), "TimeSpan", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value.ToString(CultureInfo.InvariantCulture), "TimeSpan", exception3)); } } public Guid ReadGuid() { GetBuffer(16, out var num); Guid result = GetGuid(num); Advance(16); return result; } public string ReadUTF8String(int length) { GetBuffer(length, out var num); char[] charBuffer = GetCharBuffer(length); int length2 = GetChars(num, length, charBuffer); string result = new string(charBuffer, 0, length2); Advance(length); return result; } [SecurityCritical] public unsafe void UnsafeReadArray(byte* dst, byte* dstMax) { UnsafeReadArray(dst, (int)(dstMax - dst)); } [SecurityCritical] private unsafe void UnsafeReadArray(byte* dst, int length) { if (stream != null) { while (length >= 256) { byte[] array = GetBuffer(256, out offset); for (int i = 0; i < 256; i++) { *(dst++) = array[offset + i]; } Advance(256); length -= 256; } } if (length <= 0) { return; } fixed (byte* ptr = &GetBuffer(length, out offset)[offset]) { byte* ptr2 = ptr; byte* ptr3 = dst + length; while (dst < ptr3) { *dst = *ptr2; dst++; ptr2++; } } Advance(length); } private char[] GetCharBuffer(int count) { if (count > 1024) { return new char[count]; } if (chars == null || chars.Length < count) { chars = new char[count]; } return chars; } private int GetChars(int offset, int length, char[] chars) { byte[] array = buffer; for (int i = 0; i < length; i++) { byte b = array[offset + i]; if (b >= 128) { return i + XmlConverter.ToChars(array, offset + i, length - i, chars, i); } chars[i] = (char)b; } return length; } private int GetChars(int offset, int length, char[] chars, int charOffset) { byte[] array = buffer; for (int i = 0; i < length; i++) { byte b = array[offset + i]; if (b >= 128) { return i + XmlConverter.ToChars(array, offset + i, length - i, chars, charOffset + i); } chars[charOffset + i] = (char)b; } return length; } public string GetString(int offset, int length) { char[] charBuffer = GetCharBuffer(length); int length2 = GetChars(offset, length, charBuffer); return new string(charBuffer, 0, length2); } public string GetUnicodeString(int offset, int length) { return XmlConverter.ToStringUnicode(buffer, offset, length); } public string GetString(int offset, int length, XmlNameTable nameTable) { char[] charBuffer = GetCharBuffer(length); int length2 = GetChars(offset, length, charBuffer); return nameTable.Add(charBuffer, 0, length2); } public int GetEscapedChars(int offset, int length, char[] chars) { byte[] array = buffer; int num = 0; int num2 = offset; int num3 = offset + length; while (true) { if (offset < num3 && IsAttrChar(array[offset])) { offset++; continue; } num += GetChars(num2, offset - num2, chars, num); if (offset == num3) { break; } num2 = offset; if (array[offset] == 38) { while (offset < num3 && array[offset] != 59) { offset++; } offset++; int charEntity = GetCharEntity(num2, offset - num2); num2 = offset; if (charEntity > 65535) { SurrogateChar surrogateChar = new SurrogateChar(charEntity); chars[num++] = surrogateChar.HighChar; chars[num++] = surrogateChar.LowChar; } else { chars[num++] = (char)charEntity; } } else if (array[offset] == 10 || array[offset] == 9) { chars[num++] = ' '; offset++; num2 = offset; } else { chars[num++] = ' '; offset++; if (offset < num3 && array[offset] == 10) { offset++; } num2 = offset; } } return num; } private bool IsAttrChar(int ch) { if ((uint)(ch - 9) <= 1u || ch == 13 || ch == 38) { return false; } return true; } public string GetEscapedString(int offset, int length) { char[] charBuffer = GetCharBuffer(length); int escapedChars = GetEscapedChars(offset, length, charBuffer); return new string(charBuffer, 0, escapedChars); } public string GetEscapedString(int offset, int length, XmlNameTable nameTable) { char[] charBuffer = GetCharBuffer(length); int escapedChars = GetEscapedChars(offset, length, charBuffer); return nameTable.Add(charBuffer, 0, escapedChars); } private int GetLessThanCharEntity(int offset, int length) { byte[] array = buffer; if (length != 4 || array[offset + 1] != 108 || array[offset + 2] != 116) { XmlExceptionHelper.ThrowInvalidCharRef(reader); } return 60; } private int GetGreaterThanCharEntity(int offset, int length) { byte[] array = buffer; if (length != 4 || array[offset + 1] != 103 || array[offset + 2] != 116) { XmlExceptionHelper.ThrowInvalidCharRef(reader); } return 62; } private int GetQuoteCharEntity(int offset, int length) { byte[] array = buffer; if (length != 6 || array[offset + 1] != 113 || array[offset + 2] != 117 || array[offset + 3] != 111 || array[offset + 4] != 116) { XmlExceptionHelper.ThrowInvalidCharRef(reader); } return 34; } private int GetAmpersandCharEntity(int offset, int length) { byte[] array = buffer; if (length != 5 || array[offset + 1] != 97 || array[offset + 2] != 109 || array[offset + 3] != 112) { XmlExceptionHelper.ThrowInvalidCharRef(reader); } return 38; } private int GetApostropheCharEntity(int offset, int length) { byte[] array = buffer; if (length != 6 || array[offset + 1] != 97 || array[offset + 2] != 112 || array[offset + 3] != 111 || array[offset + 4] != 115) { XmlExceptionHelper.ThrowInvalidCharRef(reader); } return 39; } private int GetDecimalCharEntity(int offset, int length) { byte[] array = buffer; int num = 0; for (int i = 2; i < length - 1; i++) { byte b = array[offset + i]; if (b < 48 || b > 57) { XmlExceptionHelper.ThrowInvalidCharRef(reader); } num = num * 10 + (b - 48); if (num > 1114111) { XmlExceptionHelper.ThrowInvalidCharRef(reader); } } return num; } private int GetHexCharEntity(int offset, int length) { byte[] array = buffer; int num = 0; for (int i = 3; i < length - 1; i++) { byte b = array[offset + i]; int num2 = 0; if (b >= 48 && b <= 57) { num2 = b - 48; } else if (b >= 97 && b <= 102) { num2 = 10 + (b - 97); } else if (b >= 65 && b <= 70) { num2 = 10 + (b - 65); } else { XmlExceptionHelper.ThrowInvalidCharRef(reader); } num = num * 16 + num2; if (num > 1114111) { XmlExceptionHelper.ThrowInvalidCharRef(reader); } } return num; } public int GetCharEntity(int offset, int length) { if (length < 3) { XmlExceptionHelper.ThrowInvalidCharRef(reader); } byte[] array = buffer; switch (array[offset + 1]) { case 108: return GetLessThanCharEntity(offset, length); case 103: return GetGreaterThanCharEntity(offset, length); case 97: if (array[offset + 2] == 109) { return GetAmpersandCharEntity(offset, length); } return GetApostropheCharEntity(offset, length); case 113: return GetQuoteCharEntity(offset, length); case 35: if (array[offset + 2] == 120) { return GetHexCharEntity(offset, length); } return GetDecimalCharEntity(offset, length); default: XmlExceptionHelper.ThrowInvalidCharRef(reader); return 0; } } public bool IsWhitespaceKey(int key) { string value = GetDictionaryString(key).Value; for (int i = 0; i < value.Length; i++) { if (!XmlConverter.IsWhitespace(value[i])) { return false; } } return true; } public bool IsWhitespaceUTF8(int offset, int length) { byte[] array = buffer; for (int i = 0; i < length; i++) { if (!XmlConverter.IsWhitespace((char)array[offset + i])) { return false; } } return true; } public bool IsWhitespaceUnicode(int offset, int length) { _ = buffer; for (int i = 0; i < length; i += 2) { if (!XmlConverter.IsWhitespace((char)GetInt16(offset + i))) { return false; } } return true; } public bool Equals2(int key1, int key2, XmlBufferReader bufferReader2) { if (key1 == key2) { return true; } return GetDictionaryString(key1).Value == bufferReader2.GetDictionaryString(key2).Value; } public bool Equals2(int key1, XmlDictionaryString xmlString2) { if ((key1 & 1) == 0 && xmlString2.Dictionary == dictionary) { return xmlString2.Key == key1 >> 1; } return GetDictionaryString(key1).Value == xmlString2.Value; } public bool Equals2(int offset1, int length1, byte[] buffer2) { int num = buffer2.Length; if (length1 != num) { return false; } byte[] array = buffer; for (int i = 0; i < length1; i++) { if (array[offset1 + i] != buffer2[i]) { return false; } } return true; } public bool Equals2(int offset1, int length1, XmlBufferReader bufferReader2, int offset2, int length2) { if (length1 != length2) { return false; } byte[] array = buffer; byte[] array2 = bufferReader2.buffer; for (int i = 0; i < length1; i++) { if (array[offset1 + i] != array2[offset2 + i]) { return false; } } return true; } public bool Equals2(int offset1, int length1, int offset2, int length2) { if (length1 != length2) { return false; } if (offset1 == offset2) { return true; } byte[] array = buffer; for (int i = 0; i < length1; i++) { if (array[offset1 + i] != array[offset2 + i]) { return false; } } return true; } [SecuritySafeCritical] public unsafe bool Equals2(int offset1, int length1, string s2) { int length2 = s2.Length; if (length1 < length2 || length1 > length2 * 3) { return false; } byte[] array = buffer; if (length1 < 8) { int num = Math.Min(length1, length2); for (int i = 0; i < num; i++) { byte b = array[offset1 + i]; if (b >= 128) { return XmlConverter.ToString(array, offset1, length1) == s2; } if (s2[i] != b) { return false; } } return length1 == length2; } int num2 = Math.Min(length1, length2); fixed (byte* ptr = &array[offset1]) { byte* ptr2 = ptr; byte* ptr3 = ptr2 + num2; fixed (char* ptr4 = s2) { char* ptr5 = ptr4; int num3 = 0; while (ptr2 < ptr3 && *ptr2 < 128) { num3 = *ptr2 - (byte)(*ptr5); if (num3 != 0) { break; } ptr2++; ptr5++; } if (num3 != 0) { return false; } if (ptr2 == ptr3) { return length1 == length2; } } } return XmlConverter.ToString(array, offset1, length1) == s2; } public int Compare(int offset1, int length1, int offset2, int length2) { byte[] array = buffer; int num = Math.Min(length1, length2); for (int i = 0; i < num; i++) { int num2 = array[offset1 + i] - array[offset2 + i]; if (num2 != 0) { return num2; } } return length1 - length2; } public byte GetByte(int offset) { return buffer[offset]; } public int GetInt8(int offset) { return (sbyte)GetByte(offset); } public int GetInt16(int offset) { byte[] array = buffer; return (short)(array[offset] + (array[offset + 1] << 8)); } public int GetInt32(int offset) { byte[] array = buffer; byte b = array[offset]; byte b2 = array[offset + 1]; byte b3 = array[offset + 2]; return (((array[offset + 3] << 8) + b3 << 8) + b2 << 8) + b; } public long GetInt64(int offset) { byte[] array = buffer; byte b = array[offset]; byte b2 = array[offset + 1]; byte b3 = array[offset + 2]; long num = (uint)((((array[offset + 3] << 8) + b3 << 8) + b2 << 8) + b); b = array[offset + 4]; b2 = array[offset + 5]; b3 = array[offset + 6]; return (long)((ulong)(uint)((((array[offset + 7] << 8) + b3 << 8) + b2 << 8) + b) << 32) + num; } public ulong GetUInt64(int offset) { return (ulong)GetInt64(offset); } [SecuritySafeCritical] public unsafe float GetSingle(int offset) { byte[] array = buffer; float result = default(float); byte* ptr = (byte*)(&result); *ptr = array[offset]; ptr[1] = array[offset + 1]; ptr[2] = array[offset + 2]; ptr[3] = array[offset + 3]; return result; } [SecuritySafeCritical] public unsafe double GetDouble(int offset) { byte[] array = buffer; double result = default(double); byte* ptr = (byte*)(&result); *ptr = array[offset]; ptr[1] = array[offset + 1]; ptr[2] = array[offset + 2]; ptr[3] = array[offset + 3]; ptr[4] = array[offset + 4]; ptr[5] = array[offset + 5]; ptr[6] = array[offset + 6]; ptr[7] = array[offset + 7]; return result; } [SecuritySafeCritical] public unsafe decimal GetDecimal(int offset) { byte[] array = buffer; byte b = array[offset]; byte b2 = array[offset + 1]; byte b3 = array[offset + 2]; int num = (((array[offset + 3] << 8) + b3 << 8) + b2 << 8) + b; if ((num & 0x7F00FFFF) == 0 && (num & 0xFF0000) <= 1835008) { decimal result = default(decimal); byte* ptr = (byte*)(&result); for (int i = 0; i < 16; i++) { ptr[i] = array[offset + i]; } return result; } XmlExceptionHelper.ThrowInvalidBinaryFormat(reader); return 0m; } public UniqueId GetUniqueId(int offset) { return new UniqueId(buffer, offset); } public Guid GetGuid(int offset) { if (guid == null) { guid = new byte[16]; } System.Buffer.BlockCopy(buffer, offset, guid, 0, guid.Length); return new Guid(guid); } public void GetBase64(int srcOffset, byte[] buffer, int dstOffset, int count) { System.Buffer.BlockCopy(this.buffer, srcOffset, buffer, dstOffset, count); } public XmlBinaryNodeType GetNodeType() { return (XmlBinaryNodeType)GetByte(); } public void SkipNodeType() { SkipByte(); } public object[] GetList(int offset, int count) { int num = Offset; Offset = offset; try { object[] array = new object[count]; for (int i = 0; i < count; i++) { XmlBinaryNodeType nodeType = GetNodeType(); SkipNodeType(); ReadValue(nodeType, listValue); array[i] = listValue.ToObject(); } return array; } finally { Offset = num; } } public XmlDictionaryString GetDictionaryString(int key) { IXmlDictionary xmlDictionary = (((key & 1) == 0) ? dictionary : session); if (!xmlDictionary.TryLookup(key >> 1, out var result)) { XmlExceptionHelper.ThrowInvalidBinaryFormat(reader); } return result; } public int ReadDictionaryKey() { int num = ReadMultiByteUInt31(); if (((uint)num & (true ? 1u : 0u)) != 0) { if (session == null) { XmlExceptionHelper.ThrowInvalidBinaryFormat(reader); } int num2 = num >> 1; if (!session.TryLookup(num2, out var _)) { if (num2 < 0 || num2 > 536870911) { XmlExceptionHelper.ThrowXmlDictionaryStringIDOutOfRange(reader); } XmlExceptionHelper.ThrowXmlDictionaryStringIDUndefinedSession(reader, num2); } } else { if (dictionary == null) { XmlExceptionHelper.ThrowInvalidBinaryFormat(reader); } int num3 = num >> 1; if (!dictionary.TryLookup(num3, out var _)) { if (num3 < 0 || num3 > 536870911) { XmlExceptionHelper.ThrowXmlDictionaryStringIDOutOfRange(reader); } XmlExceptionHelper.ThrowXmlDictionaryStringIDUndefinedStatic(reader, num3); } } return num; } public void ReadValue(XmlBinaryNodeType nodeType, ValueHandle value) { switch (nodeType) { case XmlBinaryNodeType.EmptyText: value.SetValue(ValueHandleType.Empty); break; case XmlBinaryNodeType.MinText: value.SetValue(ValueHandleType.Zero); break; case XmlBinaryNodeType.OneText: value.SetValue(ValueHandleType.One); break; case XmlBinaryNodeType.TrueText: value.SetValue(ValueHandleType.True); break; case XmlBinaryNodeType.FalseText: value.SetValue(ValueHandleType.False); break; case XmlBinaryNodeType.BoolText: value.SetValue((ReadUInt8() != 0) ? ValueHandleType.True : ValueHandleType.False); break; case XmlBinaryNodeType.Chars8Text: ReadValue(value, ValueHandleType.UTF8, ReadUInt8()); break; case XmlBinaryNodeType.Chars16Text: ReadValue(value, ValueHandleType.UTF8, ReadUInt16()); break; case XmlBinaryNodeType.Chars32Text: ReadValue(value, ValueHandleType.UTF8, ReadUInt31()); break; case XmlBinaryNodeType.UnicodeChars8Text: ReadUnicodeValue(value, ReadUInt8()); break; case XmlBinaryNodeType.UnicodeChars16Text: ReadUnicodeValue(value, ReadUInt16()); break; case XmlBinaryNodeType.UnicodeChars32Text: ReadUnicodeValue(value, ReadUInt31()); break; case XmlBinaryNodeType.Bytes8Text: ReadValue(value, ValueHandleType.Base64, ReadUInt8()); break; case XmlBinaryNodeType.Bytes16Text: ReadValue(value, ValueHandleType.Base64, ReadUInt16()); break; case XmlBinaryNodeType.Bytes32Text: ReadValue(value, ValueHandleType.Base64, ReadUInt31()); break; case XmlBinaryNodeType.DictionaryText: value.SetDictionaryValue(ReadDictionaryKey()); break; case XmlBinaryNodeType.UniqueIdText: ReadValue(value, ValueHandleType.UniqueId, 16); break; case XmlBinaryNodeType.GuidText: ReadValue(value, ValueHandleType.Guid, 16); break; case XmlBinaryNodeType.DecimalText: ReadValue(value, ValueHandleType.Decimal, 16); break; case XmlBinaryNodeType.Int8Text: ReadValue(value, ValueHandleType.Int8, 1); break; case XmlBinaryNodeType.Int16Text: ReadValue(value, ValueHandleType.Int16, 2); break; case XmlBinaryNodeType.Int32Text: ReadValue(value, ValueHandleType.Int32, 4); break; case XmlBinaryNodeType.Int64Text: ReadValue(value, ValueHandleType.Int64, 8); break; case XmlBinaryNodeType.UInt64Text: ReadValue(value, ValueHandleType.UInt64, 8); break; case XmlBinaryNodeType.FloatText: ReadValue(value, ValueHandleType.Single, 4); break; case XmlBinaryNodeType.DoubleText: ReadValue(value, ValueHandleType.Double, 8); break; case XmlBinaryNodeType.TimeSpanText: ReadValue(value, ValueHandleType.TimeSpan, 8); break; case XmlBinaryNodeType.DateTimeText: ReadValue(value, ValueHandleType.DateTime, 8); break; case XmlBinaryNodeType.StartListText: ReadList(value); break; case XmlBinaryNodeType.QNameDictionaryText: ReadQName(value); break; default: XmlExceptionHelper.ThrowInvalidBinaryFormat(reader); break; } } private void ReadValue(ValueHandle value, ValueHandleType type, int length) { int num = ReadBytes(length); value.SetValue(type, num, length); } private void ReadUnicodeValue(ValueHandle value, int length) { if (((uint)length & (true ? 1u : 0u)) != 0) { XmlExceptionHelper.ThrowInvalidBinaryFormat(reader); } ReadValue(value, ValueHandleType.Unicode, length); } private void ReadList(ValueHandle value) { if (listValue == null) { listValue = new ValueHandle(this); } int num = 0; int num2 = Offset; while (true) { XmlBinaryNodeType nodeType = GetNodeType(); SkipNodeType(); if (nodeType == XmlBinaryNodeType.StartListText) { XmlExceptionHelper.ThrowInvalidBinaryFormat(reader); } if (nodeType == XmlBinaryNodeType.EndListText) { break; } ReadValue(nodeType, listValue); num++; } value.SetValue(ValueHandleType.List, num2, num); } public void ReadQName(ValueHandle value) { int num = ReadUInt8(); if (num >= 26) { XmlExceptionHelper.ThrowInvalidBinaryFormat(reader); } int key = ReadDictionaryKey(); value.SetQNameValue(num, key); } public int[] GetRows() { if (buffer == null) { return new int[1]; } ArrayList arrayList = new ArrayList(); arrayList.Add(offsetMin); for (int i = offsetMin; i < offsetMax; i++) { if (buffer[i] == 13 || buffer[i] == 10) { if (i + 1 < offsetMax && buffer[i + 1] == 10) { i++; } arrayList.Add(i + 1); } } return (int[])arrayList.ToArray(typeof(int)); } } internal sealed class XmlCanonicalWriter { private class AttributeSorter : IComparer { private XmlCanonicalWriter writer; public AttributeSorter(XmlCanonicalWriter writer) { this.writer = writer; } public void Sort() { object[] array = new object[writer.attributeCount]; for (int i = 0; i < array.Length; i++) { array[i] = i; } Array.Sort(array, this); Attribute[] array2 = new Attribute[writer.attributes.Length]; for (int j = 0; j < array.Length; j++) { array2[j] = writer.attributes[(int)array[j]]; } writer.attributes = array2; } public int Compare(object obj1, object obj2) { int num = (int)obj1; int num2 = (int)obj2; return writer.Compare(ref writer.attributes[num], ref writer.attributes[num2]); } } private struct Scope { public int xmlnsAttributeCount; public int xmlnsOffset; } private struct Element { public int prefixOffset; public int prefixLength; public int localNameOffset; public int localNameLength; } private struct Attribute { public int prefixOffset; public int prefixLength; public int localNameOffset; public int localNameLength; public int nsOffset; public int nsLength; public int offset; public int length; } private struct XmlnsAttribute { public int prefixOffset; public int prefixLength; public int nsOffset; public int nsLength; public bool referred; } private XmlUTF8NodeWriter writer; private MemoryStream elementStream; private byte[] elementBuffer; private XmlUTF8NodeWriter elementWriter; private bool inStartElement; private int depth; private Scope[] scopes; private int xmlnsAttributeCount; private XmlnsAttribute[] xmlnsAttributes; private int attributeCount; private Attribute[] attributes; private Attribute attribute; private Element element; private byte[] xmlnsBuffer; private int xmlnsOffset; private const int maxBytesPerChar = 3; private int xmlnsStartOffset; private bool includeComments; private string[] inclusivePrefixes; private const string xmlnsNamespace = "http://www.w3.org/2000/xmlns/"; private static readonly bool[] isEscapedAttributeChar = new bool[64] { true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, true, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false }; private static readonly bool[] isEscapedElementChar = new bool[64] { true, true, true, true, true, true, true, true, true, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false }; public void SetOutput(Stream stream, bool includeComments, string[] inclusivePrefixes) { if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream"); } if (writer == null) { writer = new XmlUTF8NodeWriter(isEscapedAttributeChar, isEscapedElementChar); } writer.SetOutput(stream, ownsStream: false, null); if (elementStream == null) { elementStream = new MemoryStream(); } if (elementWriter == null) { elementWriter = new XmlUTF8NodeWriter(isEscapedAttributeChar, isEscapedElementChar); } elementWriter.SetOutput(elementStream, ownsStream: false, null); if (xmlnsAttributes == null) { xmlnsAttributeCount = 0; xmlnsOffset = 0; WriteXmlnsAttribute("xml", "http://www.w3.org/XML/1998/namespace"); WriteXmlnsAttribute("xmlns", "http://www.w3.org/2000/xmlns/"); WriteXmlnsAttribute(string.Empty, string.Empty); xmlnsStartOffset = xmlnsOffset; for (int i = 0; i < 3; i++) { xmlnsAttributes[i].referred = true; } } else { xmlnsAttributeCount = 3; xmlnsOffset = xmlnsStartOffset; } depth = 0; inStartElement = false; this.includeComments = includeComments; this.inclusivePrefixes = null; if (inclusivePrefixes == null) { return; } this.inclusivePrefixes = new string[inclusivePrefixes.Length]; for (int j = 0; j < inclusivePrefixes.Length; j++) { if (inclusivePrefixes[j] == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.Runtime.Serialization.SR.GetString("The inclusive namespace prefix collection cannot contain null as one of the items.")); } this.inclusivePrefixes[j] = inclusivePrefixes[j]; } } public void Flush() { ThrowIfClosed(); writer.Flush(); } public void Close() { if (writer != null) { writer.Close(); } if (elementWriter != null) { elementWriter.Close(); } if (elementStream != null && elementStream.Length > 512) { elementStream = null; } elementBuffer = null; if (scopes != null && scopes.Length > 16) { scopes = null; } if (attributes != null && attributes.Length > 16) { attributes = null; } if (xmlnsBuffer != null && xmlnsBuffer.Length > 1024) { xmlnsAttributes = null; xmlnsBuffer = null; } inclusivePrefixes = null; } public void WriteDeclaration() { } public void WriteComment(string value) { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } ThrowIfClosed(); if (includeComments) { writer.WriteComment(value); } } private void StartElement() { if (scopes == null) { scopes = new Scope[4]; } else if (depth == scopes.Length) { Scope[] destinationArray = new Scope[depth * 2]; Array.Copy(scopes, destinationArray, depth); scopes = destinationArray; } scopes[depth].xmlnsAttributeCount = xmlnsAttributeCount; scopes[depth].xmlnsOffset = xmlnsOffset; depth++; inStartElement = true; attributeCount = 0; elementStream.Position = 0L; } private void EndElement() { depth--; xmlnsAttributeCount = scopes[depth].xmlnsAttributeCount; xmlnsOffset = scopes[depth].xmlnsOffset; } public void WriteStartElement(string prefix, string localName) { if (prefix == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("prefix"); } if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localName"); } ThrowIfClosed(); bool num = depth == 0; StartElement(); element.prefixOffset = elementWriter.Position + 1; element.prefixLength = Encoding.UTF8.GetByteCount(prefix); element.localNameOffset = element.prefixOffset + element.prefixLength + ((element.prefixLength != 0) ? 1 : 0); element.localNameLength = Encoding.UTF8.GetByteCount(localName); elementWriter.WriteStartElement(prefix, localName); if (!num || inclusivePrefixes == null) { return; } for (int i = 0; i < scopes[0].xmlnsAttributeCount; i++) { if (IsInclusivePrefix(ref xmlnsAttributes[i])) { XmlnsAttribute xmlnsAttribute = xmlnsAttributes[i]; AddXmlnsAttribute(ref xmlnsAttribute); } } } public void WriteStartElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { if (prefixBuffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("prefixBuffer")); } if (prefixOffset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("prefixOffset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (prefixOffset > prefixBuffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("prefixOffset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", prefixBuffer.Length))); } if (prefixLength < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("prefixLength", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (prefixLength > prefixBuffer.Length - prefixOffset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("prefixLength", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", prefixBuffer.Length - prefixOffset))); } if (localNameBuffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localNameBuffer")); } if (localNameOffset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("localNameOffset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (localNameOffset > localNameBuffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("localNameOffset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", localNameBuffer.Length))); } if (localNameLength < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("localNameLength", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (localNameLength > localNameBuffer.Length - localNameOffset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("localNameLength", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", localNameBuffer.Length - localNameOffset))); } ThrowIfClosed(); bool num = depth == 0; StartElement(); element.prefixOffset = elementWriter.Position + 1; element.prefixLength = prefixLength; element.localNameOffset = element.prefixOffset + prefixLength + ((prefixLength != 0) ? 1 : 0); element.localNameLength = localNameLength; elementWriter.WriteStartElement(prefixBuffer, prefixOffset, prefixLength, localNameBuffer, localNameOffset, localNameLength); if (!num || inclusivePrefixes == null) { return; } for (int i = 0; i < scopes[0].xmlnsAttributeCount; i++) { if (IsInclusivePrefix(ref xmlnsAttributes[i])) { XmlnsAttribute xmlnsAttribute = xmlnsAttributes[i]; AddXmlnsAttribute(ref xmlnsAttribute); } } } private bool IsInclusivePrefix(ref XmlnsAttribute xmlnsAttribute) { for (int i = 0; i < inclusivePrefixes.Length; i++) { if (inclusivePrefixes[i].Length == xmlnsAttribute.prefixLength && string.Compare(Encoding.UTF8.GetString(xmlnsBuffer, xmlnsAttribute.prefixOffset, xmlnsAttribute.prefixLength), inclusivePrefixes[i], StringComparison.Ordinal) == 0) { return true; } } return false; } public void WriteEndStartElement(bool isEmpty) { ThrowIfClosed(); elementWriter.Flush(); elementBuffer = elementStream.GetBuffer(); inStartElement = false; ResolvePrefixes(); writer.WriteStartElement(elementBuffer, element.prefixOffset, element.prefixLength, elementBuffer, element.localNameOffset, element.localNameLength); for (int i = scopes[depth - 1].xmlnsAttributeCount; i < xmlnsAttributeCount; i++) { int num = i - 1; bool flag = false; while (num >= 0) { if (Equals(xmlnsBuffer, xmlnsAttributes[i].prefixOffset, xmlnsAttributes[i].prefixLength, xmlnsBuffer, xmlnsAttributes[num].prefixOffset, xmlnsAttributes[num].prefixLength)) { if (!Equals(xmlnsBuffer, xmlnsAttributes[i].nsOffset, xmlnsAttributes[i].nsLength, xmlnsBuffer, xmlnsAttributes[num].nsOffset, xmlnsAttributes[num].nsLength)) { break; } if (xmlnsAttributes[num].referred) { flag = true; break; } } num--; } if (!flag) { WriteXmlnsAttribute(ref xmlnsAttributes[i]); } } if (attributeCount > 0) { if (attributeCount > 1) { SortAttributes(); } for (int j = 0; j < attributeCount; j++) { writer.WriteText(elementBuffer, attributes[j].offset, attributes[j].length); } } writer.WriteEndStartElement(isEmpty: false); if (isEmpty) { writer.WriteEndElement(elementBuffer, element.prefixOffset, element.prefixLength, elementBuffer, element.localNameOffset, element.localNameLength); EndElement(); } elementBuffer = null; } public void WriteEndElement(string prefix, string localName) { if (prefix == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("prefix"); } if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localName"); } ThrowIfClosed(); writer.WriteEndElement(prefix, localName); EndElement(); } private void EnsureXmlnsBuffer(int byteCount) { if (xmlnsBuffer == null) { xmlnsBuffer = new byte[Math.Max(byteCount, 128)]; } else if (xmlnsOffset + byteCount > xmlnsBuffer.Length) { byte[] dst = new byte[Math.Max(xmlnsOffset + byteCount, xmlnsBuffer.Length * 2)]; Buffer.BlockCopy(xmlnsBuffer, 0, dst, 0, xmlnsOffset); xmlnsBuffer = dst; } } public void WriteXmlnsAttribute(string prefix, string ns) { if (prefix == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("prefix"); } if (ns == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ns"); } ThrowIfClosed(); if (prefix.Length > int.MaxValue - ns.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("ns", System.Runtime.Serialization.SR.GetString("The combined length of the prefix and namespace must not be greater than {0}.", 715827882))); } int num = prefix.Length + ns.Length; if (num > 715827882) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("ns", System.Runtime.Serialization.SR.GetString("The combined length of the prefix and namespace must not be greater than {0}.", 715827882))); } EnsureXmlnsBuffer(num * 3); XmlnsAttribute xmlnsAttribute = default(XmlnsAttribute); xmlnsAttribute.prefixOffset = xmlnsOffset; xmlnsAttribute.prefixLength = Encoding.UTF8.GetBytes(prefix, 0, prefix.Length, xmlnsBuffer, xmlnsOffset); xmlnsOffset += xmlnsAttribute.prefixLength; xmlnsAttribute.nsOffset = xmlnsOffset; xmlnsAttribute.nsLength = Encoding.UTF8.GetBytes(ns, 0, ns.Length, xmlnsBuffer, xmlnsOffset); xmlnsOffset += xmlnsAttribute.nsLength; xmlnsAttribute.referred = false; AddXmlnsAttribute(ref xmlnsAttribute); } public void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] nsBuffer, int nsOffset, int nsLength) { if (prefixBuffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("prefixBuffer")); } if (prefixOffset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("prefixOffset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (prefixOffset > prefixBuffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("prefixOffset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", prefixBuffer.Length))); } if (prefixLength < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("prefixLength", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (prefixLength > prefixBuffer.Length - prefixOffset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("prefixLength", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", prefixBuffer.Length - prefixOffset))); } if (nsBuffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("nsBuffer")); } if (nsOffset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("nsOffset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (nsOffset > nsBuffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("nsOffset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", nsBuffer.Length))); } if (nsLength < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("nsLength", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (nsLength > nsBuffer.Length - nsOffset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("nsLength", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", nsBuffer.Length - nsOffset))); } ThrowIfClosed(); if (prefixLength > int.MaxValue - nsLength) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("nsLength", System.Runtime.Serialization.SR.GetString("The combined length of the prefix and namespace must not be greater than {0}.", int.MaxValue))); } EnsureXmlnsBuffer(prefixLength + nsLength); XmlnsAttribute xmlnsAttribute = default(XmlnsAttribute); xmlnsAttribute.prefixOffset = xmlnsOffset; xmlnsAttribute.prefixLength = prefixLength; Buffer.BlockCopy(prefixBuffer, prefixOffset, xmlnsBuffer, xmlnsOffset, prefixLength); xmlnsOffset += prefixLength; xmlnsAttribute.nsOffset = xmlnsOffset; xmlnsAttribute.nsLength = nsLength; Buffer.BlockCopy(nsBuffer, nsOffset, xmlnsBuffer, xmlnsOffset, nsLength); xmlnsOffset += nsLength; xmlnsAttribute.referred = false; AddXmlnsAttribute(ref xmlnsAttribute); } public void WriteStartAttribute(string prefix, string localName) { if (prefix == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("prefix"); } if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localName"); } ThrowIfClosed(); attribute.offset = elementWriter.Position; attribute.length = 0; attribute.prefixOffset = attribute.offset + 1; attribute.prefixLength = Encoding.UTF8.GetByteCount(prefix); attribute.localNameOffset = attribute.prefixOffset + attribute.prefixLength + ((attribute.prefixLength != 0) ? 1 : 0); attribute.localNameLength = Encoding.UTF8.GetByteCount(localName); attribute.nsOffset = 0; attribute.nsLength = 0; elementWriter.WriteStartAttribute(prefix, localName); } public void WriteStartAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { if (prefixBuffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("prefixBuffer")); } if (prefixOffset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("prefixOffset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (prefixOffset > prefixBuffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("prefixOffset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", prefixBuffer.Length))); } if (prefixLength < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("prefixLength", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (prefixLength > prefixBuffer.Length - prefixOffset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("prefixLength", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", prefixBuffer.Length - prefixOffset))); } if (localNameBuffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localNameBuffer")); } if (localNameOffset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("localNameOffset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (localNameOffset > localNameBuffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("localNameOffset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", localNameBuffer.Length))); } if (localNameLength < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("localNameLength", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (localNameLength > localNameBuffer.Length - localNameOffset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("localNameLength", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", localNameBuffer.Length - localNameOffset))); } ThrowIfClosed(); attribute.offset = elementWriter.Position; attribute.length = 0; attribute.prefixOffset = attribute.offset + 1; attribute.prefixLength = prefixLength; attribute.localNameOffset = attribute.prefixOffset + prefixLength + ((prefixLength != 0) ? 1 : 0); attribute.localNameLength = localNameLength; attribute.nsOffset = 0; attribute.nsLength = 0; elementWriter.WriteStartAttribute(prefixBuffer, prefixOffset, prefixLength, localNameBuffer, localNameOffset, localNameLength); } public void WriteEndAttribute() { ThrowIfClosed(); elementWriter.WriteEndAttribute(); attribute.length = elementWriter.Position - attribute.offset; AddAttribute(ref attribute); } public void WriteCharEntity(int ch) { ThrowIfClosed(); if (ch <= 65535) { char[] chars = new char[1] { (char)ch }; WriteEscapedText(chars, 0, 1); } else { WriteText(ch); } } public void WriteEscapedText(string value) { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } ThrowIfClosed(); if (depth > 0) { if (inStartElement) { elementWriter.WriteEscapedText(value); } else { writer.WriteEscapedText(value); } } } public void WriteEscapedText(byte[] chars, int offset, int count) { if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > chars.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > chars.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", chars.Length - offset))); } ThrowIfClosed(); if (depth > 0) { if (inStartElement) { elementWriter.WriteEscapedText(chars, offset, count); } else { writer.WriteEscapedText(chars, offset, count); } } } public void WriteEscapedText(char[] chars, int offset, int count) { ThrowIfClosed(); if (depth > 0) { if (inStartElement) { elementWriter.WriteEscapedText(chars, offset, count); } else { writer.WriteEscapedText(chars, offset, count); } } } public void WriteText(int ch) { ThrowIfClosed(); if (inStartElement) { elementWriter.WriteText(ch); } else { writer.WriteText(ch); } } public void WriteText(byte[] chars, int offset, int count) { ThrowIfClosed(); if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > chars.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > chars.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", chars.Length - offset))); } if (inStartElement) { elementWriter.WriteText(chars, offset, count); } else { writer.WriteText(chars, offset, count); } } public void WriteText(string value) { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } if (value.Length > 0) { if (inStartElement) { elementWriter.WriteText(value); } else { writer.WriteText(value); } } } public void WriteText(char[] chars, int offset, int count) { ThrowIfClosed(); if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > chars.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > chars.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", chars.Length - offset))); } if (inStartElement) { elementWriter.WriteText(chars, offset, count); } else { writer.WriteText(chars, offset, count); } } private void ThrowIfClosed() { if (writer == null) { ThrowClosed(); } } private void ThrowClosed() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(GetType().ToString())); } private void WriteXmlnsAttribute(ref XmlnsAttribute xmlnsAttribute) { if (xmlnsAttribute.referred) { writer.WriteXmlnsAttribute(xmlnsBuffer, xmlnsAttribute.prefixOffset, xmlnsAttribute.prefixLength, xmlnsBuffer, xmlnsAttribute.nsOffset, xmlnsAttribute.nsLength); } } private void SortAttributes() { if (attributeCount < 16) { for (int i = 0; i < attributeCount - 1; i++) { int num = i; for (int j = i + 1; j < attributeCount; j++) { if (Compare(ref attributes[j], ref attributes[num]) < 0) { num = j; } } if (num != i) { Attribute attribute = attributes[i]; attributes[i] = attributes[num]; attributes[num] = attribute; } } } else { new AttributeSorter(this).Sort(); } } private void AddAttribute(ref Attribute attribute) { if (attributes == null) { attributes = new Attribute[4]; } else if (attributeCount == attributes.Length) { Attribute[] destinationArray = new Attribute[attributeCount * 2]; Array.Copy(attributes, destinationArray, attributeCount); attributes = destinationArray; } attributes[attributeCount] = attribute; attributeCount++; } private void AddXmlnsAttribute(ref XmlnsAttribute xmlnsAttribute) { if (xmlnsAttributes == null) { xmlnsAttributes = new XmlnsAttribute[4]; } else if (xmlnsAttributes.Length == xmlnsAttributeCount) { XmlnsAttribute[] destinationArray = new XmlnsAttribute[xmlnsAttributeCount * 2]; Array.Copy(xmlnsAttributes, destinationArray, xmlnsAttributeCount); xmlnsAttributes = destinationArray; } if (depth > 0 && inclusivePrefixes != null && IsInclusivePrefix(ref xmlnsAttribute)) { xmlnsAttribute.referred = true; } if (depth == 0) { xmlnsAttributes[xmlnsAttributeCount++] = xmlnsAttribute; return; } int i = scopes[depth - 1].xmlnsAttributeCount; bool flag = true; for (; i < xmlnsAttributeCount; i++) { int num = Compare(ref xmlnsAttribute, ref xmlnsAttributes[i]); if (num <= 0) { if (num == 0) { xmlnsAttributes[i] = xmlnsAttribute; flag = false; } break; } } if (flag) { Array.Copy(xmlnsAttributes, i, xmlnsAttributes, i + 1, xmlnsAttributeCount - i); xmlnsAttributes[i] = xmlnsAttribute; xmlnsAttributeCount++; } } private void ResolvePrefix(int prefixOffset, int prefixLength, out int nsOffset, out int nsLength) { int num = scopes[depth - 1].xmlnsAttributeCount; int num2 = xmlnsAttributeCount - 1; while (!Equals(elementBuffer, prefixOffset, prefixLength, xmlnsBuffer, xmlnsAttributes[num2].prefixOffset, xmlnsAttributes[num2].prefixLength)) { num2--; } nsOffset = xmlnsAttributes[num2].nsOffset; nsLength = xmlnsAttributes[num2].nsLength; if (num2 < num) { if (!xmlnsAttributes[num2].referred) { XmlnsAttribute xmlnsAttribute = xmlnsAttributes[num2]; xmlnsAttribute.referred = true; AddXmlnsAttribute(ref xmlnsAttribute); } } else { xmlnsAttributes[num2].referred = true; } } private void ResolvePrefix(ref Attribute attribute) { if (attribute.prefixLength != 0) { ResolvePrefix(attribute.prefixOffset, attribute.prefixLength, out attribute.nsOffset, out attribute.nsLength); } } private void ResolvePrefixes() { ResolvePrefix(element.prefixOffset, element.prefixLength, out var _, out var _); for (int i = 0; i < attributeCount; i++) { ResolvePrefix(ref attributes[i]); } } private int Compare(ref XmlnsAttribute xmlnsAttribute1, ref XmlnsAttribute xmlnsAttribute2) { return Compare(xmlnsBuffer, xmlnsAttribute1.prefixOffset, xmlnsAttribute1.prefixLength, xmlnsAttribute2.prefixOffset, xmlnsAttribute2.prefixLength); } private int Compare(ref Attribute attribute1, ref Attribute attribute2) { int num = Compare(xmlnsBuffer, attribute1.nsOffset, attribute1.nsLength, attribute2.nsOffset, attribute2.nsLength); if (num == 0) { num = Compare(elementBuffer, attribute1.localNameOffset, attribute1.localNameLength, attribute2.localNameOffset, attribute2.localNameLength); } return num; } private int Compare(byte[] buffer, int offset1, int length1, int offset2, int length2) { if (offset1 == offset2) { return length1 - length2; } return Compare(buffer, offset1, length1, buffer, offset2, length2); } private int Compare(byte[] buffer1, int offset1, int length1, byte[] buffer2, int offset2, int length2) { int num = Math.Min(length1, length2); int num2 = 0; for (int i = 0; i < num; i++) { if (num2 != 0) { break; } num2 = buffer1[offset1 + i] - buffer2[offset2 + i]; } if (num2 == 0) { num2 = length1 - length2; } return num2; } private bool Equals(byte[] buffer1, int offset1, int length1, byte[] buffer2, int offset2, int length2) { if (length1 != length2) { return false; } for (int i = 0; i < length1; i++) { if (buffer1[offset1 + i] != buffer2[offset2 + i]) { return false; } } return true; } } internal static class XmlConverter { public const int MaxDateTimeChars = 64; public const int MaxInt32Chars = 16; public const int MaxInt64Chars = 32; public const int MaxBoolChars = 5; public const int MaxFloatChars = 16; public const int MaxDoubleChars = 32; public const int MaxDecimalChars = 40; public const int MaxUInt64Chars = 32; public const int MaxPrimitiveChars = 64; private static char[] whiteSpaceChars = new char[4] { ' ', '\t', '\n', '\r' }; private static UTF8Encoding utf8Encoding; private static UnicodeEncoding unicodeEncoding; private static Base64Encoding base64Encoding; public static Base64Encoding Base64Encoding { get { if (base64Encoding == null) { base64Encoding = new Base64Encoding(); } return base64Encoding; } } private static UTF8Encoding UTF8Encoding { get { if (utf8Encoding == null) { utf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); } return utf8Encoding; } } private static UnicodeEncoding UnicodeEncoding { get { if (unicodeEncoding == null) { unicodeEncoding = new UnicodeEncoding(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: true); } return unicodeEncoding; } } public static bool ToBoolean(string value) { try { return XmlConvert.ToBoolean(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Boolean", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Boolean", exception2)); } } public static bool ToBoolean(byte[] buffer, int offset, int count) { if (count == 1) { switch (buffer[offset]) { case 49: return true; case 48: return false; } } return ToBoolean(ToString(buffer, offset, count)); } public static int ToInt32(string value) { try { return XmlConvert.ToInt32(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int32", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int32", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int32", exception3)); } } public static int ToInt32(byte[] buffer, int offset, int count) { if (TryParseInt32(buffer, offset, count, out var result)) { return result; } return ToInt32(ToString(buffer, offset, count)); } public static long ToInt64(string value) { try { return XmlConvert.ToInt64(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int64", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int64", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int64", exception3)); } } public static long ToInt64(byte[] buffer, int offset, int count) { if (TryParseInt64(buffer, offset, count, out var result)) { return result; } return ToInt64(ToString(buffer, offset, count)); } public static float ToSingle(string value) { try { return XmlConvert.ToSingle(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "float", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "float", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "float", exception3)); } } public static float ToSingle(byte[] buffer, int offset, int count) { if (TryParseSingle(buffer, offset, count, out var result)) { return result; } return ToSingle(ToString(buffer, offset, count)); } public static double ToDouble(string value) { try { return XmlConvert.ToDouble(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "double", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "double", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "double", exception3)); } } public static double ToDouble(byte[] buffer, int offset, int count) { if (TryParseDouble(buffer, offset, count, out var result)) { return result; } return ToDouble(ToString(buffer, offset, count)); } public static decimal ToDecimal(string value) { try { return XmlConvert.ToDecimal(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "decimal", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "decimal", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "decimal", exception3)); } } public static decimal ToDecimal(byte[] buffer, int offset, int count) { return ToDecimal(ToString(buffer, offset, count)); } public static DateTime ToDateTime(long value) { try { return DateTime.FromBinary(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(ToString(value), "DateTime", exception)); } } public static DateTime ToDateTime(string value) { try { return XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.RoundtripKind); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "DateTime", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "DateTime", exception2)); } } public static DateTime ToDateTime(byte[] buffer, int offset, int count) { if (TryParseDateTime(buffer, offset, count, out var result)) { return result; } return ToDateTime(ToString(buffer, offset, count)); } public static UniqueId ToUniqueId(string value) { try { return new UniqueId(Trim(value)); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UniqueId", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UniqueId", exception2)); } } public static UniqueId ToUniqueId(byte[] buffer, int offset, int count) { return ToUniqueId(ToString(buffer, offset, count)); } public static TimeSpan ToTimeSpan(string value) { try { return XmlConvert.ToTimeSpan(value); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "TimeSpan", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "TimeSpan", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "TimeSpan", exception3)); } } public static TimeSpan ToTimeSpan(byte[] buffer, int offset, int count) { return ToTimeSpan(ToString(buffer, offset, count)); } public static Guid ToGuid(string value) { try { return Guid.Parse(Trim(value)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Guid", exception)); } catch (ArgumentException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Guid", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Guid", exception3)); } } public static Guid ToGuid(byte[] buffer, int offset, int count) { return ToGuid(ToString(buffer, offset, count)); } public static ulong ToUInt64(string value) { try { return ulong.Parse(value, NumberFormatInfo.InvariantInfo); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UInt64", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UInt64", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "UInt64", exception3)); } } public static ulong ToUInt64(byte[] buffer, int offset, int count) { return ToUInt64(ToString(buffer, offset, count)); } public static string ToString(byte[] buffer, int offset, int count) { try { return UTF8Encoding.GetString(buffer, offset, count); } catch (DecoderFallbackException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(buffer, offset, count, exception)); } } public static string ToStringUnicode(byte[] buffer, int offset, int count) { try { return UnicodeEncoding.GetString(buffer, offset, count); } catch (DecoderFallbackException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(buffer, offset, count, exception)); } } public static byte[] ToBytes(string value) { try { return UTF8Encoding.GetBytes(value); } catch (DecoderFallbackException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(value, exception)); } } public static int ToChars(byte[] buffer, int offset, int count, char[] chars, int charOffset) { try { return UTF8Encoding.GetChars(buffer, offset, count, chars, charOffset); } catch (DecoderFallbackException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(buffer, offset, count, exception)); } } public static string ToString(bool value) { if (!value) { return "false"; } return "true"; } public static string ToString(int value) { return XmlConvert.ToString(value); } public static string ToString(long value) { return XmlConvert.ToString(value); } public static string ToString(float value) { return XmlConvert.ToString(value); } public static string ToString(double value) { return XmlConvert.ToString(value); } public static string ToString(decimal value) { return XmlConvert.ToString(value); } public static string ToString(TimeSpan value) { return XmlConvert.ToString(value); } public static string ToString(UniqueId value) { return value.ToString(); } public static string ToString(Guid value) { return value.ToString(); } public static string ToString(ulong value) { return value.ToString(NumberFormatInfo.InvariantInfo); } public static string ToString(DateTime value) { byte[] array = new byte[64]; int num = ToChars(value, array, 0); return ToString(array, 0, num); } private static string ToString(object value) { if (value is int) { return ToString((int)value); } if (value is long) { return ToString((long)value); } if (value is float) { return ToString((float)value); } if (value is double) { return ToString((double)value); } if (value is decimal) { return ToString((decimal)value); } if (value is TimeSpan) { return ToString((TimeSpan)value); } if (value is UniqueId) { return ToString((UniqueId)value); } if (value is Guid) { return ToString((Guid)value); } if (value is ulong) { return ToString((ulong)value); } if (value is DateTime) { return ToString((DateTime)value); } if (value is bool) { return ToString((bool)value); } return value.ToString(); } public static string ToString(object[] objects) { if (objects.Length == 0) { return string.Empty; } string text = ToString(objects[0]); if (objects.Length > 1) { StringBuilder stringBuilder = new StringBuilder(text); for (int i = 1; i < objects.Length; i++) { stringBuilder.Append(' '); stringBuilder.Append(ToString(objects[i])); } text = stringBuilder.ToString(); } return text; } public static void ToQualifiedName(string qname, out string prefix, out string localName) { int num = qname.IndexOf(':'); if (num < 0) { prefix = string.Empty; localName = Trim(qname); return; } if (num == qname.Length - 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Expected XML qualified name. Found '{0}'.", qname))); } prefix = Trim(qname.Substring(0, num)); localName = Trim(qname.Substring(num + 1)); } private static bool TryParseInt32(byte[] chars, int offset, int count, out int result) { result = 0; if (count == 0) { return false; } int num = 0; int num2 = offset + count; if (chars[offset] == 45) { if (count == 1) { return false; } for (int i = offset + 1; i < num2; i++) { int num3 = chars[i] - 48; if ((uint)num3 > 9u) { return false; } if (num < -214748364) { return false; } num *= 10; if (num < int.MinValue + num3) { return false; } num -= num3; } } else { for (int j = offset; j < num2; j++) { int num4 = chars[j] - 48; if ((uint)num4 > 9u) { return false; } if (num > 214748364) { return false; } num *= 10; if (num > int.MaxValue - num4) { return false; } num += num4; } } result = num; return true; } private static bool TryParseInt64(byte[] chars, int offset, int count, out long result) { result = 0L; if (count < 11) { if (!TryParseInt32(chars, offset, count, out var result2)) { return false; } result = result2; return true; } long num = 0L; int num2 = offset + count; if (chars[offset] == 45) { if (count == 1) { return false; } for (int i = offset + 1; i < num2; i++) { int num3 = chars[i] - 48; if ((uint)num3 > 9u) { return false; } if (num < -922337203685477580L) { return false; } num *= 10; if (num < long.MinValue + num3) { return false; } num -= num3; } } else { for (int j = offset; j < num2; j++) { int num4 = chars[j] - 48; if ((uint)num4 > 9u) { return false; } if (num > 922337203685477580L) { return false; } num *= 10; if (num > long.MaxValue - num4) { return false; } num += num4; } } result = num; return true; } private static bool TryParseSingle(byte[] chars, int offset, int count, out float result) { result = 0f; int num = offset + count; bool flag = false; if (offset < num && chars[offset] == 45) { flag = true; offset++; count--; } if (count < 1 || count > 10) { return false; } int num2 = 0; while (offset < num) { int num3 = chars[offset] - 48; switch (num3) { case -2: { offset++; int num4 = 1; while (offset < num) { num3 = chars[offset] - 48; if ((uint)num3 >= 10u) { return false; } num4 *= 10; num2 = num2 * 10 + num3; offset++; } if (count > 8) { result = (float)((double)num2 / (double)num4); } else { result = (float)num2 / (float)num4; } if (flag) { result = 0f - result; } return true; } default: return false; case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: break; } num2 = num2 * 10 + num3; offset++; } if (count == 10) { return false; } if (flag) { result = -num2; } else { result = num2; } return true; } private static bool TryParseDouble(byte[] chars, int offset, int count, out double result) { result = 0.0; int num = offset + count; bool flag = false; if (offset < num && chars[offset] == 45) { flag = true; offset++; count--; } if (count < 1 || count > 10) { return false; } int num2 = 0; while (offset < num) { int num3 = chars[offset] - 48; switch (num3) { case -2: { offset++; int num4 = 1; while (offset < num) { num3 = chars[offset] - 48; if ((uint)num3 >= 10u) { return false; } num4 *= 10; num2 = num2 * 10 + num3; offset++; } if (flag) { result = (0.0 - (double)num2) / (double)num4; } else { result = (double)num2 / (double)num4; } return true; } default: return false; case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: break; } num2 = num2 * 10 + num3; offset++; } if (count == 10) { return false; } if (flag) { result = -num2; } else { result = num2; } return true; } private static int ToInt32D2(byte[] chars, int offset) { byte b = (byte)(chars[offset] - 48); byte b2 = (byte)(chars[offset + 1] - 48); if (b > 9 || b2 > 9) { return -1; } return 10 * b + b2; } private static int ToInt32D4(byte[] chars, int offset, int count) { return ToInt32D7(chars, offset, count); } private static int ToInt32D7(byte[] chars, int offset, int count) { int num = 0; for (int i = 0; i < count; i++) { byte b = (byte)(chars[offset + i] - 48); if (b > 9) { return -1; } num = num * 10 + b; } return num; } private static bool TryParseDateTime(byte[] chars, int offset, int count, out DateTime result) { int num = offset + count; result = DateTime.MaxValue; if (count < 19) { return false; } if (chars[offset + 4] != 45 || chars[offset + 7] != 45 || chars[offset + 10] != 84 || chars[offset + 13] != 58 || chars[offset + 16] != 58) { return false; } int num2 = ToInt32D4(chars, offset, 4); int num3 = ToInt32D2(chars, offset + 5); int num4 = ToInt32D2(chars, offset + 8); int num5 = ToInt32D2(chars, offset + 11); int num6 = ToInt32D2(chars, offset + 14); int num7 = ToInt32D2(chars, offset + 17); if ((num2 | num3 | num4 | num5 | num6 | num7) < 0) { return false; } DateTimeKind kind = DateTimeKind.Unspecified; offset += 19; int num8 = 0; if (offset < num && chars[offset] == 46) { offset++; int num9 = offset; while (offset < num) { byte b = chars[offset]; if (b < 48 || b > 57) { break; } offset++; } int num10 = offset - num9; if (num10 < 1 || num10 > 7) { return false; } num8 = ToInt32D7(chars, num9, num10); if (num8 < 0) { return false; } for (int i = num10; i < 7; i++) { num8 *= 10; } } bool flag = false; int num11 = 0; int num12 = 0; if (offset < num) { byte b2 = chars[offset]; switch (b2) { case 90: offset++; kind = DateTimeKind.Utc; break; case 43: case 45: offset++; if (offset + 5 > num || chars[offset + 2] != 58) { return false; } kind = DateTimeKind.Utc; flag = true; num11 = ToInt32D2(chars, offset); num12 = ToInt32D2(chars, offset + 3); if ((num11 | num12) < 0) { return false; } if (b2 == 43) { num11 = -num11; num12 = -num12; } offset += 5; break; } } if (offset < num) { return false; } DateTime dateTime; try { dateTime = new DateTime(num2, num3, num4, num5, num6, num7, kind); } catch (ArgumentException) { return false; } if (num8 > 0) { dateTime = dateTime.AddTicks(num8); } if (flag) { try { TimeSpan timeSpan = new TimeSpan(num11, num12, 0); dateTime = (((num11 < 0 || !(dateTime < DateTime.MaxValue - timeSpan)) && (num11 >= 0 || !(dateTime > DateTime.MinValue - timeSpan))) ? dateTime.ToLocalTime().Add(timeSpan) : dateTime.Add(timeSpan).ToLocalTime()); } catch (ArgumentOutOfRangeException) { return false; } } result = dateTime; return true; } public static int ToChars(bool value, byte[] buffer, int offset) { if (value) { buffer[offset] = 116; buffer[offset + 1] = 114; buffer[offset + 2] = 117; buffer[offset + 3] = 101; return 4; } buffer[offset] = 102; buffer[offset + 1] = 97; buffer[offset + 2] = 108; buffer[offset + 3] = 115; buffer[offset + 4] = 101; return 5; } public static int ToCharsR(int value, byte[] chars, int offset) { int num = 0; if (value >= 0) { while (value >= 10) { int num2 = value / 10; num++; chars[--offset] = (byte)(48 + (value - num2 * 10)); value = num2; } chars[--offset] = (byte)(48 + value); return num + 1; } while (value <= -10) { int num3 = value / 10; num++; chars[--offset] = (byte)(48 - (value - num3 * 10)); value = num3; } chars[--offset] = (byte)(48 - value); chars[--offset] = 45; return num + 2; } public static int ToChars(int value, byte[] chars, int offset) { int num = ToCharsR(value, chars, offset + 16); Buffer.BlockCopy(chars, offset + 16 - num, chars, offset, num); return num; } public static int ToCharsR(long value, byte[] chars, int offset) { int num = 0; if (value >= 0) { while (value > int.MaxValue) { long num2 = value / 10; num++; chars[--offset] = (byte)(48 + (int)(value - num2 * 10)); value = num2; } } else { while (value < int.MinValue) { long num3 = value / 10; num++; chars[--offset] = (byte)(48 - (int)(value - num3 * 10)); value = num3; } } return num + ToCharsR((int)value, chars, offset); } public static int ToChars(long value, byte[] chars, int offset) { int num = ToCharsR(value, chars, offset + 32); Buffer.BlockCopy(chars, offset + 32 - num, chars, offset, num); return num; } [SecuritySafeCritical] private unsafe static bool IsNegativeZero(float value) { float num = -0f; return *(int*)(&value) == *(int*)(&num); } [SecuritySafeCritical] private unsafe static bool IsNegativeZero(double value) { double num = -0.0; return *(long*)(&value) == *(long*)(&num); } private static int ToInfinity(bool isNegative, byte[] buffer, int offset) { if (isNegative) { buffer[offset] = 45; buffer[offset + 1] = 73; buffer[offset + 2] = 78; buffer[offset + 3] = 70; return 4; } buffer[offset] = 73; buffer[offset + 1] = 78; buffer[offset + 2] = 70; return 3; } private static int ToZero(bool isNegative, byte[] buffer, int offset) { if (isNegative) { buffer[offset] = 45; buffer[offset + 1] = 48; return 2; } buffer[offset] = 48; return 1; } public static int ToChars(double value, byte[] buffer, int offset) { if (double.IsInfinity(value)) { return ToInfinity(double.IsNegativeInfinity(value), buffer, offset); } if (value == 0.0) { return ToZero(IsNegativeZero(value), buffer, offset); } return ToAsciiChars(value.ToString("R", NumberFormatInfo.InvariantInfo), buffer, offset); } public static int ToChars(float value, byte[] buffer, int offset) { if (float.IsInfinity(value)) { return ToInfinity(float.IsNegativeInfinity(value), buffer, offset); } if ((double)value == 0.0) { return ToZero(IsNegativeZero(value), buffer, offset); } return ToAsciiChars(value.ToString("R", NumberFormatInfo.InvariantInfo), buffer, offset); } public static int ToChars(decimal value, byte[] buffer, int offset) { return ToAsciiChars(value.ToString(null, NumberFormatInfo.InvariantInfo), buffer, offset); } public static int ToChars(ulong value, byte[] buffer, int offset) { return ToAsciiChars(value.ToString(null, NumberFormatInfo.InvariantInfo), buffer, offset); } private static int ToAsciiChars(string s, byte[] buffer, int offset) { for (int i = 0; i < s.Length; i++) { buffer[offset++] = (byte)s[i]; } return s.Length; } private static int ToCharsD2(int value, byte[] chars, int offset) { if (value < 10) { chars[offset] = 48; chars[offset + 1] = (byte)(48 + value); } else { int num = value / 10; chars[offset] = (byte)(48 + num); chars[offset + 1] = (byte)(48 + value - num * 10); } return 2; } private static int ToCharsD4(int value, byte[] chars, int offset) { ToCharsD2(value / 100, chars, offset); ToCharsD2(value % 100, chars, offset + 2); return 4; } private static int ToCharsD7(int value, byte[] chars, int offset) { int num = 7 - ToCharsR(value, chars, offset + 7); for (int i = 0; i < num; i++) { chars[offset + i] = 48; } int num2 = 7; while (num2 > 0 && chars[offset + num2 - 1] == 48) { num2--; } return num2; } public static int ToChars(DateTime value, byte[] chars, int offset) { int num = offset; offset += ToCharsD4(value.Year, chars, offset); chars[offset++] = 45; offset += ToCharsD2(value.Month, chars, offset); chars[offset++] = 45; offset += ToCharsD2(value.Day, chars, offset); chars[offset++] = 84; offset += ToCharsD2(value.Hour, chars, offset); chars[offset++] = 58; offset += ToCharsD2(value.Minute, chars, offset); chars[offset++] = 58; offset += ToCharsD2(value.Second, chars, offset); int num2 = (int)(value.Ticks % 10000000); if (num2 != 0) { chars[offset++] = 46; offset += ToCharsD7(num2, chars, offset); } switch (value.Kind) { case DateTimeKind.Local: { TimeSpan utcOffset = TimeZoneInfo.Local.GetUtcOffset(value); if (utcOffset.Ticks < 0) { chars[offset++] = 45; } else { chars[offset++] = 43; } offset += ToCharsD2(Math.Abs(utcOffset.Hours), chars, offset); chars[offset++] = 58; offset += ToCharsD2(Math.Abs(utcOffset.Minutes), chars, offset); break; } case DateTimeKind.Utc: chars[offset++] = 90; break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); case DateTimeKind.Unspecified: break; } return offset - num; } public static bool IsWhitespace(string s) { for (int i = 0; i < s.Length; i++) { if (!IsWhitespace(s[i])) { return false; } } return true; } public static bool IsWhitespace(char ch) { if (ch <= ' ') { if (ch != ' ' && ch != '\t' && ch != '\r') { return ch == '\n'; } return true; } return false; } public static string StripWhitespace(string s) { int num = s.Length; for (int i = 0; i < s.Length; i++) { if (IsWhitespace(s[i])) { num--; } } if (num == s.Length) { return s; } char[] array = new char[num]; num = 0; foreach (char c in s) { if (!IsWhitespace(c)) { array[num++] = c; } } return new string(array); } private static string Trim(string s) { int i; for (i = 0; i < s.Length && IsWhitespace(s[i]); i++) { } int num = s.Length; while (num > 0 && IsWhitespace(s[num - 1])) { num--; } if (i == 0 && num == s.Length) { return s; } if (num == 0) { return string.Empty; } return s.Substring(i, num - i); } } public class XmlDictionary : IXmlDictionary { private class EmptyDictionary : IXmlDictionary { public bool TryLookup(string value, out XmlDictionaryString result) { result = null; return false; } public bool TryLookup(int key, out XmlDictionaryString result) { result = null; return false; } public bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result) { result = null; return false; } } private static IXmlDictionary empty; private Dictionary lookup; private XmlDictionaryString[] strings; private int nextId; public static IXmlDictionary Empty { get { if (empty == null) { empty = new EmptyDictionary(); } return empty; } } public XmlDictionary() { lookup = new Dictionary(); strings = null; nextId = 0; } public XmlDictionary(int capacity) { lookup = new Dictionary(capacity); strings = new XmlDictionaryString[capacity]; nextId = 0; } public virtual XmlDictionaryString Add(string value) { if (!lookup.TryGetValue(value, out var value2)) { if (strings == null) { strings = new XmlDictionaryString[4]; } else if (nextId == strings.Length) { int num = nextId * 2; if (num == 0) { num = 4; } Array.Resize(ref strings, num); } value2 = new XmlDictionaryString(this, value, nextId); strings[nextId] = value2; lookup.Add(value, value2); nextId++; } return value2; } public virtual bool TryLookup(string value, out XmlDictionaryString result) { return lookup.TryGetValue(value, out result); } public virtual bool TryLookup(int key, out XmlDictionaryString result) { if (key < 0 || key >= nextId) { result = null; return false; } result = strings[key]; return true; } public virtual bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result) { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } if (value.Dictionary != this) { result = null; return false; } result = value; return true; } } public delegate void OnXmlDictionaryReaderClose(XmlDictionaryReader reader); public abstract class XmlDictionaryReader : XmlReader { private class XmlWrappedReader : XmlDictionaryReader, IXmlLineInfo { private XmlReader reader; private XmlNamespaceManager nsMgr; public override int AttributeCount => reader.AttributeCount; public override string BaseURI => reader.BaseURI; public override bool CanReadBinaryContent => reader.CanReadBinaryContent; public override bool CanReadValueChunk => reader.CanReadValueChunk; public override int Depth => reader.Depth; public override bool EOF => reader.EOF; public override bool HasValue => reader.HasValue; public override bool IsDefault => reader.IsDefault; public override bool IsEmptyElement => reader.IsEmptyElement; public override string LocalName => reader.LocalName; public override string Name => reader.Name; public override string NamespaceURI => reader.NamespaceURI; public override XmlNameTable NameTable => reader.NameTable; public override XmlNodeType NodeType => reader.NodeType; public override string Prefix => reader.Prefix; public override char QuoteChar => reader.QuoteChar; public override ReadState ReadState => reader.ReadState; public override string this[int index] => reader[index]; public override string this[string name] => reader[name]; public override string this[string name, string namespaceUri] => reader[name, namespaceUri]; public override string Value => reader.Value; public override string XmlLang => reader.XmlLang; public override XmlSpace XmlSpace => reader.XmlSpace; public override Type ValueType => reader.ValueType; public int LineNumber { get { if (!(reader is IXmlLineInfo xmlLineInfo)) { return 1; } return xmlLineInfo.LineNumber; } } public int LinePosition { get { if (!(reader is IXmlLineInfo xmlLineInfo)) { return 1; } return xmlLineInfo.LinePosition; } } public XmlWrappedReader(XmlReader reader, XmlNamespaceManager nsMgr) { this.reader = reader; this.nsMgr = nsMgr; } public override void Close() { reader.Close(); nsMgr = null; } public override string GetAttribute(int index) { return reader.GetAttribute(index); } public override string GetAttribute(string name) { return reader.GetAttribute(name); } public override string GetAttribute(string name, string namespaceUri) { return reader.GetAttribute(name, namespaceUri); } public override bool IsStartElement(string name) { return reader.IsStartElement(name); } public override bool IsStartElement(string localName, string namespaceUri) { return reader.IsStartElement(localName, namespaceUri); } public override string LookupNamespace(string namespaceUri) { return reader.LookupNamespace(namespaceUri); } public override void MoveToAttribute(int index) { reader.MoveToAttribute(index); } public override bool MoveToAttribute(string name) { return reader.MoveToAttribute(name); } public override bool MoveToAttribute(string name, string namespaceUri) { return reader.MoveToAttribute(name, namespaceUri); } public override bool MoveToElement() { return reader.MoveToElement(); } public override bool MoveToFirstAttribute() { return reader.MoveToFirstAttribute(); } public override bool MoveToNextAttribute() { return reader.MoveToNextAttribute(); } public override bool Read() { return reader.Read(); } public override bool ReadAttributeValue() { return reader.ReadAttributeValue(); } public override string ReadElementString(string name) { return reader.ReadElementString(name); } public override string ReadElementString(string localName, string namespaceUri) { return reader.ReadElementString(localName, namespaceUri); } public override string ReadInnerXml() { return reader.ReadInnerXml(); } public override string ReadOuterXml() { return reader.ReadOuterXml(); } public override void ReadStartElement(string name) { reader.ReadStartElement(name); } public override void ReadStartElement(string localName, string namespaceUri) { reader.ReadStartElement(localName, namespaceUri); } public override void ReadEndElement() { reader.ReadEndElement(); } public override string ReadString() { return reader.ReadString(); } public override void ResolveEntity() { reader.ResolveEntity(); } public override int ReadElementContentAsBase64(byte[] buffer, int offset, int count) { return reader.ReadElementContentAsBase64(buffer, offset, count); } public override int ReadContentAsBase64(byte[] buffer, int offset, int count) { return reader.ReadContentAsBase64(buffer, offset, count); } public override int ReadElementContentAsBinHex(byte[] buffer, int offset, int count) { return reader.ReadElementContentAsBinHex(buffer, offset, count); } public override int ReadContentAsBinHex(byte[] buffer, int offset, int count) { return reader.ReadContentAsBinHex(buffer, offset, count); } public override int ReadValueChunk(char[] chars, int offset, int count) { return reader.ReadValueChunk(chars, offset, count); } public override bool ReadContentAsBoolean() { return reader.ReadContentAsBoolean(); } public override DateTime ReadContentAsDateTime() { return reader.ReadContentAsDateTime(); } public override decimal ReadContentAsDecimal() { return (decimal)reader.ReadContentAs(typeof(decimal), null); } public override double ReadContentAsDouble() { return reader.ReadContentAsDouble(); } public override int ReadContentAsInt() { return reader.ReadContentAsInt(); } public override long ReadContentAsLong() { return reader.ReadContentAsLong(); } public override float ReadContentAsFloat() { return reader.ReadContentAsFloat(); } public override string ReadContentAsString() { return reader.ReadContentAsString(); } public override object ReadContentAs(Type type, IXmlNamespaceResolver namespaceResolver) { return reader.ReadContentAs(type, namespaceResolver); } public bool HasLineInfo() { if (!(reader is IXmlLineInfo xmlLineInfo)) { return false; } return xmlLineInfo.HasLineInfo(); } } internal const int MaxInitialArrayLength = 65535; public virtual bool CanCanonicalize => false; public virtual XmlDictionaryReaderQuotas Quotas => XmlDictionaryReaderQuotas.Max; public static XmlDictionaryReader CreateDictionaryReader(XmlReader reader) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } XmlDictionaryReader xmlDictionaryReader = reader as XmlDictionaryReader; if (xmlDictionaryReader == null) { xmlDictionaryReader = new XmlWrappedReader(reader, null); } return xmlDictionaryReader; } public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, XmlDictionaryReaderQuotas quotas) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); } return CreateBinaryReader(buffer, 0, buffer.Length, quotas); } public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, XmlDictionaryReaderQuotas quotas) { return CreateBinaryReader(buffer, offset, count, null, quotas); } public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas) { return CreateBinaryReader(buffer, offset, count, dictionary, quotas, null); } public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session) { return CreateBinaryReader(buffer, offset, count, dictionary, quotas, session, null); } public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose) { XmlBinaryReader xmlBinaryReader = new XmlBinaryReader(); xmlBinaryReader.SetInput(buffer, offset, count, dictionary, quotas, session, onClose); return xmlBinaryReader; } public static XmlDictionaryReader CreateBinaryReader(Stream stream, XmlDictionaryReaderQuotas quotas) { return CreateBinaryReader(stream, null, quotas); } public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas) { return CreateBinaryReader(stream, dictionary, quotas, null); } public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session) { return CreateBinaryReader(stream, dictionary, quotas, session, null); } public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose) { XmlBinaryReader xmlBinaryReader = new XmlBinaryReader(); xmlBinaryReader.SetInput(stream, dictionary, quotas, session, onClose); return xmlBinaryReader; } public static XmlDictionaryReader CreateTextReader(byte[] buffer, XmlDictionaryReaderQuotas quotas) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); } return CreateTextReader(buffer, 0, buffer.Length, quotas); } public static XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count, XmlDictionaryReaderQuotas quotas) { return CreateTextReader(buffer, offset, count, null, quotas, null); } public static XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) { XmlUTF8TextReader xmlUTF8TextReader = new XmlUTF8TextReader(); xmlUTF8TextReader.SetInput(buffer, offset, count, encoding, quotas, onClose); return xmlUTF8TextReader; } public static XmlDictionaryReader CreateTextReader(Stream stream, XmlDictionaryReaderQuotas quotas) { return CreateTextReader(stream, null, quotas, null); } public static XmlDictionaryReader CreateTextReader(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) { XmlUTF8TextReader xmlUTF8TextReader = new XmlUTF8TextReader(); xmlUTF8TextReader.SetInput(stream, encoding, quotas, onClose); return xmlUTF8TextReader; } public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas) { if (encoding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encoding"); } return CreateMtomReader(stream, new Encoding[1] { encoding }, quotas); } public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, XmlDictionaryReaderQuotas quotas) { return CreateMtomReader(stream, encodings, null, quotas); } public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas) { return CreateMtomReader(stream, encodings, contentType, quotas, int.MaxValue, null); } public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose) { XmlMtomReader xmlMtomReader = new XmlMtomReader(); xmlMtomReader.SetInput(stream, encodings, contentType, quotas, maxBufferSize, onClose); return xmlMtomReader; } public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas) { if (encoding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encoding"); } return CreateMtomReader(buffer, offset, count, new Encoding[1] { encoding }, quotas); } public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, XmlDictionaryReaderQuotas quotas) { return CreateMtomReader(buffer, offset, count, encodings, null, quotas); } public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas) { return CreateMtomReader(buffer, offset, count, encodings, contentType, quotas, int.MaxValue, null); } public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose) { XmlMtomReader xmlMtomReader = new XmlMtomReader(); xmlMtomReader.SetInput(buffer, offset, count, encodings, contentType, quotas, maxBufferSize, onClose); return xmlMtomReader; } public virtual void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } public virtual void EndCanonicalization() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } public virtual void MoveToStartElement() { if (!IsStartElement()) { XmlExceptionHelper.ThrowStartElementExpected(this); } } public virtual void MoveToStartElement(string name) { if (!IsStartElement(name)) { XmlExceptionHelper.ThrowStartElementExpected(this, name); } } public virtual void MoveToStartElement(string localName, string namespaceUri) { if (!IsStartElement(localName, namespaceUri)) { XmlExceptionHelper.ThrowStartElementExpected(this, localName, namespaceUri); } } public virtual void MoveToStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { if (!IsStartElement(localName, namespaceUri)) { XmlExceptionHelper.ThrowStartElementExpected(this, localName, namespaceUri); } } public virtual bool IsLocalName(string localName) { return LocalName == localName; } public virtual bool IsLocalName(XmlDictionaryString localName) { if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localName"); } return IsLocalName(localName.Value); } public virtual bool IsNamespaceUri(string namespaceUri) { if (namespaceUri == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri"); } return NamespaceURI == namespaceUri; } public virtual bool IsNamespaceUri(XmlDictionaryString namespaceUri) { if (namespaceUri == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri"); } return IsNamespaceUri(namespaceUri.Value); } public virtual void ReadFullStartElement() { MoveToStartElement(); if (IsEmptyElement) { XmlExceptionHelper.ThrowFullStartElementExpected(this); } Read(); } public virtual void ReadFullStartElement(string name) { MoveToStartElement(name); if (IsEmptyElement) { XmlExceptionHelper.ThrowFullStartElementExpected(this, name); } Read(); } public virtual void ReadFullStartElement(string localName, string namespaceUri) { MoveToStartElement(localName, namespaceUri); if (IsEmptyElement) { XmlExceptionHelper.ThrowFullStartElementExpected(this, localName, namespaceUri); } Read(); } public virtual void ReadFullStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { MoveToStartElement(localName, namespaceUri); if (IsEmptyElement) { XmlExceptionHelper.ThrowFullStartElementExpected(this, localName, namespaceUri); } Read(); } public virtual void ReadStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { MoveToStartElement(localName, namespaceUri); Read(); } public virtual bool IsStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return IsStartElement(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri)); } public virtual int IndexOfLocalName(string[] localNames, string namespaceUri) { if (localNames == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localNames"); } if (namespaceUri == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri"); } if (NamespaceURI == namespaceUri) { string localName = LocalName; for (int i = 0; i < localNames.Length; i++) { string text = localNames[i]; if (text == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i)); } if (localName == text) { return i; } } } return -1; } public virtual int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictionaryString namespaceUri) { if (localNames == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localNames"); } if (namespaceUri == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri"); } if (NamespaceURI == namespaceUri.Value) { string localName = LocalName; for (int i = 0; i < localNames.Length; i++) { XmlDictionaryString xmlDictionaryString = localNames[i]; if (xmlDictionaryString == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i)); } if (localName == xmlDictionaryString.Value) { return i; } } } return -1; } public virtual string GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return GetAttribute(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri)); } public virtual bool TryGetBase64ContentLength(out int length) { length = 0; return false; } public virtual int ReadValueAsBase64(byte[] buffer, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } public virtual byte[] ReadContentAsBase64() { return ReadContentAsBase64(Quotas.MaxArrayLength, 65535); } internal byte[] ReadContentAsBase64(int maxByteArrayContentLength, int maxInitialCount) { if (TryGetBase64ContentLength(out var length)) { if (length > maxByteArrayContentLength) { XmlExceptionHelper.ThrowMaxArrayLengthExceeded(this, maxByteArrayContentLength); } if (length <= maxInitialCount) { byte[] array = new byte[length]; int num; for (int i = 0; i < length; i += num) { num = ReadContentAsBase64(array, i, length - i); if (num == 0) { XmlExceptionHelper.ThrowBase64DataExpected(this); } } return array; } } return ReadContentAsBytes(base64: true, maxByteArrayContentLength); } public override string ReadContentAsString() { return ReadContentAsString(Quotas.MaxStringContentLength); } protected string ReadContentAsString(int maxStringContentLength) { StringBuilder stringBuilder = null; string text = string.Empty; bool flag = false; while (true) { switch (NodeType) { case XmlNodeType.Attribute: text = Value; break; case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: { string value = Value; if (text.Length == 0) { text = value; break; } if (stringBuilder == null) { stringBuilder = new StringBuilder(text); } if (stringBuilder.Length > maxStringContentLength - value.Length) { XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength); } stringBuilder.Append(value); break; } case XmlNodeType.EntityReference: if (CanResolveEntity) { ResolveEntity(); break; } goto default; default: flag = true; break; case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.EndEntity: break; } if (flag) { break; } if (AttributeCount != 0) { ReadAttributeValue(); } else { Read(); } } if (stringBuilder != null) { text = stringBuilder.ToString(); } if (text.Length > maxStringContentLength) { XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength); } return text; } public override string ReadString() { return ReadString(Quotas.MaxStringContentLength); } protected string ReadString(int maxStringContentLength) { if (ReadState != ReadState.Interactive) { return string.Empty; } if (NodeType != XmlNodeType.Element) { MoveToElement(); } if (NodeType == XmlNodeType.Element) { if (IsEmptyElement) { return string.Empty; } if (!Read()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("The reader cannot be advanced."))); } if (NodeType == XmlNodeType.EndElement) { return string.Empty; } } StringBuilder stringBuilder = null; string text = string.Empty; while (IsTextNode(NodeType)) { string value = Value; if (text.Length == 0) { text = value; } else { if (stringBuilder == null) { stringBuilder = new StringBuilder(text); } if (stringBuilder.Length > maxStringContentLength - value.Length) { XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength); } stringBuilder.Append(value); } if (!Read()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("The reader cannot be advanced."))); } } if (stringBuilder != null) { text = stringBuilder.ToString(); } if (text.Length > maxStringContentLength) { XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength); } return text; } public virtual byte[] ReadContentAsBinHex() { return ReadContentAsBinHex(Quotas.MaxArrayLength); } protected byte[] ReadContentAsBinHex(int maxByteArrayContentLength) { return ReadContentAsBytes(base64: false, maxByteArrayContentLength); } private byte[] ReadContentAsBytes(bool base64, int maxByteArrayContentLength) { byte[][] array = new byte[32][]; int num = 384; int num2 = 0; int num3 = 0; byte[] array2; while (true) { array2 = new byte[num]; array[num2++] = array2; int i; int num4; for (i = 0; i < array2.Length; i += num4) { num4 = ((!base64) ? ReadContentAsBinHex(array2, i, array2.Length - i) : ReadContentAsBase64(array2, i, array2.Length - i)); if (num4 == 0) { break; } } if (num3 > maxByteArrayContentLength - i) { XmlExceptionHelper.ThrowMaxArrayLengthExceeded(this, maxByteArrayContentLength); } num3 += i; if (i < array2.Length) { break; } num *= 2; } array2 = new byte[num3]; int num5 = 0; for (int j = 0; j < num2 - 1; j++) { Buffer.BlockCopy(array[j], 0, array2, num5, array[j].Length); num5 += array[j].Length; } Buffer.BlockCopy(array[num2 - 1], 0, array2, num5, num3 - num5); return array2; } protected bool IsTextNode(XmlNodeType nodeType) { if (nodeType != XmlNodeType.Text && nodeType != XmlNodeType.Whitespace && nodeType != XmlNodeType.SignificantWhitespace && nodeType != XmlNodeType.CDATA) { return nodeType == XmlNodeType.Attribute; } return true; } public virtual int ReadContentAsChars(char[] chars, int offset, int count) { int num = 0; while (true) { XmlNodeType nodeType = NodeType; if (nodeType == XmlNodeType.Element || nodeType == XmlNodeType.EndElement) { break; } if (IsTextNode(nodeType)) { num = ReadValueChunk(chars, offset, count); if (num > 0 || nodeType == XmlNodeType.Attribute || !Read()) { break; } } else if (!Read()) { break; } } return num; } public override object ReadContentAs(Type type, IXmlNamespaceResolver namespaceResolver) { if (type == typeof(Guid[])) { string[] array = (string[])ReadContentAs(typeof(string[]), namespaceResolver); Guid[] array2 = new Guid[array.Length]; for (int i = 0; i < array.Length; i++) { array2[i] = XmlConverter.ToGuid(array[i]); } return array2; } if (type == typeof(UniqueId[])) { string[] array3 = (string[])ReadContentAs(typeof(string[]), namespaceResolver); UniqueId[] array4 = new UniqueId[array3.Length]; for (int j = 0; j < array3.Length; j++) { array4[j] = XmlConverter.ToUniqueId(array3[j]); } return array4; } return base.ReadContentAs(type, namespaceResolver); } public virtual string ReadContentAsString(string[] strings, out int index) { if (strings == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("strings"); } string text = ReadContentAsString(); index = -1; for (int i = 0; i < strings.Length; i++) { string text2 = strings[i]; if (text2 == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "strings[{0}]", i)); } if (text2 == text) { index = i; return text2; } } return text; } public virtual string ReadContentAsString(XmlDictionaryString[] strings, out int index) { if (strings == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("strings"); } string text = ReadContentAsString(); index = -1; for (int i = 0; i < strings.Length; i++) { XmlDictionaryString xmlDictionaryString = strings[i]; if (xmlDictionaryString == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "strings[{0}]", i)); } if (xmlDictionaryString.Value == text) { index = i; return xmlDictionaryString.Value; } } return text; } public override decimal ReadContentAsDecimal() { return XmlConverter.ToDecimal(ReadContentAsString()); } public override float ReadContentAsFloat() { return XmlConverter.ToSingle(ReadContentAsString()); } public virtual UniqueId ReadContentAsUniqueId() { return XmlConverter.ToUniqueId(ReadContentAsString()); } public virtual Guid ReadContentAsGuid() { return XmlConverter.ToGuid(ReadContentAsString()); } public virtual TimeSpan ReadContentAsTimeSpan() { return XmlConverter.ToTimeSpan(ReadContentAsString()); } public virtual void ReadContentAsQualifiedName(out string localName, out string namespaceUri) { XmlConverter.ToQualifiedName(ReadContentAsString(), out var prefix, out localName); namespaceUri = LookupNamespace(prefix); if (namespaceUri == null) { XmlExceptionHelper.ThrowUndefinedPrefix(this, prefix); } } public override string ReadElementContentAsString() { string result; if (IsStartElement() && IsEmptyElement) { Read(); result = string.Empty; } else { ReadStartElement(); result = ReadContentAsString(); ReadEndElement(); } return result; } public override bool ReadElementContentAsBoolean() { bool result; if (IsStartElement() && IsEmptyElement) { Read(); result = XmlConverter.ToBoolean(string.Empty); } else { ReadStartElement(); result = ReadContentAsBoolean(); ReadEndElement(); } return result; } public override int ReadElementContentAsInt() { int result; if (IsStartElement() && IsEmptyElement) { Read(); result = XmlConverter.ToInt32(string.Empty); } else { ReadStartElement(); result = ReadContentAsInt(); ReadEndElement(); } return result; } public override long ReadElementContentAsLong() { long result; if (IsStartElement() && IsEmptyElement) { Read(); result = XmlConverter.ToInt64(string.Empty); } else { ReadStartElement(); result = ReadContentAsLong(); ReadEndElement(); } return result; } public override float ReadElementContentAsFloat() { float result; if (IsStartElement() && IsEmptyElement) { Read(); result = XmlConverter.ToSingle(string.Empty); } else { ReadStartElement(); result = ReadContentAsFloat(); ReadEndElement(); } return result; } public override double ReadElementContentAsDouble() { double result; if (IsStartElement() && IsEmptyElement) { Read(); result = XmlConverter.ToDouble(string.Empty); } else { ReadStartElement(); result = ReadContentAsDouble(); ReadEndElement(); } return result; } public override decimal ReadElementContentAsDecimal() { decimal result; if (IsStartElement() && IsEmptyElement) { Read(); result = XmlConverter.ToDecimal(string.Empty); } else { ReadStartElement(); result = ReadContentAsDecimal(); ReadEndElement(); } return result; } public override DateTime ReadElementContentAsDateTime() { DateTime result; if (IsStartElement() && IsEmptyElement) { Read(); try { result = DateTime.Parse(string.Empty, NumberFormatInfo.InvariantInfo); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "DateTime", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "DateTime", exception2)); } } else { ReadStartElement(); result = ReadContentAsDateTime(); ReadEndElement(); } return result; } public virtual UniqueId ReadElementContentAsUniqueId() { UniqueId result; if (IsStartElement() && IsEmptyElement) { Read(); try { result = new UniqueId(string.Empty); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "UniqueId", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "UniqueId", exception2)); } } else { ReadStartElement(); result = ReadContentAsUniqueId(); ReadEndElement(); } return result; } public virtual Guid ReadElementContentAsGuid() { Guid result; if (IsStartElement() && IsEmptyElement) { Read(); try { result = Guid.Empty; } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "Guid", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "Guid", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "Guid", exception3)); } } else { ReadStartElement(); result = ReadContentAsGuid(); ReadEndElement(); } return result; } public virtual TimeSpan ReadElementContentAsTimeSpan() { TimeSpan result; if (IsStartElement() && IsEmptyElement) { Read(); result = XmlConverter.ToTimeSpan(string.Empty); } else { ReadStartElement(); result = ReadContentAsTimeSpan(); ReadEndElement(); } return result; } public virtual byte[] ReadElementContentAsBase64() { byte[] result; if (IsStartElement() && IsEmptyElement) { Read(); result = new byte[0]; } else { ReadStartElement(); result = ReadContentAsBase64(); ReadEndElement(); } return result; } public virtual byte[] ReadElementContentAsBinHex() { byte[] result; if (IsStartElement() && IsEmptyElement) { Read(); result = new byte[0]; } else { ReadStartElement(); result = ReadContentAsBinHex(); ReadEndElement(); } return result; } public virtual void GetNonAtomizedNames(out string localName, out string namespaceUri) { localName = LocalName; namespaceUri = NamespaceURI; } public virtual bool TryGetLocalNameAsDictionaryString(out XmlDictionaryString localName) { localName = null; return false; } public virtual bool TryGetNamespaceUriAsDictionaryString(out XmlDictionaryString namespaceUri) { namespaceUri = null; return false; } public virtual bool TryGetValueAsDictionaryString(out XmlDictionaryString value) { value = null; return false; } private void CheckArray(Array array, int offset, int count) { if (array == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("array")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > array.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", array.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > array.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", array.Length - offset))); } } public virtual bool IsStartArray(out Type type) { type = null; return false; } public virtual bool TryGetArrayLength(out int count) { count = 0; return false; } public virtual bool[] ReadBooleanArray(string localName, string namespaceUri) { return BooleanArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual bool[] ReadBooleanArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return BooleanArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, bool[] array, int offset, int count) { CheckArray(array, offset, count); int i; for (i = 0; i < count; i++) { if (!IsStartElement(localName, namespaceUri)) { break; } array[offset + i] = ReadElementContentAsBoolean(); } return i; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } public virtual short[] ReadInt16Array(string localName, string namespaceUri) { return Int16ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual short[] ReadInt16Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return Int16ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, short[] array, int offset, int count) { CheckArray(array, offset, count); int i; for (i = 0; i < count; i++) { if (!IsStartElement(localName, namespaceUri)) { break; } int num = ReadElementContentAsInt(); if (num < -32768 || num > 32767) { XmlExceptionHelper.ThrowConversionOverflow(this, num.ToString(NumberFormatInfo.CurrentInfo), "Int16"); } array[offset + i] = (short)num; } return i; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } public virtual int[] ReadInt32Array(string localName, string namespaceUri) { return Int32ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int[] ReadInt32Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return Int32ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, int[] array, int offset, int count) { CheckArray(array, offset, count); int i; for (i = 0; i < count; i++) { if (!IsStartElement(localName, namespaceUri)) { break; } array[offset + i] = ReadElementContentAsInt(); } return i; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } public virtual long[] ReadInt64Array(string localName, string namespaceUri) { return Int64ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual long[] ReadInt64Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return Int64ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, long[] array, int offset, int count) { CheckArray(array, offset, count); int i; for (i = 0; i < count; i++) { if (!IsStartElement(localName, namespaceUri)) { break; } array[offset + i] = ReadElementContentAsLong(); } return i; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } public virtual float[] ReadSingleArray(string localName, string namespaceUri) { return SingleArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual float[] ReadSingleArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return SingleArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, float[] array, int offset, int count) { CheckArray(array, offset, count); int i; for (i = 0; i < count; i++) { if (!IsStartElement(localName, namespaceUri)) { break; } array[offset + i] = ReadElementContentAsFloat(); } return i; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } public virtual double[] ReadDoubleArray(string localName, string namespaceUri) { return DoubleArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual double[] ReadDoubleArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return DoubleArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, double[] array, int offset, int count) { CheckArray(array, offset, count); int i; for (i = 0; i < count; i++) { if (!IsStartElement(localName, namespaceUri)) { break; } array[offset + i] = ReadElementContentAsDouble(); } return i; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } public virtual decimal[] ReadDecimalArray(string localName, string namespaceUri) { return DecimalArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual decimal[] ReadDecimalArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return DecimalArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, decimal[] array, int offset, int count) { CheckArray(array, offset, count); int i; for (i = 0; i < count; i++) { if (!IsStartElement(localName, namespaceUri)) { break; } array[offset + i] = ReadElementContentAsDecimal(); } return i; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } public virtual DateTime[] ReadDateTimeArray(string localName, string namespaceUri) { return DateTimeArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual DateTime[] ReadDateTimeArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return DateTimeArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, DateTime[] array, int offset, int count) { CheckArray(array, offset, count); int i; for (i = 0; i < count; i++) { if (!IsStartElement(localName, namespaceUri)) { break; } array[offset + i] = ReadElementContentAsDateTime(); } return i; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } public virtual Guid[] ReadGuidArray(string localName, string namespaceUri) { return GuidArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual Guid[] ReadGuidArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return GuidArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, Guid[] array, int offset, int count) { CheckArray(array, offset, count); int i; for (i = 0; i < count; i++) { if (!IsStartElement(localName, namespaceUri)) { break; } array[offset + i] = ReadElementContentAsGuid(); } return i; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } public virtual TimeSpan[] ReadTimeSpanArray(string localName, string namespaceUri) { return TimeSpanArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual TimeSpan[] ReadTimeSpanArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return TimeSpanArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength); } public virtual int ReadArray(string localName, string namespaceUri, TimeSpan[] array, int offset, int count) { CheckArray(array, offset, count); int i; for (i = 0; i < count; i++) { if (!IsStartElement(localName, namespaceUri)) { break; } array[offset + i] = ReadElementContentAsTimeSpan(); } return i; } public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) { return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } } [Flags] public enum XmlDictionaryReaderQuotaTypes { MaxDepth = 1, MaxStringContentLength = 2, MaxArrayLength = 4, MaxBytesPerRead = 8, MaxNameTableCharCount = 0x10 } public sealed class XmlDictionaryReaderQuotas { private bool readOnly; private int maxStringContentLength; private int maxArrayLength; private int maxDepth; private int maxNameTableCharCount; private int maxBytesPerRead; private XmlDictionaryReaderQuotaTypes modifiedQuotas; private const int DefaultMaxDepth = 32; private const int DefaultMaxStringContentLength = 8192; private const int DefaultMaxArrayLength = 16384; private const int DefaultMaxBytesPerRead = 4096; private const int DefaultMaxNameTableCharCount = 16384; private static XmlDictionaryReaderQuotas defaultQuota = new XmlDictionaryReaderQuotas(32, 8192, 16384, 4096, 16384, (XmlDictionaryReaderQuotaTypes)0); private static XmlDictionaryReaderQuotas maxQuota = new XmlDictionaryReaderQuotas(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, XmlDictionaryReaderQuotaTypes.MaxDepth | XmlDictionaryReaderQuotaTypes.MaxStringContentLength | XmlDictionaryReaderQuotaTypes.MaxArrayLength | XmlDictionaryReaderQuotaTypes.MaxBytesPerRead | XmlDictionaryReaderQuotaTypes.MaxNameTableCharCount); public static XmlDictionaryReaderQuotas Max => maxQuota; [DefaultValue(8192)] public int MaxStringContentLength { get { return maxStringContentLength; } set { if (readOnly) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("The '{0}' quota is readonly.", "MaxStringContentLength"))); } if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Quota must be a positive value."), "value")); } maxStringContentLength = value; modifiedQuotas |= XmlDictionaryReaderQuotaTypes.MaxStringContentLength; } } [DefaultValue(16384)] public int MaxArrayLength { get { return maxArrayLength; } set { if (readOnly) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("The '{0}' quota is readonly.", "MaxArrayLength"))); } if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Quota must be a positive value."), "value")); } maxArrayLength = value; modifiedQuotas |= XmlDictionaryReaderQuotaTypes.MaxArrayLength; } } [DefaultValue(4096)] public int MaxBytesPerRead { get { return maxBytesPerRead; } set { if (readOnly) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("The '{0}' quota is readonly.", "MaxBytesPerRead"))); } if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Quota must be a positive value."), "value")); } maxBytesPerRead = value; modifiedQuotas |= XmlDictionaryReaderQuotaTypes.MaxBytesPerRead; } } [DefaultValue(32)] public int MaxDepth { get { return maxDepth; } set { if (readOnly) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("The '{0}' quota is readonly.", "MaxDepth"))); } if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Quota must be a positive value."), "value")); } maxDepth = value; modifiedQuotas |= XmlDictionaryReaderQuotaTypes.MaxDepth; } } [DefaultValue(16384)] public int MaxNameTableCharCount { get { return maxNameTableCharCount; } set { if (readOnly) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("The '{0}' quota is readonly.", "MaxNameTableCharCount"))); } if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Quota must be a positive value."), "value")); } maxNameTableCharCount = value; modifiedQuotas |= XmlDictionaryReaderQuotaTypes.MaxNameTableCharCount; } } public XmlDictionaryReaderQuotaTypes ModifiedQuotas => modifiedQuotas; public XmlDictionaryReaderQuotas() { defaultQuota.CopyTo(this); } private XmlDictionaryReaderQuotas(int maxDepth, int maxStringContentLength, int maxArrayLength, int maxBytesPerRead, int maxNameTableCharCount, XmlDictionaryReaderQuotaTypes modifiedQuotas) { this.maxDepth = maxDepth; this.maxStringContentLength = maxStringContentLength; this.maxArrayLength = maxArrayLength; this.maxBytesPerRead = maxBytesPerRead; this.maxNameTableCharCount = maxNameTableCharCount; this.modifiedQuotas = modifiedQuotas; MakeReadOnly(); } public void CopyTo(XmlDictionaryReaderQuotas quotas) { if (quotas == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("quotas")); } if (quotas.readOnly) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("Cannot copy XmlDictionaryReaderQuotas. Target is readonly."))); } InternalCopyTo(quotas); } internal void InternalCopyTo(XmlDictionaryReaderQuotas quotas) { quotas.maxStringContentLength = maxStringContentLength; quotas.maxArrayLength = maxArrayLength; quotas.maxDepth = maxDepth; quotas.maxNameTableCharCount = maxNameTableCharCount; quotas.maxBytesPerRead = maxBytesPerRead; quotas.modifiedQuotas = modifiedQuotas; } internal void MakeReadOnly() { readOnly = true; } } public class XmlDictionaryString { private class EmptyStringDictionary : IXmlDictionary { private XmlDictionaryString empty; public XmlDictionaryString EmptyString => empty; public EmptyStringDictionary() { empty = new XmlDictionaryString(this, string.Empty, 0); } public bool TryLookup(string value, out XmlDictionaryString result) { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } if (value.Length == 0) { result = empty; return true; } result = null; return false; } public bool TryLookup(int key, out XmlDictionaryString result) { if (key == 0) { result = empty; return true; } result = null; return false; } public bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result) { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } if (value.Dictionary != this) { result = null; return false; } result = value; return true; } } internal const int MinKey = 0; internal const int MaxKey = 536870911; private IXmlDictionary dictionary; private string value; private int key; private byte[] buffer; private static EmptyStringDictionary emptyStringDictionary = new EmptyStringDictionary(); public static XmlDictionaryString Empty => emptyStringDictionary.EmptyString; public IXmlDictionary Dictionary => dictionary; public int Key => key; public string Value => value; public XmlDictionaryString(IXmlDictionary dictionary, string value, int key) { if (dictionary == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("dictionary")); } if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } if (key < 0 || key > 536870911) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("key", System.Runtime.Serialization.SR.GetString("The value of this argument must fall within the range {0} to {1}.", 0, 536870911))); } this.dictionary = dictionary; this.value = value; this.key = key; } internal static string GetString(XmlDictionaryString s) { return s?.Value; } internal byte[] ToUTF8() { if (buffer == null) { buffer = Encoding.UTF8.GetBytes(value); } return buffer; } public override string ToString() { return value; } } public abstract class XmlDictionaryWriter : XmlWriter { private class WriteValueFastAsyncResult : AsyncResult { private enum Operation { Read, Write, Complete } private bool completed; private int blockSize; private byte[] block; private int bytesRead; private Stream stream; private Operation nextOperation; private IStreamProvider streamProvider; private XmlDictionaryWriter writer; private AsyncEventArgs writerAsyncState; private XmlWriteBase64AsyncArguments writerAsyncArgs; private static AsyncCallback onReadComplete = Fx.ThunkCallback((AsyncCallback)OnReadComplete); private static AsyncEventArgsCallback onWriteComplete; public WriteValueFastAsyncResult(XmlDictionaryWriter writer, IStreamProvider value, AsyncCallback callback, object state) : base(callback, state) { streamProvider = value; this.writer = writer; stream = value.GetStream(); if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Stream returned by IStreamProvider cannot be null."))); } blockSize = 256; bytesRead = 0; block = new byte[blockSize]; nextOperation = Operation.Read; ContinueWork(completedSynchronously: true); } private void CompleteAndReleaseStream(bool completedSynchronously, Exception completionException = null) { if (completionException == null) { streamProvider.ReleaseStream(stream); stream = null; } ((AsyncResult)this).Complete(completedSynchronously, completionException); } private void ContinueWork(bool completedSynchronously, Exception completionException = null) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Invalid comparison between Unknown and I4 //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Invalid comparison between Unknown and I4 try { while (true) { if (nextOperation == Operation.Read) { if ((int)ReadAsync() != 1) { return; } } else if (nextOperation == Operation.Write) { if ((int)WriteAsync() != 1) { return; } } else if (nextOperation == Operation.Complete) { break; } } } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } if (completedSynchronously) { throw; } if (completionException == null) { completionException = ex; } } if (!completed) { completed = true; CompleteAndReleaseStream(completedSynchronously, completionException); } } private AsyncCompletionResult ReadAsync() { IAsyncResult asyncResult = stream.BeginRead(block, 0, blockSize, onReadComplete, this); if (asyncResult.CompletedSynchronously) { HandleReadComplete(asyncResult); return (AsyncCompletionResult)1; } return (AsyncCompletionResult)0; } private void HandleReadComplete(IAsyncResult result) { bytesRead = stream.EndRead(result); if (bytesRead > 0) { nextOperation = Operation.Write; } else { nextOperation = Operation.Complete; } } private static void OnReadComplete(IAsyncResult result) { if (result.CompletedSynchronously) { return; } Exception completionException = null; WriteValueFastAsyncResult writeValueFastAsyncResult = (WriteValueFastAsyncResult)result.AsyncState; bool flag = false; try { writeValueFastAsyncResult.HandleReadComplete(result); flag = true; } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } completionException = ex; } if (!flag) { writeValueFastAsyncResult.nextOperation = Operation.Complete; } writeValueFastAsyncResult.ContinueWork(completedSynchronously: false, completionException); } private AsyncCompletionResult WriteAsync() { //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Invalid comparison between Unknown and I4 //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown if (writerAsyncState == null) { writerAsyncArgs = new XmlWriteBase64AsyncArguments(); writerAsyncState = new AsyncEventArgs(); } if (onWriteComplete == null) { onWriteComplete = new AsyncEventArgsCallback(OnWriteComplete); } writerAsyncArgs.Buffer = block; writerAsyncArgs.Offset = 0; writerAsyncArgs.Count = bytesRead; writerAsyncState.Set(onWriteComplete, writerAsyncArgs, (object)this); if ((int)writer.WriteBase64Async(writerAsyncState) == 1) { HandleWriteComplete(); ((AsyncEventArgs)writerAsyncState).Complete(true); return (AsyncCompletionResult)1; } return (AsyncCompletionResult)0; } private void HandleWriteComplete() { nextOperation = Operation.Read; if (blockSize < 65536 && bytesRead == blockSize) { blockSize *= 16; block = new byte[blockSize]; } } private static void OnWriteComplete(IAsyncEventArgs asyncState) { WriteValueFastAsyncResult writeValueFastAsyncResult = (WriteValueFastAsyncResult)asyncState.AsyncState; Exception completionException = null; bool flag = false; try { if (asyncState.Exception != null) { completionException = asyncState.Exception; } else { writeValueFastAsyncResult.HandleWriteComplete(); flag = true; } } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } completionException = ex; } if (!flag) { writeValueFastAsyncResult.nextOperation = Operation.Complete; } writeValueFastAsyncResult.ContinueWork(completedSynchronously: false, completionException); } internal static void End(IAsyncResult result) { AsyncResult.End(result); } } private class WriteValueAsyncResult : AsyncResult { private enum Operation { Read, Write } private int blockSize; private byte[] block; private int bytesRead; private Stream stream; private Operation operation; private IStreamProvider streamProvider; private XmlDictionaryWriter writer; private Func writeBlockHandler; private static Func handleWriteBlock = HandleWriteBlock; private static Func handleWriteBlockAsync = HandleWriteBlockAsync; private static AsyncCallback onContinueWork = Fx.ThunkCallback((AsyncCallback)OnContinueWork); public WriteValueAsyncResult(XmlDictionaryWriter writer, IStreamProvider value, AsyncCallback callback, object state) : base(callback, state) { streamProvider = value; this.writer = writer; writeBlockHandler = ((this.writer.Settings != null && this.writer.Settings.Async) ? handleWriteBlockAsync : handleWriteBlock); stream = value.GetStream(); if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Stream returned by IStreamProvider cannot be null."))); } blockSize = 256; bytesRead = 0; block = new byte[blockSize]; if (ContinueWork(null)) { CompleteAndReleaseStream(completedSynchronously: true, null); } } private void AdjustBlockSize() { if (blockSize < 65536 && bytesRead == blockSize) { blockSize *= 16; block = new byte[blockSize]; } } private void CompleteAndReleaseStream(bool completedSynchronously, Exception completionException) { if (completionException == null) { streamProvider.ReleaseStream(stream); stream = null; } ((AsyncResult)this).Complete(completedSynchronously, completionException); } private bool ContinueWork(IAsyncResult result) { while (true) { if (operation == Operation.Read) { if (!HandleReadBlock(result)) { return false; } if (bytesRead <= 0) { return true; } operation = Operation.Write; } else { if (!writeBlockHandler(result, this)) { break; } AdjustBlockSize(); operation = Operation.Read; } result = null; } return false; } private bool HandleReadBlock(IAsyncResult result) { if (result == null) { result = stream.BeginRead(block, 0, blockSize, onContinueWork, this); if (!result.CompletedSynchronously) { return false; } } bytesRead = stream.EndRead(result); return true; } private static bool HandleWriteBlock(IAsyncResult result, WriteValueAsyncResult thisPtr) { if (result == null) { result = thisPtr.writer.BeginWriteBase64(thisPtr.block, 0, thisPtr.bytesRead, onContinueWork, thisPtr); if (!result.CompletedSynchronously) { return false; } } thisPtr.writer.EndWriteBase64(result); return true; } private static bool HandleWriteBlockAsync(IAsyncResult result, WriteValueAsyncResult thisPtr) { Task task = (Task)result; if (task == null) { task = thisPtr.writer.WriteBase64Async(thisPtr.block, 0, thisPtr.bytesRead); TaskExtensions.AsAsyncResult(task, onContinueWork, (object)thisPtr); return false; } task.GetAwaiter().GetResult(); return true; } private static void OnContinueWork(IAsyncResult result) { if (result.CompletedSynchronously && !(result is Task)) { return; } Exception completionException = null; WriteValueAsyncResult writeValueAsyncResult = (WriteValueAsyncResult)result.AsyncState; bool flag = false; try { flag = writeValueAsyncResult.ContinueWork(result); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } flag = true; completionException = ex; } if (flag) { writeValueAsyncResult.CompleteAndReleaseStream(completedSynchronously: false, completionException); } } public static void End(IAsyncResult result) { AsyncResult.End(result); } } private class WriteBase64AsyncResult : ScheduleActionItemAsyncResult { private byte[] buffer; private int index; private int count; private XmlDictionaryWriter writer; public WriteBase64AsyncResult(byte[] buffer, int index, int count, XmlDictionaryWriter writer, AsyncCallback callback, object state) : base(callback, state) { this.buffer = buffer; this.index = index; this.count = count; this.writer = writer; ((ScheduleActionItemAsyncResult)this).Schedule(); } protected override void OnDoWork() { writer.WriteBase64(buffer, index, count); } } private class XmlWrappedWriter : XmlDictionaryWriter { private XmlWriter writer; private int depth; private int prefix; public override WriteState WriteState => writer.WriteState; public override string XmlLang => writer.XmlLang; public override XmlSpace XmlSpace => writer.XmlSpace; public XmlWrappedWriter(XmlWriter writer) { this.writer = writer; depth = 0; } public override void Close() { writer.Close(); } public override void Flush() { writer.Flush(); } public override string LookupPrefix(string namespaceUri) { return writer.LookupPrefix(namespaceUri); } public override void WriteAttributes(XmlReader reader, bool defattr) { writer.WriteAttributes(reader, defattr); } public override void WriteBase64(byte[] buffer, int index, int count) { writer.WriteBase64(buffer, index, count); } public override void WriteBinHex(byte[] buffer, int index, int count) { writer.WriteBinHex(buffer, index, count); } public override void WriteCData(string text) { writer.WriteCData(text); } public override void WriteCharEntity(char ch) { writer.WriteCharEntity(ch); } public override void WriteChars(char[] buffer, int index, int count) { writer.WriteChars(buffer, index, count); } public override void WriteComment(string text) { writer.WriteComment(text); } public override void WriteDocType(string name, string pubid, string sysid, string subset) { writer.WriteDocType(name, pubid, sysid, subset); } public override void WriteEndAttribute() { writer.WriteEndAttribute(); } public override void WriteEndDocument() { writer.WriteEndDocument(); } public override void WriteEndElement() { writer.WriteEndElement(); depth--; } public override void WriteEntityRef(string name) { writer.WriteEntityRef(name); } public override void WriteFullEndElement() { writer.WriteFullEndElement(); } public override void WriteName(string name) { writer.WriteName(name); } public override void WriteNmToken(string name) { writer.WriteNmToken(name); } public override void WriteNode(XmlReader reader, bool defattr) { writer.WriteNode(reader, defattr); } public override void WriteProcessingInstruction(string name, string text) { writer.WriteProcessingInstruction(name, text); } public override void WriteQualifiedName(string localName, string namespaceUri) { writer.WriteQualifiedName(localName, namespaceUri); } public override void WriteRaw(char[] buffer, int index, int count) { writer.WriteRaw(buffer, index, count); } public override void WriteRaw(string data) { writer.WriteRaw(data); } public override void WriteStartAttribute(string prefix, string localName, string namespaceUri) { writer.WriteStartAttribute(prefix, localName, namespaceUri); this.prefix++; } public override void WriteStartDocument() { writer.WriteStartDocument(); } public override void WriteStartDocument(bool standalone) { writer.WriteStartDocument(standalone); } public override void WriteStartElement(string prefix, string localName, string namespaceUri) { writer.WriteStartElement(prefix, localName, namespaceUri); depth++; this.prefix = 1; } public override void WriteString(string text) { writer.WriteString(text); } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { writer.WriteSurrogateCharEntity(lowChar, highChar); } public override void WriteWhitespace(string whitespace) { writer.WriteWhitespace(whitespace); } public override void WriteValue(object value) { writer.WriteValue(value); } public override void WriteValue(string value) { writer.WriteValue(value); } public override void WriteValue(bool value) { writer.WriteValue(value); } public override void WriteValue(DateTime value) { writer.WriteValue(value); } public override void WriteValue(double value) { writer.WriteValue(value); } public override void WriteValue(int value) { writer.WriteValue(value); } public override void WriteValue(long value) { writer.WriteValue(value); } public override void WriteXmlnsAttribute(string prefix, string namespaceUri) { if (namespaceUri == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri"); } if (prefix == null) { if (LookupPrefix(namespaceUri) != null) { return; } if (namespaceUri.Length == 0) { prefix = string.Empty; } else { string text = depth.ToString(NumberFormatInfo.InvariantInfo); string text2 = this.prefix.ToString(NumberFormatInfo.InvariantInfo); prefix = "d" + text + "p" + text2; } } WriteAttributeString("xmlns", prefix, null, namespaceUri); } } internal virtual bool FastAsync => false; public virtual bool CanCanonicalize => false; internal virtual AsyncCompletionResult WriteBase64Async(AsyncEventArgs state) { throw FxTrace.Exception.AsError((Exception)new NotSupportedException()); } public override Task WriteBase64Async(byte[] buffer, int index, int count) { return Task.Factory.FromAsync(BeginWriteBase64, EndWriteBase64, buffer, index, count, null); } internal virtual IAsyncResult BeginWriteBase64(byte[] buffer, int index, int count, AsyncCallback callback, object state) { return (IAsyncResult)new WriteBase64AsyncResult(buffer, index, count, this, callback, state); } internal virtual void EndWriteBase64(IAsyncResult result) { ScheduleActionItemAsyncResult.End(result); } public static XmlDictionaryWriter CreateBinaryWriter(Stream stream) { return CreateBinaryWriter(stream, null); } public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary dictionary) { return CreateBinaryWriter(stream, dictionary, null); } public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session) { return CreateBinaryWriter(stream, dictionary, session, ownsStream: true); } public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream) { XmlBinaryWriter xmlBinaryWriter = new XmlBinaryWriter(); xmlBinaryWriter.SetOutput(stream, dictionary, session, ownsStream); return xmlBinaryWriter; } public static XmlDictionaryWriter CreateTextWriter(Stream stream) { return CreateTextWriter(stream, Encoding.UTF8, ownsStream: true); } public static XmlDictionaryWriter CreateTextWriter(Stream stream, Encoding encoding) { return CreateTextWriter(stream, encoding, ownsStream: true); } public static XmlDictionaryWriter CreateTextWriter(Stream stream, Encoding encoding, bool ownsStream) { XmlUTF8TextWriter xmlUTF8TextWriter = new XmlUTF8TextWriter(); xmlUTF8TextWriter.SetOutput(stream, encoding, ownsStream); return xmlUTF8TextWriter; } public static XmlDictionaryWriter CreateMtomWriter(Stream stream, Encoding encoding, int maxSizeInBytes, string startInfo) { return CreateMtomWriter(stream, encoding, maxSizeInBytes, startInfo, null, null, writeMessageHeaders: true, ownsStream: true); } public static XmlDictionaryWriter CreateMtomWriter(Stream stream, Encoding encoding, int maxSizeInBytes, string startInfo, string boundary, string startUri, bool writeMessageHeaders, bool ownsStream) { XmlMtomWriter xmlMtomWriter = new XmlMtomWriter(); xmlMtomWriter.SetOutput(stream, encoding, maxSizeInBytes, startInfo, boundary, startUri, writeMessageHeaders, ownsStream); return xmlMtomWriter; } public static XmlDictionaryWriter CreateDictionaryWriter(XmlWriter writer) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } XmlDictionaryWriter xmlDictionaryWriter = writer as XmlDictionaryWriter; if (xmlDictionaryWriter == null) { xmlDictionaryWriter = new XmlWrappedWriter(writer); } return xmlDictionaryWriter; } public void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { WriteStartElement(null, localName, namespaceUri); } public virtual void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri) { WriteStartElement(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri)); } public void WriteStartAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { WriteStartAttribute(null, localName, namespaceUri); } public virtual void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri) { WriteStartAttribute(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri)); } public void WriteAttributeString(XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value) { WriteAttributeString(null, localName, namespaceUri, value); } public virtual void WriteXmlnsAttribute(string prefix, string namespaceUri) { if (namespaceUri == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri"); } if (prefix == null) { if (LookupPrefix(namespaceUri) != null) { return; } prefix = ((namespaceUri.Length == 0) ? string.Empty : ("d" + namespaceUri.Length.ToString(NumberFormatInfo.InvariantInfo))); } WriteAttributeString("xmlns", prefix, null, namespaceUri); } public virtual void WriteXmlnsAttribute(string prefix, XmlDictionaryString namespaceUri) { WriteXmlnsAttribute(prefix, XmlDictionaryString.GetString(namespaceUri)); } public virtual void WriteXmlAttribute(string localName, string value) { WriteAttributeString("xml", localName, null, value); } public virtual void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString value) { WriteXmlAttribute(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(value)); } public void WriteAttributeString(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value) { WriteStartAttribute(prefix, localName, namespaceUri); WriteString(value); WriteEndAttribute(); } public void WriteElementString(XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value) { WriteElementString(null, localName, namespaceUri, value); } public void WriteElementString(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value) { WriteStartElement(prefix, localName, namespaceUri); WriteString(value); WriteEndElement(); } public virtual void WriteString(XmlDictionaryString value) { WriteString(XmlDictionaryString.GetString(value)); } public virtual void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localName")); } if (namespaceUri == null) { namespaceUri = XmlDictionaryString.Empty; } WriteQualifiedName(localName.Value, namespaceUri.Value); } public virtual void WriteValue(XmlDictionaryString value) { WriteValue(XmlDictionaryString.GetString(value)); } public virtual void WriteValue(IStreamProvider value) { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } Stream stream = value.GetStream(); if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Stream returned by IStreamProvider cannot be null."))); } int num = 256; int num2 = 0; byte[] buffer = new byte[num]; while (true) { num2 = stream.Read(buffer, 0, num); if (num2 <= 0) { break; } WriteBase64(buffer, 0, num2); if (num < 65536 && num2 == num) { num *= 16; buffer = new byte[num]; } } value.ReleaseStream(stream); } public virtual Task WriteValueAsync(IStreamProvider value) { return Task.Factory.FromAsync(BeginWriteValue, EndWriteValue, value, null); } internal virtual IAsyncResult BeginWriteValue(IStreamProvider value, AsyncCallback callback, object state) { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } if (FastAsync) { return (IAsyncResult)new WriteValueFastAsyncResult(this, value, callback, state); } return (IAsyncResult)new WriteValueAsyncResult(this, value, callback, state); } internal virtual void EndWriteValue(IAsyncResult result) { if (FastAsync) { WriteValueFastAsyncResult.End(result); } else { WriteValueAsyncResult.End(result); } } public virtual void WriteValue(UniqueId value) { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } WriteString(value.ToString()); } public virtual void WriteValue(Guid value) { WriteString(value.ToString()); } public virtual void WriteValue(TimeSpan value) { WriteString(XmlConvert.ToString(value)); } public virtual void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } public virtual void EndCanonicalization() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } private void WriteElementNode(XmlDictionaryReader reader, bool defattr) { if (reader.TryGetLocalNameAsDictionaryString(out var localName) && reader.TryGetNamespaceUriAsDictionaryString(out var namespaceUri)) { WriteStartElement(reader.Prefix, localName, namespaceUri); } else { WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI); } if ((defattr || (!reader.IsDefault && (reader.SchemaInfo == null || !reader.SchemaInfo.IsDefault))) && reader.MoveToFirstAttribute()) { do { if (reader.TryGetLocalNameAsDictionaryString(out localName) && reader.TryGetNamespaceUriAsDictionaryString(out namespaceUri)) { WriteStartAttribute(reader.Prefix, localName, namespaceUri); } else { WriteStartAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI); } while (reader.ReadAttributeValue()) { if (reader.NodeType == XmlNodeType.EntityReference) { WriteEntityRef(reader.Name); } else { WriteTextNode(reader, isAttribute: true); } } WriteEndAttribute(); } while (reader.MoveToNextAttribute()); reader.MoveToElement(); } if (reader.IsEmptyElement) { WriteEndElement(); } } private void WriteArrayNode(XmlDictionaryReader reader, string prefix, string localName, string namespaceUri, Type type) { if (type == typeof(bool)) { BooleanArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } if (type == typeof(short)) { Int16ArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } if (type == typeof(int)) { Int32ArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } if (type == typeof(long)) { Int64ArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } if (type == typeof(float)) { SingleArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } if (type == typeof(double)) { DoubleArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } if (type == typeof(decimal)) { DecimalArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } if (type == typeof(DateTime)) { DateTimeArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } if (type == typeof(Guid)) { GuidArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } if (type == typeof(TimeSpan)) { TimeSpanArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } WriteElementNode(reader, defattr: false); reader.Read(); } private void WriteArrayNode(XmlDictionaryReader reader, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Type type) { if (type == typeof(bool)) { BooleanArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } if (type == typeof(short)) { Int16ArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } if (type == typeof(int)) { Int32ArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } if (type == typeof(long)) { Int64ArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } if (type == typeof(float)) { SingleArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } if (type == typeof(double)) { DoubleArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } if (type == typeof(decimal)) { DecimalArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } if (type == typeof(DateTime)) { DateTimeArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } if (type == typeof(Guid)) { GuidArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } if (type == typeof(TimeSpan)) { TimeSpanArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader); return; } WriteElementNode(reader, defattr: false); reader.Read(); } private void WriteArrayNode(XmlDictionaryReader reader, Type type) { if (reader.TryGetLocalNameAsDictionaryString(out var localName) && reader.TryGetNamespaceUriAsDictionaryString(out var namespaceUri)) { WriteArrayNode(reader, reader.Prefix, localName, namespaceUri, type); } else { WriteArrayNode(reader, reader.Prefix, reader.LocalName, reader.NamespaceURI, type); } } protected virtual void WriteTextNode(XmlDictionaryReader reader, bool isAttribute) { if (reader.TryGetValueAsDictionaryString(out var value)) { WriteString(value); } else { WriteString(reader.Value); } if (!isAttribute) { reader.Read(); } } public override void WriteNode(XmlReader reader, bool defattr) { if (reader is XmlDictionaryReader reader2) { WriteNode(reader2, defattr); } else { base.WriteNode(reader, defattr); } } public virtual void WriteNode(XmlDictionaryReader reader, bool defattr) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader")); } int num = ((reader.NodeType == XmlNodeType.None) ? (-1) : reader.Depth); do { XmlNodeType nodeType = reader.NodeType; if (nodeType == XmlNodeType.Text || nodeType == XmlNodeType.Whitespace || nodeType == XmlNodeType.SignificantWhitespace) { WriteTextNode(reader, isAttribute: false); continue; } if (reader.Depth > num && reader.IsStartArray(out var type)) { WriteArrayNode(reader, type); continue; } switch (nodeType) { case XmlNodeType.Element: WriteElementNode(reader, defattr); break; case XmlNodeType.CDATA: WriteCData(reader.Value); break; case XmlNodeType.EntityReference: WriteEntityRef(reader.Name); break; case XmlNodeType.ProcessingInstruction: case XmlNodeType.XmlDeclaration: WriteProcessingInstruction(reader.Name, reader.Value); break; case XmlNodeType.DocumentType: WriteDocType(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value); break; case XmlNodeType.Comment: WriteComment(reader.Value); break; case XmlNodeType.EndElement: WriteFullEndElement(); break; } if (!reader.Read()) { break; } } while (num < reader.Depth || (num == reader.Depth && reader.NodeType == XmlNodeType.EndElement)); } private void CheckArray(Array array, int offset, int count) { if (array == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("array")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > array.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", array.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > array.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", array.Length - offset))); } } public virtual void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) { WriteStartElement(prefix, localName, namespaceUri); WriteValue(array[offset + i]); WriteEndElement(); } } public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } public virtual void WriteArray(string prefix, string localName, string namespaceUri, short[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) { WriteStartElement(prefix, localName, namespaceUri); WriteValue(array[offset + i]); WriteEndElement(); } } public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } public virtual void WriteArray(string prefix, string localName, string namespaceUri, int[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) { WriteStartElement(prefix, localName, namespaceUri); WriteValue(array[offset + i]); WriteEndElement(); } } public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } public virtual void WriteArray(string prefix, string localName, string namespaceUri, long[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) { WriteStartElement(prefix, localName, namespaceUri); WriteValue(array[offset + i]); WriteEndElement(); } } public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } public virtual void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) { WriteStartElement(prefix, localName, namespaceUri); WriteValue(array[offset + i]); WriteEndElement(); } } public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } public virtual void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) { WriteStartElement(prefix, localName, namespaceUri); WriteValue(array[offset + i]); WriteEndElement(); } } public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } public virtual void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) { WriteStartElement(prefix, localName, namespaceUri); WriteValue(array[offset + i]); WriteEndElement(); } } public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } public virtual void WriteArray(string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) { WriteStartElement(prefix, localName, namespaceUri); WriteValue(array[offset + i]); WriteEndElement(); } } public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } public virtual void WriteArray(string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) { WriteStartElement(prefix, localName, namespaceUri); WriteValue(array[offset + i]); WriteEndElement(); } } public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } public virtual void WriteArray(string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) { WriteStartElement(prefix, localName, namespaceUri); WriteValue(array[offset + i]); WriteEndElement(); } } public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } } public interface IXmlMtomReaderInitializer { void SetInput(byte[] buffer, int offset, int count, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose); void SetInput(Stream stream, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose); } internal class XmlMtomReader : XmlDictionaryReader, IXmlLineInfo, IXmlMtomReaderInitializer { internal class MimePart { private Stream stream; private MimeHeaders headers; private byte[] buffer; private bool isReferencedFromInfoset; internal Stream Stream => stream; internal MimeHeaders Headers => headers; internal bool ReferencedFromInfoset { get { return isReferencedFromInfoset; } set { isReferencedFromInfoset = value; } } internal long Length { get { if (!stream.CanSeek) { return 0L; } return stream.Length; } } internal MimePart(Stream stream, MimeHeaders headers) { this.stream = stream; this.headers = headers; } internal byte[] GetBuffer(int maxBuffer, ref int remaining) { if (buffer == null) { MemoryStream memoryStream = (stream.CanSeek ? new MemoryStream((int)stream.Length) : new MemoryStream()); int num = 256; byte[] array = new byte[num]; int num2 = 0; do { num2 = stream.Read(array, 0, num); DecrementBufferQuota(maxBuffer, ref remaining, num2); if (num2 > 0) { memoryStream.Write(array, 0, num2); } } while (num2 > 0); memoryStream.Seek(0L, SeekOrigin.Begin); buffer = memoryStream.GetBuffer(); stream = memoryStream; } return buffer; } internal void Release(int maxBuffer, ref int remaining) { remaining += (int)Length; headers.Release(ref remaining); } } internal class XopIncludeReader : XmlDictionaryReader, IXmlLineInfo { private int chunkSize = 4096; private int bytesRemaining; private MimePart part; private ReadState readState; private XmlDictionaryReader parentReader; private string stringValue; private int stringOffset; private XmlNodeType nodeType; private MemoryStream binHexStream; private byte[] valueBuffer; private int valueOffset; private int valueCount; private bool finishedStream; public override XmlDictionaryReaderQuotas Quotas => parentReader.Quotas; public override XmlNodeType NodeType { get { if (readState != ReadState.Interactive) { return parentReader.NodeType; } return nodeType; } } public override string Value { get { if (readState != ReadState.Interactive) { return string.Empty; } if (stringValue == null) { int num = bytesRemaining; num -= num % 3; if (valueCount > 0 && valueOffset > 0) { Buffer.BlockCopy(valueBuffer, valueOffset, valueBuffer, 0, valueCount); valueOffset = 0; } num -= valueCount; if (valueBuffer == null) { valueBuffer = new byte[num]; } else if (valueBuffer.Length < num) { Array.Resize(ref valueBuffer, num); } byte[] array = valueBuffer; int num2 = 0; int num3 = 0; while (num > 0) { num3 = part.Stream.Read(array, num2, num); if (num3 == 0) { finishedStream = true; break; } bytesRemaining -= num3; valueCount += num3; num -= num3; num2 += num3; } stringValue = Convert.ToBase64String(array, 0, valueCount); } return stringValue; } } public override int AttributeCount => 0; public override string BaseURI => parentReader.BaseURI; public override bool CanReadBinaryContent => true; public override bool CanReadValueChunk => true; public override bool CanResolveEntity => parentReader.CanResolveEntity; public override int Depth { get { if (readState != ReadState.Interactive) { return parentReader.Depth; } return parentReader.Depth + 1; } } public override bool EOF => readState == ReadState.EndOfFile; public override bool HasAttributes => false; public override bool HasValue => readState == ReadState.Interactive; public override bool IsDefault => false; public override bool IsEmptyElement => false; public override string LocalName { get { if (readState != ReadState.Interactive) { return parentReader.LocalName; } return string.Empty; } } public override string Name { get { if (readState != ReadState.Interactive) { return parentReader.Name; } return string.Empty; } } public override string NamespaceURI { get { if (readState != ReadState.Interactive) { return parentReader.NamespaceURI; } return string.Empty; } } public override XmlNameTable NameTable => parentReader.NameTable; public override string Prefix { get { if (readState != ReadState.Interactive) { return parentReader.Prefix; } return string.Empty; } } public override char QuoteChar => parentReader.QuoteChar; public override ReadState ReadState => readState; public override XmlReaderSettings Settings => parentReader.Settings; public override string this[int index] => null; public override string this[string name] => null; public override string this[string name, string ns] => null; public override string XmlLang => parentReader.XmlLang; public override XmlSpace XmlSpace => parentReader.XmlSpace; public override Type ValueType { get { if (readState != ReadState.Interactive) { return parentReader.ValueType; } return typeof(byte[]); } } int IXmlLineInfo.LineNumber => ((IXmlLineInfo)parentReader).LineNumber; int IXmlLineInfo.LinePosition => ((IXmlLineInfo)parentReader).LinePosition; public XopIncludeReader(MimePart part, XmlDictionaryReader reader) { if (part == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("part"); } if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } this.part = part; parentReader = reader; readState = ReadState.Initial; nodeType = XmlNodeType.None; chunkSize = Math.Min(reader.Quotas.MaxBytesPerRead, chunkSize); bytesRemaining = chunkSize; finishedStream = false; } public override bool Read() { bool result = true; switch (readState) { case ReadState.Initial: readState = ReadState.Interactive; nodeType = XmlNodeType.Text; break; case ReadState.Interactive: if (finishedStream || (bytesRemaining == chunkSize && stringValue == null)) { readState = ReadState.EndOfFile; nodeType = XmlNodeType.EndElement; } else { bytesRemaining = chunkSize; } break; case ReadState.EndOfFile: nodeType = XmlNodeType.None; result = false; break; } stringValue = null; binHexStream = null; valueOffset = 0; valueCount = 0; stringOffset = 0; CloseStreams(); return result; } public override int ReadValueAsBase64(byte[] buffer, int offset, int count) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > buffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", buffer.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", buffer.Length - offset))); } if (stringValue != null) { count = Math.Min(count, valueCount); if (count > 0) { Buffer.BlockCopy(valueBuffer, valueOffset, buffer, offset, count); valueOffset += count; valueCount -= count; } return count; } if (bytesRemaining < count) { count = bytesRemaining; } int i = 0; if (readState == ReadState.Interactive) { int num; for (; i < count; i += num) { num = part.Stream.Read(buffer, offset + i, count - i); if (num == 0) { finishedStream = true; break; } } } bytesRemaining -= i; return i; } public override int ReadContentAsBase64(byte[] buffer, int offset, int count) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > buffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", buffer.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", buffer.Length - offset))); } if (valueCount > 0) { count = Math.Min(count, valueCount); Buffer.BlockCopy(valueBuffer, valueOffset, buffer, offset, count); valueOffset += count; valueCount -= count; return count; } if (chunkSize < count) { count = chunkSize; } int i = 0; if (readState == ReadState.Interactive) { int num; for (; i < count; i += num) { num = part.Stream.Read(buffer, offset + i, count - i); if (num == 0) { finishedStream = true; if (!Read()) { break; } } } } bytesRemaining = chunkSize; return i; } public override int ReadContentAsBinHex(byte[] buffer, int offset, int count) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > buffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", buffer.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", buffer.Length - offset))); } if (chunkSize < count) { count = chunkSize; } int num = 0; int num2 = 0; while (num < count) { if (binHexStream == null) { try { binHexStream = new MemoryStream(new BinHexEncoding().GetBytes(Value)); } catch (FormatException ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(ex.Message, ex)); } } int num3 = binHexStream.Read(buffer, offset + num, count - num); if (num3 == 0) { finishedStream = true; if (!Read()) { break; } num2 = 0; } num += num3; num2 += num3; } if (stringValue != null && num2 > 0) { stringValue = stringValue.Substring(num2 * 2); stringOffset = Math.Max(0, stringOffset - num2 * 2); bytesRemaining = chunkSize; } return num; } public override int ReadValueChunk(char[] chars, int offset, int count) { if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("chars"); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > chars.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > chars.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", chars.Length - offset))); } if (readState != ReadState.Interactive) { return 0; } _ = Value; count = Math.Min(stringValue.Length - stringOffset, count); if (count > 0) { stringValue.CopyTo(stringOffset, chars, offset, count); stringOffset += count; } return count; } public override string ReadContentAsString() { int num = Quotas.MaxStringContentLength; StringBuilder stringBuilder = new StringBuilder(); do { string value = Value; if (value.Length > num) { XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, Quotas.MaxStringContentLength); } num -= value.Length; stringBuilder.Append(value); } while (Read()); return stringBuilder.ToString(); } public override void Close() { CloseStreams(); readState = ReadState.Closed; } private void CloseStreams() { if (binHexStream != null) { binHexStream.Close(); binHexStream = null; } } public override string GetAttribute(int index) { return null; } public override string GetAttribute(string name) { return null; } public override string GetAttribute(string name, string ns) { return null; } public override string GetAttribute(XmlDictionaryString localName, XmlDictionaryString ns) { return null; } public override bool IsLocalName(string localName) { return false; } public override bool IsLocalName(XmlDictionaryString localName) { return false; } public override bool IsNamespaceUri(string ns) { return false; } public override bool IsNamespaceUri(XmlDictionaryString ns) { return false; } public override bool IsStartElement() { return false; } public override bool IsStartElement(string localName) { return false; } public override bool IsStartElement(string localName, string ns) { return false; } public override bool IsStartElement(XmlDictionaryString localName, XmlDictionaryString ns) { return false; } public override string LookupNamespace(string ns) { return parentReader.LookupNamespace(ns); } public override void MoveToAttribute(int index) { } public override bool MoveToAttribute(string name) { return false; } public override bool MoveToAttribute(string name, string ns) { return false; } public override bool MoveToElement() { return false; } public override bool MoveToFirstAttribute() { return false; } public override bool MoveToNextAttribute() { return false; } public override bool ReadAttributeValue() { return false; } public override string ReadInnerXml() { return ReadContentAsString(); } public override string ReadOuterXml() { return ReadContentAsString(); } public override void ResolveEntity() { } public override void Skip() { Read(); } bool IXmlLineInfo.HasLineInfo() { return ((IXmlLineInfo)parentReader).HasLineInfo(); } } private Encoding[] encodings; private XmlDictionaryReader xmlReader; private XmlDictionaryReader infosetReader; private MimeReader mimeReader; private Dictionary mimeParts; private OnXmlDictionaryReaderClose onClose; private bool readingBinaryElement; private int maxBufferSize; private int bufferRemaining; private MimePart part; public override XmlDictionaryReaderQuotas Quotas => xmlReader.Quotas; public override int AttributeCount => xmlReader.AttributeCount; public override string BaseURI => xmlReader.BaseURI; public override bool CanReadBinaryContent => xmlReader.CanReadBinaryContent; public override bool CanReadValueChunk => xmlReader.CanReadValueChunk; public override bool CanResolveEntity => xmlReader.CanResolveEntity; public override int Depth => xmlReader.Depth; public override bool EOF => xmlReader.EOF; public override bool HasAttributes => xmlReader.HasAttributes; public override bool HasValue => xmlReader.HasValue; public override bool IsDefault => xmlReader.IsDefault; public override bool IsEmptyElement => xmlReader.IsEmptyElement; public override string LocalName => xmlReader.LocalName; public override string Name => xmlReader.Name; public override string NamespaceURI => xmlReader.NamespaceURI; public override XmlNameTable NameTable => xmlReader.NameTable; public override XmlNodeType NodeType => xmlReader.NodeType; public override string Prefix => xmlReader.Prefix; public override char QuoteChar => xmlReader.QuoteChar; public override ReadState ReadState { get { if (xmlReader.ReadState != ReadState.Interactive && infosetReader != null) { return infosetReader.ReadState; } return xmlReader.ReadState; } } public override XmlReaderSettings Settings => xmlReader.Settings; public override string this[int index] => xmlReader[index]; public override string this[string name] => xmlReader[name]; public override string this[string name, string ns] => xmlReader[name, ns]; public override string Value => xmlReader.Value; public override Type ValueType => xmlReader.ValueType; public override string XmlLang => xmlReader.XmlLang; public override XmlSpace XmlSpace => xmlReader.XmlSpace; public int LineNumber { get { if (xmlReader.ReadState == ReadState.Closed) { return 0; } if (!(xmlReader is IXmlLineInfo xmlLineInfo)) { return 0; } return xmlLineInfo.LineNumber; } } public int LinePosition { get { if (xmlReader.ReadState == ReadState.Closed) { return 0; } if (!(xmlReader is IXmlLineInfo xmlLineInfo)) { return 0; } return xmlLineInfo.LinePosition; } } internal static void DecrementBufferQuota(int maxBuffer, ref int remaining, int size) { if (remaining - size <= 0) { remaining = 0; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MTOM buffer quota exceeded. The maximum size is {0}.", maxBuffer))); } remaining -= size; } private void SetReadEncodings(Encoding[] encodings) { if (encodings == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encodings"); } for (int i = 0; i < encodings.Length; i++) { if (encodings[i] == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "encodings[{0}]", i)); } } this.encodings = new Encoding[encodings.Length]; encodings.CopyTo(this.encodings, 0); } private void CheckContentType(string contentType) { if (contentType != null && contentType.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("MTOM content type is invalid."), "contentType")); } } public void SetInput(byte[] buffer, int offset, int count, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose) { SetInput(new MemoryStream(buffer, offset, count), encodings, contentType, quotas, maxBufferSize, onClose); } public void SetInput(Stream stream, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose) { SetReadEncodings(encodings); CheckContentType(contentType); Initialize(stream, contentType, quotas, maxBufferSize); this.onClose = onClose; } private void Initialize(Stream stream, string contentType, XmlDictionaryReaderQuotas quotas, int maxBufferSize) { if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream"); } this.maxBufferSize = maxBufferSize; bufferRemaining = maxBufferSize; string boundary; string start; string startInfo; if (contentType == null) { MimeMessageReader mimeMessageReader = new MimeMessageReader(stream); MimeHeaders mimeHeaders = mimeMessageReader.ReadHeaders(this.maxBufferSize, ref bufferRemaining); ReadMessageMimeVersionHeader(mimeHeaders.MimeVersion); ReadMessageContentTypeHeader(mimeHeaders.ContentType, out boundary, out start, out startInfo); stream = mimeMessageReader.GetContentStream(); if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MTOM message content is invalid."))); } } else { ReadMessageContentTypeHeader(new ContentTypeHeader(contentType), out boundary, out start, out startInfo); } mimeReader = new MimeReader(stream, boundary); mimeParts = null; readingBinaryElement = false; MimePart mimePart = ((start == null) ? ReadRootMimePart() : ReadMimePart(GetStartUri(start))); byte[] buffer = mimePart.GetBuffer(this.maxBufferSize, ref bufferRemaining); int count = (int)mimePart.Length; Encoding encoding = ReadRootContentTypeHeader(mimePart.Headers.ContentType, encodings, startInfo); CheckContentTransferEncodingOnRoot(mimePart.Headers.ContentTransferEncoding); if (xmlReader is IXmlTextReaderInitializer xmlTextReaderInitializer) { xmlTextReaderInitializer.SetInput(buffer, 0, count, encoding, quotas, null); } else { xmlReader = XmlDictionaryReader.CreateTextReader(buffer, 0, count, encoding, quotas, null); } } private void ReadMessageMimeVersionHeader(MimeVersionHeader header) { if (header != null && header.Version != MimeVersionHeader.Default.Version) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MTOM message has invalid MIME version. Expected '{1}', got '{0}' instead.", header.Version, MimeVersionHeader.Default.Version))); } } private void ReadMessageContentTypeHeader(ContentTypeHeader header, out string boundary, out string start, out string startInfo) { if (header == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MTOM message content type was not found."))); } if (string.Compare(MtomGlobals.MediaType, header.MediaType, StringComparison.OrdinalIgnoreCase) != 0 || string.Compare(MtomGlobals.MediaSubtype, header.MediaSubtype, StringComparison.OrdinalIgnoreCase) != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MTOM message is not multipart: media type should be '{0}', media subtype should be '{1}'.", MtomGlobals.MediaType, MtomGlobals.MediaSubtype))); } if (!header.Parameters.TryGetValue(MtomGlobals.TypeParam, out var value) || MtomGlobals.XopType != value) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MTOM msssage type is not '{0}'.", MtomGlobals.XopType))); } if (!header.Parameters.TryGetValue(MtomGlobals.BoundaryParam, out boundary)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Required MTOM parameter '{0}' is not specified.", MtomGlobals.BoundaryParam))); } if (!MailBnfHelper.IsValidMimeBoundary(boundary)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MIME boundary is invalid: '{0}'.", boundary))); } if (!header.Parameters.TryGetValue(MtomGlobals.StartParam, out start)) { start = null; } if (!header.Parameters.TryGetValue(MtomGlobals.StartInfoParam, out startInfo)) { startInfo = null; } } private Encoding ReadRootContentTypeHeader(ContentTypeHeader header, Encoding[] expectedEncodings, string expectedType) { if (header == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MTOM root content type is not found."))); } if (string.Compare(MtomGlobals.XopMediaType, header.MediaType, StringComparison.OrdinalIgnoreCase) != 0 || string.Compare(MtomGlobals.XopMediaSubtype, header.MediaSubtype, StringComparison.OrdinalIgnoreCase) != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MTOM root should have media type '{0}' and subtype '{1}'.", MtomGlobals.XopMediaType, MtomGlobals.XopMediaSubtype))); } if (!header.Parameters.TryGetValue(MtomGlobals.CharsetParam, out var value) || value == null || value.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Required MTOM root parameter '{0}' is not specified.", MtomGlobals.CharsetParam))); } Encoding encoding = null; for (int i = 0; i < encodings.Length; i++) { if (string.Compare(value, expectedEncodings[i].WebName, StringComparison.OrdinalIgnoreCase) == 0) { encoding = expectedEncodings[i]; break; } } if (encoding == null) { if (string.Compare(value, "utf-16LE", StringComparison.OrdinalIgnoreCase) == 0) { for (int j = 0; j < encodings.Length; j++) { if (string.Compare(expectedEncodings[j].WebName, Encoding.Unicode.WebName, StringComparison.OrdinalIgnoreCase) == 0) { encoding = expectedEncodings[j]; break; } } } else if (string.Compare(value, "utf-16BE", StringComparison.OrdinalIgnoreCase) == 0) { for (int k = 0; k < encodings.Length; k++) { if (string.Compare(expectedEncodings[k].WebName, Encoding.BigEndianUnicode.WebName, StringComparison.OrdinalIgnoreCase) == 0) { encoding = expectedEncodings[k]; break; } } } if (encoding == null) { StringBuilder stringBuilder = new StringBuilder(); for (int l = 0; l < encodings.Length; l++) { if (stringBuilder.Length != 0) { stringBuilder.Append(" | "); } stringBuilder.Append(encodings[l].WebName); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Unexpected charset on MTOM root. Expected '{1}', got '{0}' instead.", value, stringBuilder.ToString()))); } } if (expectedType != null) { if (!header.Parameters.TryGetValue(MtomGlobals.TypeParam, out var value2) || value2 == null || value2.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Required MTOM root parameter '{0}' is not specified.", MtomGlobals.TypeParam))); } if (value2 != expectedType) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Unexpected type on MTOM root. Expected '{1}', got '{0}' instead.", value2, expectedType))); } } return encoding; } private void CheckContentTransferEncodingOnRoot(ContentTransferEncodingHeader header) { if (header != null && header.ContentTransferEncoding == ContentTransferEncoding.Other) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MTOM content transfer encoding value is not supported. Raw value is '{0}', '{1}' in 7bit encoding, '{2}' in 8bit encoding, and '{3}' in binary.", header.Value, ContentTransferEncodingHeader.SevenBit.ContentTransferEncodingValue, ContentTransferEncodingHeader.EightBit.ContentTransferEncodingValue, ContentTransferEncodingHeader.Binary.ContentTransferEncodingValue))); } } private void CheckContentTransferEncodingOnBinaryPart(ContentTransferEncodingHeader header) { if (header == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MTOM content transfer encoding is not present. ContentTransferEncoding header is '{0}'.", ContentTransferEncodingHeader.Binary.ContentTransferEncodingValue))); } if (header.ContentTransferEncoding != ContentTransferEncoding.Binary) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Invalid transfer encoding for MIME part: '{0}', in binary: '{1}'.", header.Value, ContentTransferEncodingHeader.Binary.ContentTransferEncodingValue))); } } private string GetStartUri(string startUri) { if (startUri.StartsWith("<", StringComparison.Ordinal)) { if (startUri.EndsWith(">", StringComparison.Ordinal)) { return startUri; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Invalid MTOM start URI: '{0}'.", startUri))); } return string.Format(CultureInfo.InvariantCulture, "<{0}>", startUri); } public override bool Read() { bool flag = xmlReader.Read(); if (xmlReader.NodeType == XmlNodeType.Element) { XopIncludeReader xopIncludeReader = null; if (xmlReader.IsStartElement(MtomGlobals.XopIncludeLocalName, MtomGlobals.XopIncludeNamespace)) { string text = null; while (xmlReader.MoveToNextAttribute()) { if (xmlReader.LocalName == MtomGlobals.XopIncludeHrefLocalName && xmlReader.NamespaceURI == MtomGlobals.XopIncludeHrefNamespace) { text = xmlReader.Value; } else if (xmlReader.NamespaceURI == MtomGlobals.XopIncludeNamespace) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("xop Include element has invalid attribute: '{0}' in '{1}' namespace.", xmlReader.LocalName, MtomGlobals.XopIncludeNamespace))); } } if (text == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("xop Include element did not specify '{0}' attribute.", MtomGlobals.XopIncludeHrefLocalName))); } MimePart mimePart = ReadMimePart(text); CheckContentTransferEncodingOnBinaryPart(mimePart.Headers.ContentTransferEncoding); part = mimePart; xopIncludeReader = new XopIncludeReader(mimePart, xmlReader); xopIncludeReader.Read(); xmlReader.MoveToElement(); if (xmlReader.IsEmptyElement) { xmlReader.Read(); } else { int depth = xmlReader.Depth; xmlReader.ReadStartElement(); while (xmlReader.Depth > depth) { if (xmlReader.IsStartElement() && xmlReader.NamespaceURI == MtomGlobals.XopIncludeNamespace) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("xop Include element has invalid element: '{0}' in '{1}' namespace.", xmlReader.LocalName, MtomGlobals.XopIncludeNamespace))); } xmlReader.Skip(); } xmlReader.ReadEndElement(); } } if (xopIncludeReader != null) { xmlReader.MoveToContent(); infosetReader = xmlReader; xmlReader = xopIncludeReader; xopIncludeReader = null; } } if (xmlReader.ReadState == ReadState.EndOfFile && infosetReader != null) { if (!flag) { flag = infosetReader.Read(); } part.Release(maxBufferSize, ref bufferRemaining); xmlReader = infosetReader; infosetReader = null; } return flag; } private MimePart ReadMimePart(string uri) { MimePart value = null; if (uri == null || uri.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("empty URI is invalid for MTOM MIME part."))); } string text = null; if (uri.StartsWith(MimeGlobals.ContentIDScheme, StringComparison.Ordinal)) { text = string.Format(CultureInfo.InvariantCulture, "<{0}>", Uri.UnescapeDataString(uri.Substring(MimeGlobals.ContentIDScheme.Length))); } else if (uri.StartsWith("<", StringComparison.Ordinal)) { text = uri; } if (text == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Invalid MTOM CID URI: '{0}'.", uri))); } if (mimeParts != null && mimeParts.TryGetValue(text, out value)) { if (value.ReferencedFromInfoset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Specified MIME part '{0}' is referenced more than once.", text))); } } else { int maxMimeParts = AppSettings.MaxMimeParts; while (value == null && mimeReader.ReadNextPart()) { MimeHeaders mimeHeaders = mimeReader.ReadHeaders(maxBufferSize, ref bufferRemaining); Stream contentStream = mimeReader.GetContentStream(); if (contentStream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MTOM message content in MIME part is invalid."))); } ContentIDHeader contentIDHeader = mimeHeaders?.ContentID; if (contentIDHeader == null || contentIDHeader.Value == null) { int num = 256; byte[] buffer = new byte[num]; int num2 = 0; do { num2 = contentStream.Read(buffer, 0, num); } while (num2 > 0); continue; } string value2 = mimeHeaders.ContentID.Value; MimePart mimePart = new MimePart(contentStream, mimeHeaders); if (mimeParts == null) { mimeParts = new Dictionary(); } mimeParts.Add(value2, mimePart); if (mimeParts.Count > maxMimeParts) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MIME parts number exceeded the maximum settings. Must be less than {0}. Specified as '{1}'.", maxMimeParts, "microsoft:xmldictionaryreader:maxmimeparts"))); } if (value2.Equals(text)) { value = mimePart; } else { mimePart.GetBuffer(maxBufferSize, ref bufferRemaining); } } if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MTOM part with URI '{0}' is not found.", uri))); } } value.ReferencedFromInfoset = true; return value; } private MimePart ReadRootMimePart() { if (!mimeReader.ReadNextPart()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MTOM root part is not found."))); } MimeHeaders headers = mimeReader.ReadHeaders(maxBufferSize, ref bufferRemaining); return new MimePart(mimeReader.GetContentStream() ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MTOM message content in MIME part is invalid."))), headers); } private void AdvanceToContentOnElement() { if (NodeType != XmlNodeType.Attribute) { MoveToContent(); } } public override void Close() { xmlReader.Close(); mimeReader.Close(); OnXmlDictionaryReaderClose onXmlDictionaryReaderClose = onClose; onClose = null; if (onXmlDictionaryReaderClose == null) { return; } try { onXmlDictionaryReaderClose(this); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(ex); } } public override string GetAttribute(int index) { return xmlReader.GetAttribute(index); } public override string GetAttribute(string name) { return xmlReader.GetAttribute(name); } public override string GetAttribute(string name, string ns) { return xmlReader.GetAttribute(name, ns); } public override string GetAttribute(XmlDictionaryString localName, XmlDictionaryString ns) { return xmlReader.GetAttribute(localName, ns); } public override bool IsLocalName(string localName) { return xmlReader.IsLocalName(localName); } public override bool IsLocalName(XmlDictionaryString localName) { return xmlReader.IsLocalName(localName); } public override bool IsNamespaceUri(string ns) { return xmlReader.IsNamespaceUri(ns); } public override bool IsNamespaceUri(XmlDictionaryString ns) { return xmlReader.IsNamespaceUri(ns); } public override bool IsStartElement() { return xmlReader.IsStartElement(); } public override bool IsStartElement(string localName) { return xmlReader.IsStartElement(localName); } public override bool IsStartElement(string localName, string ns) { return xmlReader.IsStartElement(localName, ns); } public override bool IsStartElement(XmlDictionaryString localName, XmlDictionaryString ns) { return xmlReader.IsStartElement(localName, ns); } public override string LookupNamespace(string ns) { return xmlReader.LookupNamespace(ns); } public override void MoveToAttribute(int index) { xmlReader.MoveToAttribute(index); } public override bool MoveToAttribute(string name) { return xmlReader.MoveToAttribute(name); } public override bool MoveToAttribute(string name, string ns) { return xmlReader.MoveToAttribute(name, ns); } public override bool MoveToElement() { return xmlReader.MoveToElement(); } public override bool MoveToFirstAttribute() { return xmlReader.MoveToFirstAttribute(); } public override bool MoveToNextAttribute() { return xmlReader.MoveToNextAttribute(); } public override bool ReadAttributeValue() { return xmlReader.ReadAttributeValue(); } public override object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) { AdvanceToContentOnElement(); return xmlReader.ReadContentAs(returnType, namespaceResolver); } public override byte[] ReadContentAsBase64() { AdvanceToContentOnElement(); return xmlReader.ReadContentAsBase64(); } public override int ReadValueAsBase64(byte[] buffer, int offset, int count) { AdvanceToContentOnElement(); return xmlReader.ReadValueAsBase64(buffer, offset, count); } public override int ReadContentAsBase64(byte[] buffer, int offset, int count) { AdvanceToContentOnElement(); return xmlReader.ReadContentAsBase64(buffer, offset, count); } public override int ReadElementContentAsBase64(byte[] buffer, int offset, int count) { if (!readingBinaryElement) { if (IsEmptyElement) { Read(); return 0; } ReadStartElement(); readingBinaryElement = true; } int num = ReadContentAsBase64(buffer, offset, count); if (num == 0) { ReadEndElement(); readingBinaryElement = false; } return num; } public override int ReadElementContentAsBinHex(byte[] buffer, int offset, int count) { if (!readingBinaryElement) { if (IsEmptyElement) { Read(); return 0; } ReadStartElement(); readingBinaryElement = true; } int num = ReadContentAsBinHex(buffer, offset, count); if (num == 0) { ReadEndElement(); readingBinaryElement = false; } return num; } public override int ReadContentAsBinHex(byte[] buffer, int offset, int count) { AdvanceToContentOnElement(); return xmlReader.ReadContentAsBinHex(buffer, offset, count); } public override bool ReadContentAsBoolean() { AdvanceToContentOnElement(); return xmlReader.ReadContentAsBoolean(); } public override int ReadContentAsChars(char[] chars, int index, int count) { AdvanceToContentOnElement(); return xmlReader.ReadContentAsChars(chars, index, count); } public override DateTime ReadContentAsDateTime() { AdvanceToContentOnElement(); return xmlReader.ReadContentAsDateTime(); } public override decimal ReadContentAsDecimal() { AdvanceToContentOnElement(); return xmlReader.ReadContentAsDecimal(); } public override double ReadContentAsDouble() { AdvanceToContentOnElement(); return xmlReader.ReadContentAsDouble(); } public override int ReadContentAsInt() { AdvanceToContentOnElement(); return xmlReader.ReadContentAsInt(); } public override long ReadContentAsLong() { AdvanceToContentOnElement(); return xmlReader.ReadContentAsLong(); } public override object ReadContentAsObject() { AdvanceToContentOnElement(); return xmlReader.ReadContentAsObject(); } public override float ReadContentAsFloat() { AdvanceToContentOnElement(); return xmlReader.ReadContentAsFloat(); } public override string ReadContentAsString() { AdvanceToContentOnElement(); return xmlReader.ReadContentAsString(); } public override string ReadInnerXml() { return xmlReader.ReadInnerXml(); } public override string ReadOuterXml() { return xmlReader.ReadOuterXml(); } public override int ReadValueChunk(char[] buffer, int index, int count) { return xmlReader.ReadValueChunk(buffer, index, count); } public override void ResolveEntity() { xmlReader.ResolveEntity(); } public override void Skip() { xmlReader.Skip(); } public bool HasLineInfo() { if (xmlReader.ReadState == ReadState.Closed) { return false; } if (!(xmlReader is IXmlLineInfo xmlLineInfo)) { return false; } return xmlLineInfo.HasLineInfo(); } } internal class MimeMessageReader { private static byte[] CRLFCRLF = new byte[4] { 13, 10, 13, 10 }; private bool getContentStreamCalled; private MimeHeaderReader mimeHeaderReader; private DelimittedStreamReader reader; public MimeMessageReader(Stream stream) { if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream"); } reader = new DelimittedStreamReader(stream); mimeHeaderReader = new MimeHeaderReader(reader.GetNextStream(CRLFCRLF)); } public Stream GetContentStream() { if (getContentStreamCalled) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("On MimeMessage, GetContentStream method is already called."))); } mimeHeaderReader.Close(); Stream nextStream = reader.GetNextStream(null); getContentStreamCalled = true; return nextStream; } public MimeHeaders ReadHeaders(int maxBuffer, ref int remaining) { MimeHeaders mimeHeaders = new MimeHeaders(); while (mimeHeaderReader.Read(maxBuffer, ref remaining)) { mimeHeaders.Add(mimeHeaderReader.Name, mimeHeaderReader.Value, ref remaining); } return mimeHeaders; } } internal class MimeReader { private static byte[] CRLFCRLF = new byte[4] { 13, 10, 13, 10 }; private byte[] boundaryBytes; private string content; private Stream currentStream; private MimeHeaderReader mimeHeaderReader; private DelimittedStreamReader reader; private byte[] scratch = new byte[2]; public string Preface { get { if (content == null) { Stream nextStream = reader.GetNextStream(boundaryBytes); content = new StreamReader(nextStream, Encoding.ASCII, detectEncodingFromByteOrderMarks: false, 256).ReadToEnd(); nextStream.Close(); if (content == null) { content = string.Empty; } } return content; } } public MimeReader(Stream stream, string boundary) { if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream"); } if (boundary == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("boundary"); } reader = new DelimittedStreamReader(stream); boundaryBytes = MimeWriter.GetBoundaryBytes(boundary); reader.Push(boundaryBytes, 0, 2); } public void Close() { reader.Close(); } public Stream GetContentStream() { mimeHeaderReader.Close(); return reader.GetNextStream(boundaryBytes); } public bool ReadNextPart() { _ = Preface; if (currentStream != null) { currentStream.Close(); currentStream = null; } Stream nextStream = reader.GetNextStream(CRLFCRLF); if (nextStream == null) { return false; } if (BlockRead(nextStream, scratch, 0, 2) == 2) { if (scratch[0] == 13 && scratch[1] == 10) { if (mimeHeaderReader == null) { mimeHeaderReader = new MimeHeaderReader(nextStream); } else { mimeHeaderReader.Reset(nextStream); } return true; } if (scratch[0] == 45 && scratch[1] == 45 && (BlockRead(nextStream, scratch, 0, 2) < 2 || (scratch[0] == 13 && scratch[1] == 10))) { return false; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("MIME parts are truncated."))); } public MimeHeaders ReadHeaders(int maxBuffer, ref int remaining) { MimeHeaders mimeHeaders = new MimeHeaders(); while (mimeHeaderReader.Read(maxBuffer, ref remaining)) { mimeHeaders.Add(mimeHeaderReader.Name, mimeHeaderReader.Value, ref remaining); } return mimeHeaders; } private int BlockRead(Stream stream, byte[] buffer, int offset, int count) { int num = 0; do { int num2 = stream.Read(buffer, offset + num, count - num); if (num2 == 0) { break; } num += num2; } while (num < count); return num; } } internal class DelimittedStreamReader { private enum MatchState { True, False, InsufficientData } private class DelimittedReadStream : Stream { private DelimittedStreamReader reader; public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => false; public override long Length { get { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Seek operation is not supported on this Stream.", GetType().FullName))); } } public override long Position { get { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Seek operation is not supported on this Stream.", GetType().FullName))); } set { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Seek operation is not supported on this Stream.", GetType().FullName))); } } public DelimittedReadStream(DelimittedStreamReader reader) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } this.reader = reader; } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Write operation is not supported on this '{0}' Stream.", GetType().FullName))); } public override void Close() { reader.Close(this); } public override void EndWrite(IAsyncResult asyncResult) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Write operation is not supported on this '{0}' Stream.", GetType().FullName))); } public override void Flush() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Write operation is not supported on this '{0}' Stream.", GetType().FullName))); } public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > buffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", buffer.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", buffer.Length - offset))); } return reader.Read(this, buffer, offset, count); } public override long Seek(long offset, SeekOrigin origin) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Seek operation is not supported on this Stream.", GetType().FullName))); } public override void SetLength(long value) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Write operation is not supported on this '{0}' Stream.", GetType().FullName))); } public override void Write(byte[] buffer, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Write operation is not supported on this '{0}' Stream.", GetType().FullName))); } } private bool canGetNextStream = true; private DelimittedReadStream currentStream; private byte[] delimitter; private byte[] matchBuffer; private byte[] scratch; private BufferedReadStream stream; public DelimittedStreamReader(Stream stream) { this.stream = new BufferedReadStream(stream); } public void Close() { stream.Close(); } private void Close(DelimittedReadStream caller) { if (currentStream != caller) { return; } if (delimitter == null) { stream.Close(); } else { if (scratch == null) { scratch = new byte[1024]; } while (Read(caller, scratch, 0, scratch.Length) != 0) { } } currentStream = null; } public Stream GetNextStream(byte[] delimitter) { if (currentStream != null) { currentStream.Close(); currentStream = null; } if (!canGetNextStream) { return null; } this.delimitter = delimitter; canGetNextStream = delimitter != null; currentStream = new DelimittedReadStream(this); return currentStream; } private MatchState MatchDelimitter(byte[] buffer, int start, int end) { if (delimitter.Length > end - start) { for (int num = end - start - 1; num >= 1; num--) { if (buffer[start + num] != delimitter[num]) { return MatchState.False; } } return MatchState.InsufficientData; } for (int num2 = delimitter.Length - 1; num2 >= 1; num2--) { if (buffer[start + num2] != delimitter[num2]) { return MatchState.False; } } return MatchState.True; } private int ProcessRead(byte[] buffer, int offset, int read) { if (read == 0) { return read; } int i = offset; for (int num = offset + read; i < num; i++) { if (buffer[i] != delimitter[0]) { continue; } switch (MatchDelimitter(buffer, i, num)) { case MatchState.True: { int result = i - offset; i += delimitter.Length; stream.Push(buffer, i, num - i); currentStream = null; return result; } case MatchState.InsufficientData: { int num2 = i - offset; if (num2 > 0) { stream.Push(buffer, i, num - i); return num2; } return -1; } } } return read; } private int Read(DelimittedReadStream caller, byte[] buffer, int offset, int count) { if (currentStream != caller) { return 0; } int num = stream.Read(buffer, offset, count); if (num == 0) { canGetNextStream = false; currentStream = null; return num; } if (delimitter == null) { return num; } int num2 = ProcessRead(buffer, offset, num); if (num2 < 0) { if (matchBuffer == null || matchBuffer.Length < delimitter.Length - num) { matchBuffer = new byte[delimitter.Length - num]; } int count2 = stream.ReadBlock(matchBuffer, 0, delimitter.Length - num); if (MatchRemainder(num, count2)) { currentStream = null; num2 = 0; } else { stream.Push(matchBuffer, 0, count2); int i; for (i = 1; i < num && buffer[i] != delimitter[0]; i++) { } if (i < num) { stream.Push(buffer, offset + i, num - i); } num2 = i; } } return num2; } private bool MatchRemainder(int start, int count) { if (start + count != delimitter.Length) { return false; } for (count--; count >= 0; count--) { if (delimitter[start + count] != matchBuffer[count]) { return false; } } return true; } internal void Push(byte[] buffer, int offset, int count) { stream.Push(buffer, offset, count); } } internal class MimeHeaders { private static class Constants { public const string ContentTransferEncoding = "content-transfer-encoding"; public const string ContentID = "content-id"; public const string ContentType = "content-type"; public const string MimeVersion = "mime-version"; } private Dictionary headers = new Dictionary(); public ContentTypeHeader ContentType { get { if (headers.TryGetValue("content-type", out var value)) { return value as ContentTypeHeader; } return null; } } public ContentIDHeader ContentID { get { if (headers.TryGetValue("content-id", out var value)) { return value as ContentIDHeader; } return null; } } public ContentTransferEncodingHeader ContentTransferEncoding { get { if (headers.TryGetValue("content-transfer-encoding", out var value)) { return value as ContentTransferEncodingHeader; } return null; } } public MimeVersionHeader MimeVersion { get { if (headers.TryGetValue("mime-version", out var value)) { return value as MimeVersionHeader; } return null; } } public void Add(string name, string value, ref int remaining) { if (name == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name"); } if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } switch (name) { case "content-type": Add(new ContentTypeHeader(value)); break; case "content-id": Add(new ContentIDHeader(name, value)); break; case "content-transfer-encoding": Add(new ContentTransferEncodingHeader(value)); break; case "mime-version": Add(new MimeVersionHeader(value)); break; default: remaining += value.Length * 2; break; } remaining += name.Length * 2; } public void Add(MimeHeader header) { if (header == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("header"); } if (headers.TryGetValue(header.Name, out var _)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("MIME header '{0}' already exists.", header.Name))); } headers.Add(header.Name, header); } public void Release(ref int remaining) { foreach (MimeHeader value in headers.Values) { remaining += value.Value.Length * 2; } } } internal class MimeHeader { private string name; private string value; public string Name => name; public string Value => value; public MimeHeader(string name, string value) { if (name == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name"); } this.name = name; this.value = value; } } internal class ContentTypeHeader : MimeHeader { public static readonly ContentTypeHeader Default = new ContentTypeHeader("application/octet-stream"); private string mediaType; private string subType; private Dictionary parameters; public string MediaType { get { if (mediaType == null && base.Value != null) { ParseValue(); } return mediaType; } } public string MediaSubtype { get { if (subType == null && base.Value != null) { ParseValue(); } return subType; } } public Dictionary Parameters { get { if (parameters == null) { if (base.Value != null) { ParseValue(); } else { parameters = new Dictionary(); } } return parameters; } } public ContentTypeHeader(string value) : base("content-type", value) { } private void ParseValue() { if (parameters != null) { return; } int offset = 0; parameters = new Dictionary(); mediaType = MailBnfHelper.ReadToken(base.Value, ref offset, null); if (offset >= base.Value.Length || base.Value[offset++] != '/') { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("MIME content type header is invalid."))); } subType = MailBnfHelper.ReadToken(base.Value, ref offset, null); while (MailBnfHelper.SkipCFWS(base.Value, ref offset)) { if (offset >= base.Value.Length || base.Value[offset++] != ';') { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("MIME content type header is invalid."))); } if (!MailBnfHelper.SkipCFWS(base.Value, ref offset)) { break; } string text = MailBnfHelper.ReadParameterAttribute(base.Value, ref offset, null); if (text == null || offset >= base.Value.Length || base.Value[offset++] != '=') { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("MIME content type header is invalid."))); } string text2 = MailBnfHelper.ReadParameterValue(base.Value, ref offset, null); parameters.Add(text.ToLowerInvariant(), text2); } if (!parameters.ContainsKey(MtomGlobals.StartInfoParam)) { return; } string text3 = parameters[MtomGlobals.StartInfoParam]; int offset2 = text3.IndexOf(';'); if (offset2 <= -1) { return; } while (MailBnfHelper.SkipCFWS(text3, ref offset2)) { if (text3[offset2] == ';') { offset2++; string text4 = MailBnfHelper.ReadParameterAttribute(text3, ref offset2, null); if (text4 == null || offset2 >= text3.Length || text3[offset2++] != '=') { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("MIME content type header is invalid."))); } string text5 = MailBnfHelper.ReadParameterValue(text3, ref offset2, null); if (text4 == MtomGlobals.ActionParam) { parameters[MtomGlobals.ActionParam] = text5; } continue; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("MIME content type header is invalid."))); } } } internal enum ContentTransferEncoding { SevenBit, EightBit, Binary, Other, Unspecified } internal class ContentTransferEncodingHeader : MimeHeader { private ContentTransferEncoding contentTransferEncoding; private string contentTransferEncodingValue; public static readonly ContentTransferEncodingHeader Binary = new ContentTransferEncodingHeader(ContentTransferEncoding.Binary, "binary"); public static readonly ContentTransferEncodingHeader EightBit = new ContentTransferEncodingHeader(ContentTransferEncoding.EightBit, "8bit"); public static readonly ContentTransferEncodingHeader SevenBit = new ContentTransferEncodingHeader(ContentTransferEncoding.SevenBit, "7bit"); public ContentTransferEncoding ContentTransferEncoding { get { ParseValue(); return contentTransferEncoding; } } public string ContentTransferEncodingValue { get { ParseValue(); return contentTransferEncodingValue; } } public ContentTransferEncodingHeader(string value) : base("content-transfer-encoding", value.ToLowerInvariant()) { } public ContentTransferEncodingHeader(ContentTransferEncoding contentTransferEncoding, string value) : base("content-transfer-encoding", null) { this.contentTransferEncoding = contentTransferEncoding; contentTransferEncodingValue = value; } private void ParseValue() { if (contentTransferEncodingValue == null) { int offset = 0; contentTransferEncodingValue = ((base.Value.Length == 0) ? base.Value : ((base.Value[0] == '"') ? MailBnfHelper.ReadQuotedString(base.Value, ref offset, null) : MailBnfHelper.ReadToken(base.Value, ref offset, null))); switch (contentTransferEncodingValue) { case "7bit": contentTransferEncoding = ContentTransferEncoding.SevenBit; break; case "8bit": contentTransferEncoding = ContentTransferEncoding.EightBit; break; case "binary": contentTransferEncoding = ContentTransferEncoding.Binary; break; default: contentTransferEncoding = ContentTransferEncoding.Other; break; } } } } internal class ContentIDHeader : MimeHeader { public ContentIDHeader(string name, string value) : base(name, value) { } } internal class MimeVersionHeader : MimeHeader { public static readonly MimeVersionHeader Default = new MimeVersionHeader("1.0"); private string version; public string Version { get { if (version == null && base.Value != null) { ParseValue(); } return version; } } public MimeVersionHeader(string value) : base("mime-version", value) { } private void ParseValue() { if (base.Value == "1.0") { version = "1.0"; return; } int offset = 0; if (!MailBnfHelper.SkipCFWS(base.Value, ref offset)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("MIME version header is invalid."))); } StringBuilder stringBuilder = new StringBuilder(); MailBnfHelper.ReadDigits(base.Value, ref offset, stringBuilder); if (!MailBnfHelper.SkipCFWS(base.Value, ref offset) || offset >= base.Value.Length || base.Value[offset++] != '.' || !MailBnfHelper.SkipCFWS(base.Value, ref offset)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("MIME version header is invalid."))); } stringBuilder.Append('.'); MailBnfHelper.ReadDigits(base.Value, ref offset, stringBuilder); version = stringBuilder.ToString(); } } internal class MimeHeaderReader { private enum ReadState { ReadName, SkipWS, ReadValue, ReadLF, ReadWS, EOF } private string value; private byte[] buffer = new byte[1024]; private int maxOffset; private string name; private int offset; private ReadState readState; private Stream stream; public string Value => value; public string Name => name; public MimeHeaderReader(Stream stream) { if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream"); } this.stream = stream; } public void Close() { stream.Close(); readState = ReadState.EOF; } public bool Read(int maxBuffer, ref int remaining) { name = null; value = null; while (readState != ReadState.EOF) { if (offset == maxOffset) { maxOffset = stream.Read(buffer, 0, buffer.Length); offset = 0; if (BufferEnd()) { break; } } if (ProcessBuffer(maxBuffer, ref remaining)) { break; } } return value != null; } [SecuritySafeCritical] [PermissionSet(SecurityAction.Demand, Unrestricted = true)] private unsafe bool ProcessBuffer(int maxBuffer, ref int remaining) { fixed (byte* ptr = buffer) { byte* ptr2 = ptr + offset; byte* ptr3 = ptr + maxOffset; byte* ptr4 = ptr2; object[] obj; int num; switch (readState) { case ReadState.ReadName: for (; ptr4 < ptr3; ptr4++) { if (*ptr4 == 58) { goto IL_0065; } if (*ptr4 >= 65 && *ptr4 <= 90) { byte* intPtr = ptr4; *intPtr += 32; continue; } if (*ptr4 >= 33 && *ptr4 <= 126) { continue; } goto IL_00b1; } AppendName(new string((sbyte*)ptr2, 0, (int)(ptr4 - ptr2)), maxBuffer, ref remaining); readState = ReadState.ReadName; break; case ReadState.SkipWS: while (ptr4 < ptr3) { if (*ptr4 == 9 || *ptr4 == 32) { ptr4++; continue; } goto case ReadState.ReadValue; } readState = ReadState.SkipWS; break; case ReadState.ReadValue: ptr2 = ptr4; while (ptr4 < ptr3) { if (*ptr4 != 13) { if (*ptr4 == 10) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("Malformed MIME header."))); } ptr4++; continue; } goto IL_018b; } AppendValue(new string((sbyte*)ptr2, 0, (int)(ptr4 - ptr2)), maxBuffer, ref remaining); readState = ReadState.ReadValue; break; case ReadState.ReadLF: if (ptr4 < ptr3) { if (*ptr4 != 10) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("Malformed MIME header."))); } ptr4++; goto case ReadState.ReadWS; } readState = ReadState.ReadLF; break; case ReadState.ReadWS: if (ptr4 < ptr3) { if (*ptr4 != 32 && *ptr4 != 9) { readState = ReadState.ReadName; offset = (int)(ptr4 - ptr); return true; } goto case ReadState.ReadValue; } readState = ReadState.ReadWS; break; case ReadState.EOF: { readState = ReadState.EOF; offset = (int)(ptr4 - ptr); return true; } IL_0065: AppendName(new string((sbyte*)ptr2, 0, (int)(ptr4 - ptr2)), maxBuffer, ref remaining); ptr4++; goto case ReadState.SkipWS; IL_00b1: if (name == null && *ptr4 == 13) { ptr4++; if (ptr4 >= ptr3 || *ptr4 != 10) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("Malformed MIME header."))); } goto case ReadState.EOF; } obj = new object[2] { (char)(*ptr4), null }; num = *ptr4; obj[1] = num.ToString("X", CultureInfo.InvariantCulture); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("MIME header has an invalid character ('{0}', {1} in hexadecimal value).", obj))); IL_018b: AppendValue(new string((sbyte*)ptr2, 0, (int)(ptr4 - ptr2)), maxBuffer, ref remaining); ptr4++; goto case ReadState.ReadLF; } offset = (int)(ptr4 - ptr); } return false; } private bool BufferEnd() { if (maxOffset == 0) { if (readState != ReadState.ReadWS && readState != ReadState.ReadValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("Malformed MIME header."))); } readState = ReadState.EOF; return true; } return false; } public void Reset(Stream stream) { if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream"); } if (readState != ReadState.EOF) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("On MimeReader, Reset method is called before EOF."))); } this.stream = stream; readState = ReadState.ReadName; maxOffset = 0; offset = 0; } private void AppendValue(string value, int maxBuffer, ref int remaining) { XmlMtomReader.DecrementBufferQuota(maxBuffer, ref remaining, value.Length * 2); if (this.value == null) { this.value = value; } else { this.value += value; } } private void AppendName(string value, int maxBuffer, ref int remaining) { XmlMtomReader.DecrementBufferQuota(maxBuffer, ref remaining, value.Length * 2); if (name == null) { name = value; } else { name += value; } } } internal class BufferedReadStream : Stream { private Stream stream; private byte[] storedBuffer; private int storedLength; private int storedOffset; private bool readMore; public override bool CanWrite => false; public override bool CanSeek => false; public override bool CanRead => stream.CanRead; public override long Length { get { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Seek operation is not supported on this Stream.", stream.GetType().FullName))); } } public override long Position { get { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Seek operation is not supported on this Stream.", stream.GetType().FullName))); } set { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Seek operation is not supported on this Stream.", stream.GetType().FullName))); } } public BufferedReadStream(Stream stream) : this(stream, readMore: false) { } public BufferedReadStream(Stream stream, bool readMore) { if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream"); } this.stream = stream; this.readMore = readMore; } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { if (!CanRead) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Read operation is not supported on the Stream.", stream.GetType().FullName))); } return stream.BeginRead(buffer, offset, count, callback, state); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Write operation is not supported on this '{0}' Stream.", stream.GetType().FullName))); } public override void Close() { stream.Close(); } public override int EndRead(IAsyncResult asyncResult) { if (!CanRead) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Read operation is not supported on the Stream.", stream.GetType().FullName))); } return stream.EndRead(asyncResult); } public override void EndWrite(IAsyncResult asyncResult) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Write operation is not supported on this '{0}' Stream.", stream.GetType().FullName))); } public override void Flush() { stream.Flush(); } public override int Read(byte[] buffer, int offset, int count) { if (!CanRead) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Read operation is not supported on the Stream.", stream.GetType().FullName))); } if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > buffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", buffer.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", buffer.Length - offset))); } int num = 0; if (storedOffset < storedLength) { num = Math.Min(count, storedLength - storedOffset); Buffer.BlockCopy(storedBuffer, storedOffset, buffer, offset, num); storedOffset += num; if (num == count || !readMore) { return num; } offset += num; count -= num; } return num + stream.Read(buffer, offset, count); } public override int ReadByte() { if (storedOffset < storedLength) { return storedBuffer[storedOffset++]; } return base.ReadByte(); } public int ReadBlock(byte[] buffer, int offset, int count) { int i; int num; for (i = 0; i < count; i += num) { if ((num = Read(buffer, offset + i, count - i)) == 0) { break; } } return i; } public void Push(byte[] buffer, int offset, int count) { if (count == 0) { return; } if (storedOffset == storedLength) { if (storedBuffer == null || storedBuffer.Length < count) { storedBuffer = new byte[count]; } storedOffset = 0; storedLength = count; } else if (count <= storedOffset) { storedOffset -= count; } else if (count <= storedBuffer.Length - storedLength + storedOffset) { Buffer.BlockCopy(storedBuffer, storedOffset, storedBuffer, count, storedLength - storedOffset); storedLength += count - storedOffset; storedOffset = 0; } else { byte[] dst = new byte[count + storedLength - storedOffset]; Buffer.BlockCopy(storedBuffer, storedOffset, dst, count, storedLength - storedOffset); storedLength += count - storedOffset; storedOffset = 0; storedBuffer = dst; } Buffer.BlockCopy(buffer, offset, storedBuffer, storedOffset, count); } public override long Seek(long offset, SeekOrigin origin) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Seek operation is not supported on this Stream.", stream.GetType().FullName))); } public override void SetLength(long value) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Seek operation is not supported on this Stream.", stream.GetType().FullName))); } public override void Write(byte[] buffer, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.Runtime.Serialization.SR.GetString("Write operation is not supported on this '{0}' Stream.", stream.GetType().FullName))); } } internal static class MailBnfHelper { private static bool[] s_fqtext; private static bool[] s_ttext; private static bool[] s_digits; private static bool[] s_boundary; static MailBnfHelper() { s_fqtext = new bool[128]; s_ttext = new bool[128]; s_digits = new bool[128]; s_boundary = new bool[128]; for (int i = 1; i <= 9; i++) { s_fqtext[i] = true; } s_fqtext[11] = true; s_fqtext[12] = true; for (int j = 14; j <= 33; j++) { s_fqtext[j] = true; } for (int k = 35; k <= 91; k++) { s_fqtext[k] = true; } for (int l = 93; l <= 127; l++) { s_fqtext[l] = true; } for (int m = 33; m <= 126; m++) { s_ttext[m] = true; } s_ttext[40] = false; s_ttext[41] = false; s_ttext[60] = false; s_ttext[62] = false; s_ttext[64] = false; s_ttext[44] = false; s_ttext[59] = false; s_ttext[58] = false; s_ttext[92] = false; s_ttext[34] = false; s_ttext[47] = false; s_ttext[91] = false; s_ttext[93] = false; s_ttext[63] = false; s_ttext[61] = false; for (int n = 48; n <= 57; n++) { s_digits[n] = true; } for (int num = 48; num <= 57; num++) { s_boundary[num] = true; } for (int num2 = 65; num2 <= 90; num2++) { s_boundary[num2] = true; } for (int num3 = 97; num3 <= 122; num3++) { s_boundary[num3] = true; } s_boundary[39] = true; s_boundary[40] = true; s_boundary[41] = true; s_boundary[43] = true; s_boundary[95] = true; s_boundary[44] = true; s_boundary[45] = true; s_boundary[46] = true; s_boundary[47] = true; s_boundary[58] = true; s_boundary[61] = true; s_boundary[63] = true; s_boundary[32] = true; } public static bool SkipCFWS(string data, ref int offset) { int num = 0; while (offset < data.Length) { if (data[offset] > '\u007f') { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("MIME header has an invalid character ('{0}', {1} in hexadecimal value).", data[offset], ((int)data[offset]).ToString("X", CultureInfo.InvariantCulture)))); } if (data[offset] == '\\' && num > 0) { offset += 2; } else if (data[offset] == '(') { num++; } else if (data[offset] == ')') { num--; } else if (data[offset] != ' ' && data[offset] != '\t' && num == 0) { return true; } offset++; } return false; } public static string ReadQuotedString(string data, ref int offset, StringBuilder builder) { int num = ++offset; StringBuilder stringBuilder = ((builder != null) ? builder : new StringBuilder()); while (offset < data.Length) { if (data[offset] == '\\') { stringBuilder.Append(data, num, offset - num); num = ++offset; } else { if (data[offset] == '"') { stringBuilder.Append(data, num, offset - num); offset++; if (builder == null) { return stringBuilder.ToString(); } return null; } if (data[offset] >= s_fqtext.Length || !s_fqtext[(uint)data[offset]]) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("MIME header has an invalid character ('{0}', {1} in hexadecimal value).", data[offset], ((int)data[offset]).ToString("X", CultureInfo.InvariantCulture)))); } } offset++; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("Malformed MIME header."))); } public static string ReadParameterAttribute(string data, ref int offset, StringBuilder builder) { if (!SkipCFWS(data, ref offset)) { return null; } return ReadToken(data, ref offset, null); } public static string ReadParameterValue(string data, ref int offset, StringBuilder builder) { if (!SkipCFWS(data, ref offset)) { return string.Empty; } if (offset < data.Length && data[offset] == '"') { return ReadQuotedString(data, ref offset, builder); } return ReadToken(data, ref offset, builder); } public static string ReadToken(string data, ref int offset, StringBuilder builder) { int num = offset; while (offset < data.Length) { if (data[offset] > s_ttext.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("MIME header has an invalid character ('{0}', {1} in hexadecimal value).", data[offset], ((int)data[offset]).ToString("X", CultureInfo.InvariantCulture)))); } if (!s_ttext[(uint)data[offset]]) { break; } offset++; } return data.Substring(num, offset - num); } public static string ReadDigits(string data, ref int offset, StringBuilder builder) { int num = offset; StringBuilder stringBuilder = ((builder != null) ? builder : new StringBuilder()); while (offset < data.Length && data[offset] < s_digits.Length && s_digits[(uint)data[offset]]) { offset++; } stringBuilder.Append(data, num, offset - num); if (builder == null) { return stringBuilder.ToString(); } return null; } public static bool IsValidMimeBoundary(string data) { int num = data?.Length ?? 0; if (num == 0 || num > 70 || data[num - 1] == ' ') { return false; } for (int i = 0; i < num; i++) { if (data[i] >= s_boundary.Length || !s_boundary[(uint)data[i]]) { return false; } } return true; } } public interface IXmlMtomWriterInitializer { void SetOutput(Stream stream, Encoding encoding, int maxSizeInBytes, string startInfo, string boundary, string startUri, bool writeMessageHeaders, bool ownsStream); } internal class XmlMtomWriter : XmlDictionaryWriter, IXmlMtomWriterInitializer { private static class MimeBoundaryGenerator { private static long id; private static string prefix; static MimeBoundaryGenerator() { prefix = Guid.NewGuid().ToString() + "+id="; } internal static string Next() { long num = Interlocked.Increment(ref id); return string.Format(CultureInfo.InvariantCulture, "{0}{1}", prefix, num); } } private class MimePart { internal IList binaryData; internal string contentID; internal string contentType; internal string contentTransferEncoding; internal int sizeInBytes; internal MimePart(IList binaryData, string contentID, string contentType, string contentTransferEncoding, int sizeOfBufferedBinaryData, int maxSizeInBytes) { this.binaryData = binaryData; this.contentID = contentID; this.contentType = contentType ?? MtomGlobals.DefaultContentTypeForBinary; this.contentTransferEncoding = contentTransferEncoding; sizeInBytes = GetSize(contentID, contentType, contentTransferEncoding, sizeOfBufferedBinaryData, maxSizeInBytes); } private static int GetSize(string contentID, string contentType, string contentTransferEncoding, int sizeOfBufferedBinaryData, int maxSizeInBytes) { int num = ValidateSizeOfMessage(maxSizeInBytes, 0, MimeGlobals.CRLF.Length * 3); if (contentTransferEncoding != null) { num += ValidateSizeOfMessage(maxSizeInBytes, num, MimeWriter.GetHeaderSize(MimeGlobals.ContentTransferEncodingHeader, contentTransferEncoding, maxSizeInBytes)); } if (contentType != null) { num += ValidateSizeOfMessage(maxSizeInBytes, num, MimeWriter.GetHeaderSize(MimeGlobals.ContentTypeHeader, contentType, maxSizeInBytes)); } if (contentID != null) { num += ValidateSizeOfMessage(maxSizeInBytes, num, MimeWriter.GetHeaderSize(MimeGlobals.ContentIDHeader, contentID, maxSizeInBytes)); num += ValidateSizeOfMessage(maxSizeInBytes, num, 2); } return num + ValidateSizeOfMessage(maxSizeInBytes, num, sizeOfBufferedBinaryData); } } private const int MaxInlinedBytes = 767; private int maxSizeInBytes; private XmlDictionaryWriter writer; private XmlDictionaryWriter infosetWriter; private MimeWriter mimeWriter; private Encoding encoding; private bool isUTF8; private string contentID; private string contentType; private string initialContentTypeForRootPart; private string initialContentTypeForMimeMessage; private MemoryStream contentTypeStream; private List mimeParts; private IList binaryDataChunks; private int depth; private int totalSizeOfMimeParts; private int sizeOfBufferedBinaryData; private char[] chars; private byte[] bytes; private bool isClosed; private bool ownsStream; private XmlDictionaryWriter Writer { get { if (!IsInitialized) { Initialize(); } return writer; } } private bool IsInitialized => initialContentTypeForRootPart == null; public override XmlWriterSettings Settings => Writer.Settings; public override WriteState WriteState => Writer.WriteState; public override string XmlLang => Writer.XmlLang; public override XmlSpace XmlSpace => Writer.XmlSpace; public void SetOutput(Stream stream, Encoding encoding, int maxSizeInBytes, string startInfo, string boundary, string startUri, bool writeMessageHeaders, bool ownsStream) { if (encoding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encoding"); } if (maxSizeInBytes < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxSizeInBytes", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } this.maxSizeInBytes = maxSizeInBytes; this.encoding = encoding; isUTF8 = IsUTF8Encoding(encoding); Initialize(stream, startInfo, boundary, startUri, writeMessageHeaders, ownsStream); } private void Initialize(Stream stream, string startInfo, string boundary, string startUri, bool writeMessageHeaders, bool ownsStream) { if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream"); } if (startInfo == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("startInfo"); } if (boundary == null) { boundary = GetBoundaryString(); } if (startUri == null) { startUri = GenerateUriForMimePart(0); } if (!MailBnfHelper.IsValidMimeBoundary(boundary)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("MIME boundary is invalid: '{0}'.", boundary), "boundary")); } this.ownsStream = ownsStream; isClosed = false; depth = 0; totalSizeOfMimeParts = 0; sizeOfBufferedBinaryData = 0; binaryDataChunks = null; contentType = null; contentTypeStream = null; contentID = startUri; if (mimeParts != null) { mimeParts.Clear(); } mimeWriter = new MimeWriter(stream, boundary); initialContentTypeForRootPart = GetContentTypeForRootMimePart(encoding, startInfo); if (writeMessageHeaders) { initialContentTypeForMimeMessage = GetContentTypeForMimeMessage(boundary, startUri, startInfo); } } private void Initialize() { if (isClosed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("The XmlWriter is closed."))); } if (initialContentTypeForRootPart != null) { if (initialContentTypeForMimeMessage != null) { mimeWriter.StartPreface(); mimeWriter.WriteHeader(MimeGlobals.MimeVersionHeader, MimeGlobals.DefaultVersion); mimeWriter.WriteHeader(MimeGlobals.ContentTypeHeader, initialContentTypeForMimeMessage); initialContentTypeForMimeMessage = null; } WriteMimeHeaders(contentID, initialContentTypeForRootPart, isUTF8 ? MimeGlobals.Encoding8bit : MimeGlobals.EncodingBinary); Stream contentStream = mimeWriter.GetContentStream(); if (!(writer is IXmlTextWriterInitializer xmlTextWriterInitializer)) { writer = XmlDictionaryWriter.CreateTextWriter(contentStream, encoding, ownsStream); } else { xmlTextWriterInitializer.SetOutput(contentStream, encoding, ownsStream); } contentID = null; initialContentTypeForRootPart = null; } } private static string GetBoundaryString() { return MimeBoundaryGenerator.Next(); } internal static bool IsUTF8Encoding(Encoding encoding) { return encoding.WebName == "utf-8"; } private static string GetContentTypeForMimeMessage(string boundary, string startUri, string startInfo) { StringBuilder stringBuilder = new StringBuilder(string.Format(CultureInfo.InvariantCulture, "{0}/{1};{2}=\"{3}\";{4}=\"{5}\"", MtomGlobals.MediaType, MtomGlobals.MediaSubtype, MtomGlobals.TypeParam, MtomGlobals.XopType, MtomGlobals.BoundaryParam, boundary)); if (startUri != null && startUri.Length > 0) { stringBuilder.AppendFormat(CultureInfo.InvariantCulture, ";{0}=\"<{1}>\"", MtomGlobals.StartParam, startUri); } if (startInfo != null && startInfo.Length > 0) { stringBuilder.AppendFormat(CultureInfo.InvariantCulture, ";{0}=\"{1}\"", MtomGlobals.StartInfoParam, startInfo); } return stringBuilder.ToString(); } private static string GetContentTypeForRootMimePart(Encoding encoding, string startInfo) { string text = string.Format(CultureInfo.InvariantCulture, "{0};{1}={2}", MtomGlobals.XopType, MtomGlobals.CharsetParam, CharSet(encoding)); if (startInfo != null) { text = string.Format(CultureInfo.InvariantCulture, "{0};{1}=\"{2}\"", text, MtomGlobals.TypeParam, startInfo); } return text; } private static string CharSet(Encoding enc) { string webName = enc.WebName; if (string.Compare(webName, Encoding.UTF8.WebName, StringComparison.OrdinalIgnoreCase) == 0) { return webName; } if (string.Compare(webName, Encoding.Unicode.WebName, StringComparison.OrdinalIgnoreCase) == 0) { return "utf-16LE"; } if (string.Compare(webName, Encoding.BigEndianUnicode.WebName, StringComparison.OrdinalIgnoreCase) == 0) { return "utf-16BE"; } return webName; } public override void WriteStartElement(string prefix, string localName, string ns) { WriteBase64InlineIfPresent(); ThrowIfElementIsXOPInclude(prefix, localName, ns); Writer.WriteStartElement(prefix, localName, ns); depth++; } public override void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString ns) { if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localName"); } WriteBase64InlineIfPresent(); ThrowIfElementIsXOPInclude(prefix, localName.Value, ns?.Value); Writer.WriteStartElement(prefix, localName, ns); depth++; } private void ThrowIfElementIsXOPInclude(string prefix, string localName, string ns) { if (ns == null && Writer is XmlBaseWriter xmlBaseWriter) { ns = xmlBaseWriter.LookupNamespace(prefix); } if (localName == MtomGlobals.XopIncludeLocalName && ns == MtomGlobals.XopIncludeNamespace) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MTOM data must not contain xop:Include element. '{0}' element in '{1}' namespace.", MtomGlobals.XopIncludeLocalName, MtomGlobals.XopIncludeNamespace))); } } public override void WriteEndElement() { WriteXOPInclude(); Writer.WriteEndElement(); depth--; WriteXOPBinaryParts(); } public override void WriteFullEndElement() { WriteXOPInclude(); Writer.WriteFullEndElement(); depth--; WriteXOPBinaryParts(); } public override void WriteValue(IStreamProvider value) { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } if (Writer.WriteState == WriteState.Element) { if (binaryDataChunks == null) { binaryDataChunks = new List(); contentID = GenerateUriForMimePart((mimeParts == null) ? 1 : (mimeParts.Count + 1)); } binaryDataChunks.Add(new MtomBinaryData(value)); } else { Writer.WriteValue(value); } } public override void WriteBase64(byte[] buffer, int index, int count) { if (Writer.WriteState == WriteState.Element) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("buffer")); } if (index < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - index) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", buffer.Length - index))); } if (binaryDataChunks == null) { binaryDataChunks = new List(); contentID = GenerateUriForMimePart((mimeParts == null) ? 1 : (mimeParts.Count + 1)); } int num = ValidateSizeOfMessage(maxSizeInBytes, 0, totalSizeOfMimeParts); num += ValidateSizeOfMessage(maxSizeInBytes, num, sizeOfBufferedBinaryData); num += ValidateSizeOfMessage(maxSizeInBytes, num, count); sizeOfBufferedBinaryData += count; binaryDataChunks.Add(new MtomBinaryData(buffer, index, count)); } else { Writer.WriteBase64(buffer, index, count); } } internal static int ValidateSizeOfMessage(int maxSize, int offset, int size) { if (size > maxSize - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("MTOM exceeded max size in bytes. The maximum size is {0}.", maxSize))); } return size; } private void WriteBase64InlineIfPresent() { if (binaryDataChunks != null) { WriteBase64Inline(); } } private void WriteBase64Inline() { foreach (MtomBinaryData binaryDataChunk in binaryDataChunks) { if (binaryDataChunk.type == MtomBinaryDataType.Provider) { Writer.WriteValue(binaryDataChunk.provider); } else { Writer.WriteBase64(binaryDataChunk.chunk, 0, binaryDataChunk.chunk.Length); } } sizeOfBufferedBinaryData = 0; binaryDataChunks = null; contentType = null; contentID = null; } private void WriteXOPInclude() { if (binaryDataChunks == null) { return; } bool flag = true; long num = 0L; foreach (MtomBinaryData binaryDataChunk in binaryDataChunks) { long length = binaryDataChunk.Length; if (length < 0 || length > 767 - num) { flag = false; break; } num += length; } if (flag) { WriteBase64Inline(); return; } if (mimeParts == null) { mimeParts = new List(); } MimePart mimePart = new MimePart(binaryDataChunks, contentID, contentType, MimeGlobals.EncodingBinary, sizeOfBufferedBinaryData, maxSizeInBytes); mimeParts.Add(mimePart); totalSizeOfMimeParts += ValidateSizeOfMessage(maxSizeInBytes, totalSizeOfMimeParts, mimePart.sizeInBytes); totalSizeOfMimeParts += ValidateSizeOfMessage(maxSizeInBytes, totalSizeOfMimeParts, mimeWriter.GetBoundarySize()); Writer.WriteStartElement(MtomGlobals.XopIncludePrefix, MtomGlobals.XopIncludeLocalName, MtomGlobals.XopIncludeNamespace); Writer.WriteStartAttribute(MtomGlobals.XopIncludeHrefLocalName, MtomGlobals.XopIncludeHrefNamespace); Writer.WriteValue(string.Format(CultureInfo.InvariantCulture, "{0}{1}", MimeGlobals.ContentIDScheme, contentID)); Writer.WriteEndAttribute(); Writer.WriteEndElement(); binaryDataChunks = null; sizeOfBufferedBinaryData = 0; contentType = null; contentID = null; } public static string GenerateUriForMimePart(int index) { return string.Format(CultureInfo.InvariantCulture, "http://tempuri.org/{0}/{1}", index, DateTime.Now.Ticks); } private void WriteXOPBinaryParts() { if (depth > 0 || mimeWriter.WriteState == MimeWriterState.Closed) { return; } if (Writer.WriteState != WriteState.Closed) { Writer.Flush(); } if (mimeParts != null) { foreach (MimePart mimePart in mimeParts) { WriteMimeHeaders(mimePart.contentID, mimePart.contentType, mimePart.contentTransferEncoding); Stream contentStream = mimeWriter.GetContentStream(); int num = 256; int num2 = 0; byte[] buffer = new byte[num]; Stream stream = null; foreach (MtomBinaryData binaryDatum in mimePart.binaryData) { if (binaryDatum.type == MtomBinaryDataType.Provider) { stream = binaryDatum.provider.GetStream(); if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Stream returned by IStreamProvider cannot be null."))); } while (true) { num2 = stream.Read(buffer, 0, num); if (num2 <= 0) { break; } contentStream.Write(buffer, 0, num2); if (num < 65536 && num2 == num) { num *= 16; buffer = new byte[num]; } } binaryDatum.provider.ReleaseStream(stream); } else { contentStream.Write(binaryDatum.chunk, 0, binaryDatum.chunk.Length); } } } mimeParts.Clear(); } mimeWriter.Close(); } private void WriteMimeHeaders(string contentID, string contentType, string contentTransferEncoding) { mimeWriter.StartPart(); if (contentID != null) { mimeWriter.WriteHeader(MimeGlobals.ContentIDHeader, string.Format(CultureInfo.InvariantCulture, "<{0}>", contentID)); } if (contentTransferEncoding != null) { mimeWriter.WriteHeader(MimeGlobals.ContentTransferEncodingHeader, contentTransferEncoding); } if (contentType != null) { mimeWriter.WriteHeader(MimeGlobals.ContentTypeHeader, contentType); } } public override void Close() { if (isClosed) { return; } isClosed = true; if (IsInitialized) { WriteXOPInclude(); if (Writer.WriteState == WriteState.Element || Writer.WriteState == WriteState.Attribute || Writer.WriteState == WriteState.Content) { Writer.WriteEndDocument(); } Writer.Flush(); depth = 0; WriteXOPBinaryParts(); Writer.Close(); } } private void CheckIfStartContentTypeAttribute(string localName, string ns) { if (localName != null && localName == MtomGlobals.MimeContentTypeLocalName && ns != null && (ns == MtomGlobals.MimeContentTypeNamespace200406 || ns == MtomGlobals.MimeContentTypeNamespace200505)) { contentTypeStream = new MemoryStream(); infosetWriter = Writer; writer = XmlDictionaryWriter.CreateBinaryWriter(contentTypeStream); Writer.WriteStartElement("Wrapper"); Writer.WriteStartAttribute(localName, ns); } } private void CheckIfEndContentTypeAttribute() { if (contentTypeStream == null) { return; } Writer.WriteEndAttribute(); Writer.WriteEndElement(); Writer.Flush(); contentTypeStream.Position = 0L; XmlReader xmlReader = XmlDictionaryReader.CreateBinaryReader(contentTypeStream, null, XmlDictionaryReaderQuotas.Max, null, null); while (xmlReader.Read()) { if (xmlReader.IsStartElement("Wrapper")) { contentType = xmlReader.GetAttribute(MtomGlobals.MimeContentTypeLocalName, MtomGlobals.MimeContentTypeNamespace200406); if (contentType == null) { contentType = xmlReader.GetAttribute(MtomGlobals.MimeContentTypeLocalName, MtomGlobals.MimeContentTypeNamespace200505); } break; } } writer = infosetWriter; infosetWriter = null; contentTypeStream = null; if (contentType != null) { Writer.WriteString(contentType); } } public override void Flush() { if (IsInitialized) { Writer.Flush(); } } public override string LookupPrefix(string ns) { return Writer.LookupPrefix(ns); } public override void WriteAttributes(XmlReader reader, bool defattr) { Writer.WriteAttributes(reader, defattr); } public override void WriteBinHex(byte[] buffer, int index, int count) { WriteBase64InlineIfPresent(); Writer.WriteBinHex(buffer, index, count); } public override void WriteCData(string text) { WriteBase64InlineIfPresent(); Writer.WriteCData(text); } public override void WriteCharEntity(char ch) { WriteBase64InlineIfPresent(); Writer.WriteCharEntity(ch); } public override void WriteChars(char[] buffer, int index, int count) { WriteBase64InlineIfPresent(); Writer.WriteChars(buffer, index, count); } public override void WriteComment(string text) { if (depth != 0 || mimeWriter.WriteState != MimeWriterState.Closed) { WriteBase64InlineIfPresent(); Writer.WriteComment(text); } } public override void WriteDocType(string name, string pubid, string sysid, string subset) { WriteBase64InlineIfPresent(); Writer.WriteDocType(name, pubid, sysid, subset); } public override void WriteEndAttribute() { CheckIfEndContentTypeAttribute(); Writer.WriteEndAttribute(); } public override void WriteEndDocument() { WriteXOPInclude(); Writer.WriteEndDocument(); depth = 0; WriteXOPBinaryParts(); } public override void WriteEntityRef(string name) { WriteBase64InlineIfPresent(); Writer.WriteEntityRef(name); } public override void WriteName(string name) { WriteBase64InlineIfPresent(); Writer.WriteName(name); } public override void WriteNmToken(string name) { WriteBase64InlineIfPresent(); Writer.WriteNmToken(name); } protected override void WriteTextNode(XmlDictionaryReader reader, bool attribute) { Type valueType = reader.ValueType; if (valueType == typeof(string)) { if (reader.CanReadValueChunk) { if (chars == null) { chars = new char[256]; } int count; while ((count = reader.ReadValueChunk(chars, 0, chars.Length)) > 0) { WriteChars(chars, 0, count); } } else { WriteString(reader.Value); } if (!attribute) { reader.Read(); } } else if (valueType == typeof(byte[])) { if (reader.CanReadBinaryContent) { if (bytes == null) { bytes = new byte[384]; } int count2; while ((count2 = reader.ReadValueAsBase64(bytes, 0, bytes.Length)) > 0) { WriteBase64(bytes, 0, count2); } } else { WriteString(reader.Value); } if (!attribute) { reader.Read(); } } else { base.WriteTextNode(reader, attribute); } } public override void WriteNode(XPathNavigator navigator, bool defattr) { WriteBase64InlineIfPresent(); Writer.WriteNode(navigator, defattr); } public override void WriteProcessingInstruction(string name, string text) { WriteBase64InlineIfPresent(); Writer.WriteProcessingInstruction(name, text); } public override void WriteQualifiedName(string localName, string namespaceUri) { WriteBase64InlineIfPresent(); Writer.WriteQualifiedName(localName, namespaceUri); } public override void WriteRaw(char[] buffer, int index, int count) { WriteBase64InlineIfPresent(); Writer.WriteRaw(buffer, index, count); } public override void WriteRaw(string data) { WriteBase64InlineIfPresent(); Writer.WriteRaw(data); } public override void WriteStartAttribute(string prefix, string localName, string ns) { Writer.WriteStartAttribute(prefix, localName, ns); CheckIfStartContentTypeAttribute(localName, ns); } public override void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString ns) { Writer.WriteStartAttribute(prefix, localName, ns); if (localName != null && ns != null) { CheckIfStartContentTypeAttribute(localName.Value, ns.Value); } } public override void WriteStartDocument() { Writer.WriteStartDocument(); } public override void WriteStartDocument(bool standalone) { Writer.WriteStartDocument(standalone); } public override void WriteString(string text) { if (depth != 0 || mimeWriter.WriteState != MimeWriterState.Closed || !XmlConverter.IsWhitespace(text)) { WriteBase64InlineIfPresent(); Writer.WriteString(text); } } public override void WriteString(XmlDictionaryString value) { if (depth != 0 || mimeWriter.WriteState != MimeWriterState.Closed || !XmlConverter.IsWhitespace(value.Value)) { WriteBase64InlineIfPresent(); Writer.WriteString(value); } } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { WriteBase64InlineIfPresent(); Writer.WriteSurrogateCharEntity(lowChar, highChar); } public override void WriteWhitespace(string whitespace) { if (depth != 0 || mimeWriter.WriteState != MimeWriterState.Closed) { WriteBase64InlineIfPresent(); Writer.WriteWhitespace(whitespace); } } public override void WriteValue(object value) { if (value is IStreamProvider value2) { WriteValue(value2); return; } WriteBase64InlineIfPresent(); Writer.WriteValue(value); } public override void WriteValue(string value) { if (depth != 0 || mimeWriter.WriteState != MimeWriterState.Closed || !XmlConverter.IsWhitespace(value)) { WriteBase64InlineIfPresent(); Writer.WriteValue(value); } } public override void WriteValue(bool value) { WriteBase64InlineIfPresent(); Writer.WriteValue(value); } public override void WriteValue(DateTime value) { WriteBase64InlineIfPresent(); Writer.WriteValue(value); } public override void WriteValue(double value) { WriteBase64InlineIfPresent(); Writer.WriteValue(value); } public override void WriteValue(int value) { WriteBase64InlineIfPresent(); Writer.WriteValue(value); } public override void WriteValue(long value) { WriteBase64InlineIfPresent(); Writer.WriteValue(value); } public override void WriteValue(XmlDictionaryString value) { if (depth != 0 || mimeWriter.WriteState != MimeWriterState.Closed || !XmlConverter.IsWhitespace(value.Value)) { WriteBase64InlineIfPresent(); Writer.WriteValue(value); } } public override void WriteXmlnsAttribute(string prefix, string ns) { Writer.WriteXmlnsAttribute(prefix, ns); } public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) { Writer.WriteXmlnsAttribute(prefix, ns); } } internal static class MtomGlobals { internal static string XopIncludeLocalName = "Include"; internal static string XopIncludeNamespace = "http://www.w3.org/2004/08/xop/include"; internal static string XopIncludePrefix = "xop"; internal static string XopIncludeHrefLocalName = "href"; internal static string XopIncludeHrefNamespace = string.Empty; internal static string MediaType = "multipart"; internal static string MediaSubtype = "related"; internal static string BoundaryParam = "boundary"; internal static string TypeParam = "type"; internal static string XopMediaType = "application"; internal static string XopMediaSubtype = "xop+xml"; internal static string XopType = "application/xop+xml"; internal static string StartParam = "start"; internal static string StartInfoParam = "start-info"; internal static string ActionParam = "action"; internal static string CharsetParam = "charset"; internal static string MimeContentTypeLocalName = "contentType"; internal static string MimeContentTypeNamespace200406 = "http://www.w3.org/2004/06/xmlmime"; internal static string MimeContentTypeNamespace200505 = "http://www.w3.org/2005/05/xmlmime"; internal static string DefaultContentTypeForBinary = "application/octet-stream"; } internal static class MimeGlobals { internal static string MimeVersionHeader = "MIME-Version"; internal static string DefaultVersion = "1.0"; internal static string ContentIDScheme = "cid:"; internal static string ContentIDHeader = "Content-ID"; internal static string ContentTypeHeader = "Content-Type"; internal static string ContentTransferEncodingHeader = "Content-Transfer-Encoding"; internal static string EncodingBinary = "binary"; internal static string Encoding8bit = "8bit"; internal static byte[] COLONSPACE = new byte[2] { 58, 32 }; internal static byte[] DASHDASH = new byte[2] { 45, 45 }; internal static byte[] CRLF = new byte[2] { 13, 10 }; internal static byte[] BoundaryPrefix = new byte[4] { 13, 10, 45, 45 }; } internal enum MimeWriterState { Start, StartPreface, StartPart, Header, Content, Closed } internal class MimeWriter { private Stream stream; private byte[] boundaryBytes; private MimeWriterState state; private BufferedWrite bufferedWrite; private Stream contentStream; internal MimeWriterState WriteState => state; internal MimeWriter(Stream stream, string boundary) { if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream"); } if (boundary == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("boundary"); } this.stream = stream; boundaryBytes = GetBoundaryBytes(boundary); state = MimeWriterState.Start; bufferedWrite = new BufferedWrite(); } internal static int GetHeaderSize(string name, string value, int maxSizeInBytes) { if (name == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name"); } if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } int num = XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, 0, MimeGlobals.COLONSPACE.Length + MimeGlobals.CRLF.Length); num += XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, num, name.Length); return num + XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, num, value.Length); } internal static byte[] GetBoundaryBytes(string boundary) { byte[] array = new byte[boundary.Length + MimeGlobals.BoundaryPrefix.Length]; for (int i = 0; i < MimeGlobals.BoundaryPrefix.Length; i++) { array[i] = MimeGlobals.BoundaryPrefix[i]; } Encoding.ASCII.GetBytes(boundary, 0, boundary.Length, array, MimeGlobals.BoundaryPrefix.Length); return array; } internal int GetBoundarySize() { return boundaryBytes.Length; } internal void StartPreface() { if (state != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("MIME writer is at invalid state for starting preface.", state.ToString()))); } state = MimeWriterState.StartPreface; } internal void StartPart() { MimeWriterState mimeWriterState = state; if (mimeWriterState == MimeWriterState.StartPart || mimeWriterState == MimeWriterState.Closed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("MIME writer is at invalid state for starting a part.", state.ToString()))); } state = MimeWriterState.StartPart; if (contentStream != null) { contentStream.Flush(); contentStream = null; } bufferedWrite.Write(boundaryBytes); bufferedWrite.Write(MimeGlobals.CRLF); } internal void Close() { MimeWriterState mimeWriterState = state; if (mimeWriterState == MimeWriterState.Closed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("MIME writer is at invalid state for closing.", state.ToString()))); } state = MimeWriterState.Closed; if (contentStream != null) { contentStream.Flush(); contentStream = null; } bufferedWrite.Write(boundaryBytes); bufferedWrite.Write(MimeGlobals.DASHDASH); bufferedWrite.Write(MimeGlobals.CRLF); Flush(); } private void Flush() { if (bufferedWrite.Length > 0) { stream.Write(bufferedWrite.GetBuffer(), 0, bufferedWrite.Length); bufferedWrite.Reset(); } } internal void WriteHeader(string name, string value) { if (name == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name"); } if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } MimeWriterState mimeWriterState = state; if (mimeWriterState == MimeWriterState.Start || (uint)(mimeWriterState - 4) <= 1u) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("MIME writer is at invalid state for header.", state.ToString()))); } state = MimeWriterState.Header; bufferedWrite.Write(name); bufferedWrite.Write(MimeGlobals.COLONSPACE); bufferedWrite.Write(value); bufferedWrite.Write(MimeGlobals.CRLF); } internal Stream GetContentStream() { MimeWriterState mimeWriterState = state; if (mimeWriterState == MimeWriterState.Start || (uint)(mimeWriterState - 4) <= 1u) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.Runtime.Serialization.SR.GetString("MIME writer is at invalid state for content.", state.ToString()))); } state = MimeWriterState.Content; bufferedWrite.Write(MimeGlobals.CRLF); Flush(); contentStream = stream; return contentStream; } } internal class BufferedWrite { private byte[] buffer; private int offset; internal int Length => offset; internal BufferedWrite() : this(256) { } internal BufferedWrite(int initialSize) { buffer = new byte[initialSize]; } private void EnsureBuffer(int count) { int num = buffer.Length; if (count <= num - offset) { return; } int num2 = num; do { if (num2 == int.MaxValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Write buffer overflow."))); } num2 = ((num2 < 1073741823) ? (num2 * 2) : int.MaxValue); } while (count > num2 - offset); byte[] dst = new byte[num2]; Buffer.BlockCopy(buffer, 0, dst, 0, offset); buffer = dst; } internal byte[] GetBuffer() { return buffer; } internal void Reset() { offset = 0; } internal void Write(byte[] value) { Write(value, 0, value.Length); } internal void Write(byte[] value, int index, int count) { EnsureBuffer(count); Buffer.BlockCopy(value, index, buffer, offset, count); offset += count; } internal void Write(string value) { Write(value, 0, value.Length); } internal void Write(string value, int index, int count) { EnsureBuffer(count); for (int i = 0; i < count; i++) { char c = value[index + i]; if (c > 'ÿ') { object[] obj = new object[2] { c, null }; int num = c; obj[1] = num.ToString("X", CultureInfo.InvariantCulture); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("MIME header has an invalid character ('{0}', {1} in hexadecimal value).", obj))); } buffer[offset + i] = (byte)c; } offset += count; } } internal enum MtomBinaryDataType { Provider, Segment } internal class MtomBinaryData { internal MtomBinaryDataType type; internal IStreamProvider provider; internal byte[] chunk; internal long Length { get { if (type == MtomBinaryDataType.Segment) { return chunk.Length; } return -1L; } } internal MtomBinaryData(IStreamProvider provider) { type = MtomBinaryDataType.Provider; this.provider = provider; } internal MtomBinaryData(byte[] buffer, int offset, int count) { type = MtomBinaryDataType.Segment; chunk = new byte[count]; Buffer.BlockCopy(buffer, offset, chunk, 0, count); } } internal abstract class XmlNodeWriter { private class XmlNullNodeWriter : XmlNodeWriter { public override void Flush() { } public override void Close() { } public override void WriteDeclaration() { } public override void WriteComment(string text) { } public override void WriteCData(string text) { } public override void WriteStartElement(string prefix, string localName) { } public override void WriteStartElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { } public override void WriteStartElement(string prefix, XmlDictionaryString localName) { } public override void WriteEndStartElement(bool isEmpty) { } public override void WriteEndElement(string prefix, string localName) { } public override void WriteEndElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { } public override void WriteXmlnsAttribute(string prefix, string ns) { } public override void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] nsBuffer, int nsOffset, int nsLength) { } public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) { } public override void WriteStartAttribute(string prefix, string localName) { } public override void WriteStartAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { } public override void WriteStartAttribute(string prefix, XmlDictionaryString localName) { } public override void WriteEndAttribute() { } public override void WriteCharEntity(int ch) { } public override void WriteEscapedText(string value) { } public override void WriteEscapedText(XmlDictionaryString value) { } public override void WriteEscapedText(char[] chars, int offset, int count) { } public override void WriteEscapedText(byte[] buffer, int offset, int count) { } public override void WriteText(string value) { } public override void WriteText(XmlDictionaryString value) { } public override void WriteText(char[] chars, int offset, int count) { } public override void WriteText(byte[] buffer, int offset, int count) { } public override void WriteInt32Text(int value) { } public override void WriteInt64Text(long value) { } public override void WriteBoolText(bool value) { } public override void WriteUInt64Text(ulong value) { } public override void WriteFloatText(float value) { } public override void WriteDoubleText(double value) { } public override void WriteDecimalText(decimal value) { } public override void WriteDateTimeText(DateTime value) { } public override void WriteUniqueIdText(UniqueId value) { } public override void WriteTimeSpanText(TimeSpan value) { } public override void WriteGuidText(Guid value) { } public override void WriteStartListText() { } public override void WriteListSeparator() { } public override void WriteEndListText() { } public override void WriteBase64Text(byte[] trailBuffer, int trailCount, byte[] buffer, int offset, int count) { } public override void WriteQualifiedName(string prefix, XmlDictionaryString localName) { } } private class WriteBase64TextAsyncResult : ScheduleActionItemAsyncResult { private byte[] trailBuffer; private int trailCount; private byte[] buffer; private int offset; private int count; private XmlNodeWriter nodeWriter; public WriteBase64TextAsyncResult(byte[] trailBuffer, int trailCount, byte[] buffer, int offset, int count, XmlNodeWriter nodeWriter, AsyncCallback callback, object state) : base(callback, state) { this.trailBuffer = trailBuffer; this.trailCount = trailCount; this.buffer = buffer; this.offset = offset; this.count = count; this.nodeWriter = nodeWriter; ((ScheduleActionItemAsyncResult)this).Schedule(); } protected override void OnDoWork() { nodeWriter.WriteBase64Text(trailBuffer, trailCount, buffer, offset, count); } } private static XmlNodeWriter nullNodeWriter; public static XmlNodeWriter Null { get { if (nullNodeWriter == null) { nullNodeWriter = new XmlNullNodeWriter(); } return nullNodeWriter; } } internal virtual AsyncCompletionResult WriteBase64TextAsync(AsyncEventArgs state) { throw Fx.AssertAndThrow("WriteBase64TextAsync not implemented."); } public virtual IAsyncResult BeginWriteBase64Text(byte[] trailBuffer, int trailCount, byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return (IAsyncResult)new WriteBase64TextAsyncResult(trailBuffer, trailCount, buffer, offset, count, this, callback, state); } public virtual void EndWriteBase64Text(IAsyncResult result) { ScheduleActionItemAsyncResult.End(result); } public abstract void Flush(); public abstract void Close(); public abstract void WriteDeclaration(); public abstract void WriteComment(string text); public abstract void WriteCData(string text); public abstract void WriteStartElement(string prefix, string localName); public virtual void WriteStartElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteStartElement(Encoding.UTF8.GetString(prefixBuffer, prefixOffset, prefixLength), Encoding.UTF8.GetString(localNameBuffer, localNameOffset, localNameLength)); } public abstract void WriteStartElement(string prefix, XmlDictionaryString localName); public abstract void WriteEndStartElement(bool isEmpty); public abstract void WriteEndElement(string prefix, string localName); public virtual void WriteEndElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteEndElement(Encoding.UTF8.GetString(prefixBuffer, prefixOffset, prefixLength), Encoding.UTF8.GetString(localNameBuffer, localNameOffset, localNameLength)); } public abstract void WriteXmlnsAttribute(string prefix, string ns); public virtual void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] nsBuffer, int nsOffset, int nsLength) { WriteXmlnsAttribute(Encoding.UTF8.GetString(prefixBuffer, prefixOffset, prefixLength), Encoding.UTF8.GetString(nsBuffer, nsOffset, nsLength)); } public abstract void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns); public abstract void WriteStartAttribute(string prefix, string localName); public virtual void WriteStartAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteStartAttribute(Encoding.UTF8.GetString(prefixBuffer, prefixOffset, prefixLength), Encoding.UTF8.GetString(localNameBuffer, localNameOffset, localNameLength)); } public abstract void WriteStartAttribute(string prefix, XmlDictionaryString localName); public abstract void WriteEndAttribute(); public abstract void WriteCharEntity(int ch); public abstract void WriteEscapedText(string value); public abstract void WriteEscapedText(XmlDictionaryString value); public abstract void WriteEscapedText(char[] chars, int offset, int count); public abstract void WriteEscapedText(byte[] buffer, int offset, int count); public abstract void WriteText(string value); public abstract void WriteText(XmlDictionaryString value); public abstract void WriteText(char[] chars, int offset, int count); public abstract void WriteText(byte[] buffer, int offset, int count); public abstract void WriteInt32Text(int value); public abstract void WriteInt64Text(long value); public abstract void WriteBoolText(bool value); public abstract void WriteUInt64Text(ulong value); public abstract void WriteFloatText(float value); public abstract void WriteDoubleText(double value); public abstract void WriteDecimalText(decimal value); public abstract void WriteDateTimeText(DateTime value); public abstract void WriteUniqueIdText(UniqueId value); public abstract void WriteTimeSpanText(TimeSpan value); public abstract void WriteGuidText(Guid value); public abstract void WriteStartListText(); public abstract void WriteListSeparator(); public abstract void WriteEndListText(); public abstract void WriteBase64Text(byte[] trailBuffer, int trailCount, byte[] buffer, int offset, int count); public abstract void WriteQualifiedName(string prefix, XmlDictionaryString localName); } internal class XmlNodeWriterWriteBase64TextArgs { internal byte[] TrailBuffer { get; set; } internal int TrailCount { get; set; } internal byte[] Buffer { get; set; } internal int Offset { get; set; } internal int Count { get; set; } } internal class XmlSigningNodeWriter : XmlNodeWriter { private XmlNodeWriter writer; private XmlCanonicalWriter signingWriter; private byte[] chars; private byte[] base64Chars; private bool text; public XmlNodeWriter NodeWriter { get { return writer; } set { writer = value; } } public XmlCanonicalWriter CanonicalWriter => signingWriter; public XmlSigningNodeWriter(bool text) { this.text = text; } public void SetOutput(XmlNodeWriter writer, Stream stream, bool includeComments, string[] inclusivePrefixes) { this.writer = writer; if (signingWriter == null) { signingWriter = new XmlCanonicalWriter(); } signingWriter.SetOutput(stream, includeComments, inclusivePrefixes); chars = new byte[64]; base64Chars = null; } public override void Flush() { writer.Flush(); signingWriter.Flush(); } public override void Close() { writer.Close(); signingWriter.Close(); } public override void WriteDeclaration() { writer.WriteDeclaration(); signingWriter.WriteDeclaration(); } public override void WriteComment(string text) { writer.WriteComment(text); signingWriter.WriteComment(text); } public override void WriteCData(string text) { writer.WriteCData(text); signingWriter.WriteEscapedText(text); } public override void WriteStartElement(string prefix, string localName) { writer.WriteStartElement(prefix, localName); signingWriter.WriteStartElement(prefix, localName); } public override void WriteStartElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { writer.WriteStartElement(prefixBuffer, prefixOffset, prefixLength, localNameBuffer, localNameOffset, localNameLength); signingWriter.WriteStartElement(prefixBuffer, prefixOffset, prefixLength, localNameBuffer, localNameOffset, localNameLength); } public override void WriteStartElement(string prefix, XmlDictionaryString localName) { writer.WriteStartElement(prefix, localName); signingWriter.WriteStartElement(prefix, localName.Value); } public override void WriteEndStartElement(bool isEmpty) { writer.WriteEndStartElement(isEmpty); signingWriter.WriteEndStartElement(isEmpty); } public override void WriteEndElement(string prefix, string localName) { writer.WriteEndElement(prefix, localName); signingWriter.WriteEndElement(prefix, localName); } public override void WriteXmlnsAttribute(string prefix, string ns) { writer.WriteXmlnsAttribute(prefix, ns); signingWriter.WriteXmlnsAttribute(prefix, ns); } public override void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] nsBuffer, int nsOffset, int nsLength) { writer.WriteXmlnsAttribute(prefixBuffer, prefixOffset, prefixLength, nsBuffer, nsOffset, nsLength); signingWriter.WriteXmlnsAttribute(prefixBuffer, prefixOffset, prefixLength, nsBuffer, nsOffset, nsLength); } public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) { writer.WriteXmlnsAttribute(prefix, ns); signingWriter.WriteXmlnsAttribute(prefix, ns.Value); } public override void WriteStartAttribute(string prefix, string localName) { writer.WriteStartAttribute(prefix, localName); signingWriter.WriteStartAttribute(prefix, localName); } public override void WriteStartAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { writer.WriteStartAttribute(prefixBuffer, prefixOffset, prefixLength, localNameBuffer, localNameOffset, localNameLength); signingWriter.WriteStartAttribute(prefixBuffer, prefixOffset, prefixLength, localNameBuffer, localNameOffset, localNameLength); } public override void WriteStartAttribute(string prefix, XmlDictionaryString localName) { writer.WriteStartAttribute(prefix, localName); signingWriter.WriteStartAttribute(prefix, localName.Value); } public override void WriteEndAttribute() { writer.WriteEndAttribute(); signingWriter.WriteEndAttribute(); } public override void WriteCharEntity(int ch) { writer.WriteCharEntity(ch); signingWriter.WriteCharEntity(ch); } public override void WriteEscapedText(string value) { writer.WriteEscapedText(value); signingWriter.WriteEscapedText(value); } public override void WriteEscapedText(char[] chars, int offset, int count) { writer.WriteEscapedText(chars, offset, count); signingWriter.WriteEscapedText(chars, offset, count); } public override void WriteEscapedText(XmlDictionaryString value) { writer.WriteEscapedText(value); signingWriter.WriteEscapedText(value.Value); } public override void WriteEscapedText(byte[] chars, int offset, int count) { writer.WriteEscapedText(chars, offset, count); signingWriter.WriteEscapedText(chars, offset, count); } public override void WriteText(string value) { writer.WriteText(value); signingWriter.WriteText(value); } public override void WriteText(char[] chars, int offset, int count) { writer.WriteText(chars, offset, count); signingWriter.WriteText(chars, offset, count); } public override void WriteText(byte[] chars, int offset, int count) { writer.WriteText(chars, offset, count); signingWriter.WriteText(chars, offset, count); } public override void WriteText(XmlDictionaryString value) { writer.WriteText(value); signingWriter.WriteText(value.Value); } public override void WriteInt32Text(int value) { int count = XmlConverter.ToChars(value, chars, 0); if (text) { writer.WriteText(chars, 0, count); } else { writer.WriteInt32Text(value); } signingWriter.WriteText(chars, 0, count); } public override void WriteInt64Text(long value) { int count = XmlConverter.ToChars(value, chars, 0); if (text) { writer.WriteText(chars, 0, count); } else { writer.WriteInt64Text(value); } signingWriter.WriteText(chars, 0, count); } public override void WriteBoolText(bool value) { int count = XmlConverter.ToChars(value, chars, 0); if (text) { writer.WriteText(chars, 0, count); } else { writer.WriteBoolText(value); } signingWriter.WriteText(chars, 0, count); } public override void WriteUInt64Text(ulong value) { int count = XmlConverter.ToChars(value, chars, 0); if (text) { writer.WriteText(chars, 0, count); } else { writer.WriteUInt64Text(value); } signingWriter.WriteText(chars, 0, count); } public override void WriteFloatText(float value) { int count = XmlConverter.ToChars(value, chars, 0); if (text) { writer.WriteText(chars, 0, count); } else { writer.WriteFloatText(value); } signingWriter.WriteText(chars, 0, count); } public override void WriteDoubleText(double value) { int count = XmlConverter.ToChars(value, chars, 0); if (text) { writer.WriteText(chars, 0, count); } else { writer.WriteDoubleText(value); } signingWriter.WriteText(chars, 0, count); } public override void WriteDecimalText(decimal value) { int count = XmlConverter.ToChars(value, chars, 0); if (text) { writer.WriteText(chars, 0, count); } else { writer.WriteDecimalText(value); } signingWriter.WriteText(chars, 0, count); } public override void WriteDateTimeText(DateTime value) { int count = XmlConverter.ToChars(value, chars, 0); if (text) { writer.WriteText(chars, 0, count); } else { writer.WriteDateTimeText(value); } signingWriter.WriteText(chars, 0, count); } public override void WriteUniqueIdText(UniqueId value) { string value2 = XmlConverter.ToString(value); if (text) { writer.WriteText(value2); } else { writer.WriteUniqueIdText(value); } signingWriter.WriteText(value2); } public override void WriteTimeSpanText(TimeSpan value) { string value2 = XmlConverter.ToString(value); if (text) { writer.WriteText(value2); } else { writer.WriteTimeSpanText(value); } signingWriter.WriteText(value2); } public override void WriteGuidText(Guid value) { string value2 = XmlConverter.ToString(value); if (text) { writer.WriteText(value2); } else { writer.WriteGuidText(value); } signingWriter.WriteText(value2); } public override void WriteStartListText() { writer.WriteStartListText(); } public override void WriteListSeparator() { writer.WriteListSeparator(); signingWriter.WriteText(32); } public override void WriteEndListText() { writer.WriteEndListText(); } public override void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count) { if (trailByteCount > 0) { WriteBase64Text(trailBytes, 0, trailByteCount); } WriteBase64Text(buffer, offset, count); if (!text) { writer.WriteBase64Text(trailBytes, trailByteCount, buffer, offset, count); } } private void WriteBase64Text(byte[] buffer, int offset, int count) { if (base64Chars == null) { base64Chars = new byte[512]; } Base64Encoding base64Encoding = XmlConverter.Base64Encoding; while (count >= 3) { int num = Math.Min(base64Chars.Length / 4 * 3, count - count % 3); int count2 = num / 3 * 4; base64Encoding.GetChars(buffer, offset, num, base64Chars, 0); signingWriter.WriteText(base64Chars, 0, count2); if (text) { writer.WriteText(base64Chars, 0, count2); } offset += num; count -= num; } if (count > 0) { base64Encoding.GetChars(buffer, offset, count, base64Chars, 0); signingWriter.WriteText(base64Chars, 0, 4); if (text) { writer.WriteText(base64Chars, 0, 4); } } } public override void WriteQualifiedName(string prefix, XmlDictionaryString localName) { writer.WriteQualifiedName(prefix, localName); if (prefix.Length != 0) { signingWriter.WriteText(prefix); signingWriter.WriteText(":"); } signingWriter.WriteText(localName.Value); } } internal abstract class XmlStreamNodeWriter : XmlNodeWriter { private class GetBufferAsyncResult : AsyncResult { private XmlStreamNodeWriter writer; private int offset; private int count; private static AsyncCompletion onComplete = new AsyncCompletion(OnComplete); public GetBufferAsyncResult(int count, XmlStreamNodeWriter writer, AsyncCallback callback, object state) : base(callback, state) { this.count = count; this.writer = writer; int num = writer.offset; bool flag = false; if (num + count <= 512) { offset = num; flag = true; } else { IAsyncResult asyncResult = writer.BeginFlushBuffer(((AsyncResult)this).PrepareAsyncCompletion(onComplete), this); flag = ((AsyncResult)this).SyncContinue(asyncResult); } if (flag) { ((AsyncResult)this).Complete(true); } } private static bool OnComplete(IAsyncResult result) { return ((GetBufferAsyncResult)result.AsyncState).HandleFlushBuffer(result); } private bool HandleFlushBuffer(IAsyncResult result) { writer.EndFlushBuffer(result); offset = 0; return true; } public static byte[] End(IAsyncResult result, out int offset) { GetBufferAsyncResult getBufferAsyncResult = AsyncResult.End(result); offset = getBufferAsyncResult.offset; return getBufferAsyncResult.writer.buffer; } } private class WriteBytesAsyncResult : AsyncResult { private static AsyncCompletion onHandleGetBufferComplete = new AsyncCompletion(OnHandleGetBufferComplete); private static AsyncCompletion onHandleFlushBufferComplete = new AsyncCompletion(OnHandleFlushBufferComplete); private static AsyncCompletion onHandleWrite = new AsyncCompletion(OnHandleWrite); private byte[] byteBuffer; private int byteOffset; private int byteCount; private XmlStreamNodeWriter writer; public WriteBytesAsyncResult(byte[] byteBuffer, int byteOffset, int byteCount, XmlStreamNodeWriter writer, AsyncCallback callback, object state) : base(callback, state) { this.byteBuffer = byteBuffer; this.byteOffset = byteOffset; this.byteCount = byteCount; this.writer = writer; bool flag = false; if ((byteCount >= 512) ? HandleFlushBuffer(null) : HandleGetBuffer(null)) { ((AsyncResult)this).Complete(true); } } private static bool OnHandleGetBufferComplete(IAsyncResult result) { return ((WriteBytesAsyncResult)result.AsyncState).HandleGetBuffer(result); } private static bool OnHandleFlushBufferComplete(IAsyncResult result) { return ((WriteBytesAsyncResult)result.AsyncState).HandleFlushBuffer(result); } private static bool OnHandleWrite(IAsyncResult result) { return ((WriteBytesAsyncResult)result.AsyncState).HandleWrite(result); } private bool HandleGetBuffer(IAsyncResult result) { if (result == null) { result = writer.BeginGetBuffer(byteCount, ((AsyncResult)this).PrepareAsyncCompletion(onHandleGetBufferComplete), this); if (!result.CompletedSynchronously) { return false; } } int offset; byte[] dst = writer.EndGetBuffer(result, out offset); Buffer.BlockCopy(byteBuffer, byteOffset, dst, offset, byteCount); writer.Advance(byteCount); return true; } private bool HandleFlushBuffer(IAsyncResult result) { if (result == null) { result = writer.BeginFlushBuffer(((AsyncResult)this).PrepareAsyncCompletion(onHandleFlushBufferComplete), this); if (!result.CompletedSynchronously) { return false; } } writer.EndFlushBuffer(result); return HandleWrite(null); } private bool HandleWrite(IAsyncResult result) { if (result == null) { result = writer.stream.BeginWrite(byteBuffer, byteOffset, byteCount, ((AsyncResult)this).PrepareAsyncCompletion(onHandleWrite), this); if (!result.CompletedSynchronously) { return false; } } writer.stream.EndWrite(result); return true; } public static void End(IAsyncResult result) { AsyncResult.End(result); } } private class FlushBufferAsyncResult : AsyncResult { private static AsyncCompletion onComplete = new AsyncCompletion(OnComplete); private XmlStreamNodeWriter writer; public FlushBufferAsyncResult(XmlStreamNodeWriter writer, AsyncCallback callback, object state) : base(callback, state) { this.writer = writer; bool flag = true; if (writer.offset != 0) { flag = HandleFlushBuffer(null); } if (flag) { ((AsyncResult)this).Complete(true); } } private static bool OnComplete(IAsyncResult result) { return ((FlushBufferAsyncResult)result.AsyncState).HandleFlushBuffer(result); } private bool HandleFlushBuffer(IAsyncResult result) { if (result == null) { result = writer.stream.BeginWrite(writer.buffer, 0, writer.offset, ((AsyncResult)this).PrepareAsyncCompletion(onComplete), this); if (!result.CompletedSynchronously) { return false; } } writer.stream.EndWrite(result); writer.offset = 0; return true; } public static void End(IAsyncResult result) { AsyncResult.End(result); } } internal class GetBufferArgs { public int Count { get; set; } } internal class GetBufferEventResult { internal byte[] Buffer { get; set; } internal int Offset { get; set; } } internal class GetBufferAsyncEventArgs : AsyncEventArgs { } private Stream stream; private byte[] buffer; private int offset; private bool ownsStream; private const int bufferLength = 512; private const int maxEntityLength = 32; private const int maxBytesPerChar = 3; private Encoding encoding; private int hasPendingWrite; private AsyncEventArgs flushBufferState; private static UTF8Encoding UTF8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); private static AsyncCallback onFlushBufferComplete; private static AsyncEventArgsCallback onGetFlushComplete; public Stream Stream { get { return stream; } set { stream = value; } } public byte[] StreamBuffer => buffer; public int BufferOffset => offset; public int Position => (int)stream.Position + offset; protected XmlStreamNodeWriter() { buffer = new byte[512]; encoding = UTF8Encoding; } protected void SetOutput(Stream stream, bool ownsStream, Encoding encoding) { this.stream = stream; this.ownsStream = ownsStream; offset = 0; if (encoding != null) { this.encoding = encoding; } } protected byte[] GetBuffer(int count, out int offset) { int num = this.offset; if (num + count <= 512) { offset = num; } else { FlushBuffer(); offset = 0; } return buffer; } internal AsyncCompletionResult GetBufferAsync(GetBufferAsyncEventArgs getBufferState) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Invalid comparison between Unknown and I4 int count = ((AsyncEventArgs)(object)getBufferState).Arguments.Count; int num = 0; int num2 = offset; if (num2 + count <= 512) { num = num2; } else { if (onGetFlushComplete == null) { onGetFlushComplete = new AsyncEventArgsCallback(GetBufferFlushComplete); } if (flushBufferState == null) { flushBufferState = new AsyncEventArgs(); } flushBufferState.Set(onGetFlushComplete, (object)getBufferState, (object)this); if ((int)FlushBufferAsync(flushBufferState) != 1) { return (AsyncCompletionResult)0; } num = 0; ((AsyncEventArgs)flushBufferState).Complete(true); } ((AsyncEventArgs)getBufferState).Result = ((AsyncEventArgs)getBufferState).Result ?? new GetBufferEventResult(); ((AsyncEventArgs)getBufferState).Result.Buffer = buffer; ((AsyncEventArgs)getBufferState).Result.Offset = num; return (AsyncCompletionResult)1; } private static void GetBufferFlushComplete(IAsyncEventArgs completionState) { XmlStreamNodeWriter xmlStreamNodeWriter = (XmlStreamNodeWriter)completionState.AsyncState; GetBufferAsyncEventArgs obj = (GetBufferAsyncEventArgs)xmlStreamNodeWriter.flushBufferState.Arguments; ((AsyncEventArgs)obj).Result = ((AsyncEventArgs)obj).Result ?? new GetBufferEventResult(); ((AsyncEventArgs)obj).Result.Buffer = xmlStreamNodeWriter.buffer; ((AsyncEventArgs)obj).Result.Offset = 0; ((AsyncEventArgs)obj).Complete(false, completionState.Exception); } private AsyncCompletionResult FlushBufferAsync(AsyncEventArgs state) { if (Interlocked.CompareExchange(ref hasPendingWrite, 1, 0) != 0) { throw FxTrace.Exception.AsError((Exception)new InvalidOperationException(System.Runtime.Serialization.SR.GetString("Flush buffer is already in use."))); } if (offset != 0) { if (onFlushBufferComplete == null) { onFlushBufferComplete = OnFlushBufferCompete; } IAsyncResult asyncResult = stream.BeginWrite(buffer, 0, offset, onFlushBufferComplete, this); if (!asyncResult.CompletedSynchronously) { return (AsyncCompletionResult)0; } stream.EndWrite(asyncResult); offset = 0; } if (Interlocked.CompareExchange(ref hasPendingWrite, 0, 1) != 1) { throw FxTrace.Exception.AsError((Exception)new InvalidOperationException(System.Runtime.Serialization.SR.GetString("No async write operation is pending."))); } return (AsyncCompletionResult)1; } private static void OnFlushBufferCompete(IAsyncResult result) { if (result.CompletedSynchronously) { return; } XmlStreamNodeWriter xmlStreamNodeWriter = (XmlStreamNodeWriter)result.AsyncState; Exception ex = null; try { xmlStreamNodeWriter.stream.EndWrite(result); xmlStreamNodeWriter.offset = 0; if (Interlocked.CompareExchange(ref xmlStreamNodeWriter.hasPendingWrite, 0, 1) != 1) { throw FxTrace.Exception.AsError((Exception)new InvalidOperationException(System.Runtime.Serialization.SR.GetString("No async write operation is pending."))); } } catch (Exception ex2) { if (Fx.IsFatal(ex2)) { throw; } ex = ex2; } ((AsyncEventArgs)xmlStreamNodeWriter.flushBufferState).Complete(false, ex); } protected IAsyncResult BeginGetBuffer(int count, AsyncCallback callback, object state) { return (IAsyncResult)new GetBufferAsyncResult(count, this, callback, state); } protected byte[] EndGetBuffer(IAsyncResult result, out int offset) { return GetBufferAsyncResult.End(result, out offset); } protected void Advance(int count) { offset += count; } private void EnsureByte() { if (offset >= 512) { FlushBuffer(); } } protected void WriteByte(byte b) { EnsureByte(); buffer[offset++] = b; } protected void WriteByte(char ch) { WriteByte((byte)ch); } protected void WriteBytes(byte b1, byte b2) { byte[] array = buffer; int num = offset; if (num + 1 >= 512) { FlushBuffer(); num = 0; } array[num] = b1; array[num + 1] = b2; offset += 2; } protected void WriteBytes(char ch1, char ch2) { WriteBytes((byte)ch1, (byte)ch2); } public void WriteBytes(byte[] byteBuffer, int byteOffset, int byteCount) { if (byteCount < 512) { int dstOffset; byte[] dst = GetBuffer(byteCount, out dstOffset); Buffer.BlockCopy(byteBuffer, byteOffset, dst, dstOffset, byteCount); Advance(byteCount); } else { FlushBuffer(); stream.Write(byteBuffer, byteOffset, byteCount); } } public IAsyncResult BeginWriteBytes(byte[] byteBuffer, int byteOffset, int byteCount, AsyncCallback callback, object state) { return (IAsyncResult)new WriteBytesAsyncResult(byteBuffer, byteOffset, byteCount, this, callback, state); } public void EndWriteBytes(IAsyncResult result) { WriteBytesAsyncResult.End(result); } [SecurityCritical] protected unsafe void UnsafeWriteBytes(byte* bytes, int byteCount) { FlushBuffer(); byte[] array = buffer; while (byteCount > 512) { for (int i = 0; i < 512; i++) { array[i] = bytes[i]; } stream.Write(array, 0, 512); bytes += 512; byteCount -= 512; } if (byteCount > 0) { for (int j = 0; j < byteCount; j++) { array[j] = bytes[j]; } stream.Write(array, 0, byteCount); } } [SecuritySafeCritical] protected unsafe void WriteUTF8Char(int ch) { if (ch < 128) { WriteByte((byte)ch); } else if (ch <= 65535) { char* ptr = stackalloc char[1]; *ptr = (char)ch; UnsafeWriteUTF8Chars(ptr, 1); } else { SurrogateChar surrogateChar = new SurrogateChar(ch); char* ptr2 = stackalloc char[2]; *ptr2 = surrogateChar.HighChar; ptr2[1] = surrogateChar.LowChar; UnsafeWriteUTF8Chars(ptr2, 2); } } protected void WriteUTF8Chars(byte[] chars, int charOffset, int charCount) { if (charCount < 512) { int dstOffset; byte[] dst = GetBuffer(charCount, out dstOffset); Buffer.BlockCopy(chars, charOffset, dst, dstOffset, charCount); Advance(charCount); } else { FlushBuffer(); stream.Write(chars, charOffset, charCount); } } [SecuritySafeCritical] protected unsafe void WriteUTF8Chars(string value) { int length = value.Length; if (length > 0) { fixed (char* chars = value) { UnsafeWriteUTF8Chars(chars, length); } } } [SecurityCritical] protected unsafe void UnsafeWriteUTF8Chars(char* chars, int charCount) { while (charCount > 170) { int num = 170; if ((chars[num - 1] & 0xFC00) == 55296) { num--; } int num2; byte[] array = GetBuffer(num * 3, out num2); Advance(UnsafeGetUTF8Chars(chars, num, array, num2)); charCount -= num; chars += num; } if (charCount > 0) { int num3; byte[] array2 = GetBuffer(charCount * 3, out num3); Advance(UnsafeGetUTF8Chars(chars, charCount, array2, num3)); } } [SecurityCritical] protected unsafe void UnsafeWriteUnicodeChars(char* chars, int charCount) { while (charCount > 256) { int num = 256; if ((chars[num - 1] & 0xFC00) == 55296) { num--; } int num2; byte[] array = GetBuffer(num * 2, out num2); Advance(UnsafeGetUnicodeChars(chars, num, array, num2)); charCount -= num; chars += num; } if (charCount > 0) { int num3; byte[] array2 = GetBuffer(charCount * 2, out num3); Advance(UnsafeGetUnicodeChars(chars, charCount, array2, num3)); } } [SecurityCritical] protected unsafe int UnsafeGetUnicodeChars(char* chars, int charCount, byte[] buffer, int offset) { char* ptr = chars + charCount; while (chars < ptr) { char c = *(chars++); buffer[offset++] = (byte)c; c = (char)((int)c >> 8); buffer[offset++] = (byte)c; } return charCount * 2; } [SecurityCritical] protected unsafe int UnsafeGetUTF8Length(char* chars, int charCount) { char* ptr = chars + charCount; while (chars < ptr && *chars < '\u0080') { chars++; } if (chars == ptr) { return charCount; } return (int)(chars - (ptr - charCount)) + encoding.GetByteCount(chars, (int)(ptr - chars)); } [SecurityCritical] protected unsafe int UnsafeGetUTF8Chars(char* chars, int charCount, byte[] buffer, int offset) { if (charCount > 0) { fixed (byte* ptr = &buffer[offset]) { byte* ptr2 = ptr; byte* ptr3 = ptr2 + (buffer.Length - offset); char* ptr4 = chars + charCount; do { IL_0045: if (chars < ptr4) { char c = *chars; if (c < '\u0080') { *ptr2 = (byte)c; ptr2++; chars++; goto IL_0045; } } if (chars >= ptr4) { break; } char* ptr5 = chars; while (chars < ptr4 && *chars >= '\u0080') { chars++; } ptr2 += encoding.GetBytes(ptr5, (int)(chars - ptr5), ptr2, (int)(ptr3 - ptr2)); } while (chars < ptr4); return (int)(ptr2 - ptr); } } return 0; } protected virtual void FlushBuffer() { if (offset != 0) { stream.Write(buffer, 0, offset); offset = 0; } } protected virtual IAsyncResult BeginFlushBuffer(AsyncCallback callback, object state) { return (IAsyncResult)new FlushBufferAsyncResult(this, callback, state); } protected virtual void EndFlushBuffer(IAsyncResult result) { FlushBufferAsyncResult.End(result); } public override void Flush() { FlushBuffer(); stream.Flush(); } public override void Close() { if (stream != null) { if (ownsStream) { stream.Close(); } stream = null; } } } public interface IXmlTextReaderInitializer { void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose); void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose); } internal class XmlUTF8TextReader : XmlBaseReader, IXmlLineInfo, IXmlTextReaderInitializer { private static class CharType { public const byte None = 0; public const byte FirstName = 1; public const byte Name = 2; public const byte Whitespace = 4; public const byte Text = 8; public const byte AttributeText = 16; public const byte SpecialWhitespace = 32; public const byte Comment = 64; } private const int MaxTextChunk = 2048; private PrefixHandle prefix; private StringHandle localName; private int[] rowOffsets; private OnXmlDictionaryReaderClose onClose; private bool buffered; private int maxBytesPerRead; private static byte[] charType = new byte[256] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 108, 108, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 124, 88, 72, 88, 88, 88, 64, 72, 88, 88, 88, 88, 88, 90, 90, 88, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 88, 88, 64, 88, 88, 88, 88, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 88, 88, 80, 88, 91, 88, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 88, 88, 88, 88, 88, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 3, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91 }; public int LineNumber { get { GetPosition(out var row, out var _); return row; } } public int LinePosition { get { GetPosition(out var _, out var column); return column; } } public XmlUTF8TextReader() { prefix = new PrefixHandle(base.BufferReader); localName = new StringHandle(base.BufferReader); } public void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("buffer")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (offset > buffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", buffer.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", buffer.Length - offset))); } MoveToInitial(quotas, onClose); ArraySegment arraySegment = EncodingStreamWrapper.ProcessBuffer(buffer, offset, count, encoding); base.BufferReader.SetBuffer(arraySegment.Array, arraySegment.Offset, arraySegment.Count, null, null); buffered = true; } public void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) { if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream"); } MoveToInitial(quotas, onClose); stream = new EncodingStreamWrapper(stream, encoding); base.BufferReader.SetBuffer(stream, null, null); buffered = false; } private void MoveToInitial(XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) { MoveToInitial(quotas); maxBytesPerRead = quotas.MaxBytesPerRead; this.onClose = onClose; } public override void Close() { rowOffsets = null; base.Close(); OnXmlDictionaryReaderClose onXmlDictionaryReaderClose = onClose; onClose = null; if (onXmlDictionaryReaderClose == null) { return; } try { onXmlDictionaryReaderClose(this); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(ex); } } private void SkipWhitespace() { while (!base.BufferReader.EndOfFile && (charType[base.BufferReader.GetByte()] & 4u) != 0) { base.BufferReader.SkipByte(); } } private void ReadDeclaration() { if (!buffered) { BufferElement(); } byte[] buffer = base.BufferReader.GetBuffer(5, out var offset); if (buffer[offset] != 63 || buffer[offset + 1] != 120 || buffer[offset + 2] != 109 || buffer[offset + 3] != 108 || (charType[buffer[offset + 4]] & 4) == 0) { XmlExceptionHelper.ThrowProcessingInstructionNotSupported(this); } if (base.Node.ReadState != 0) { XmlExceptionHelper.ThrowDeclarationNotFirst(this); } base.BufferReader.Advance(5); int offset2 = offset + 1; int length = 3; int offset3 = base.BufferReader.Offset; SkipWhitespace(); ReadAttributes(); int num; for (num = base.BufferReader.Offset - offset3; num > 0; num--) { byte @byte = base.BufferReader.GetByte(offset3 + num - 1); if ((charType[@byte] & 4) == 0) { break; } } buffer = base.BufferReader.GetBuffer(2, out offset); if (buffer[offset] != 63 || buffer[offset + 1] != 62) { XmlExceptionHelper.ThrowTokenExpected(this, "?>", Encoding.UTF8.GetString(buffer, offset, 2)); } base.BufferReader.Advance(2); XmlDeclarationNode xmlDeclarationNode = MoveToDeclaration(); xmlDeclarationNode.LocalName.SetValue(offset2, length); xmlDeclarationNode.Value.SetValue(ValueHandleType.UTF8, offset3, num); } private void VerifyNCName(string s) { try { XmlConvert.VerifyNCName(s); } catch (XmlException exception) { XmlExceptionHelper.ThrowXmlException(this, exception); } } private void ReadQualifiedName(PrefixHandle prefix, StringHandle localName) { int i; int offsetMax; byte[] buffer = base.BufferReader.GetBuffer(out i, out offsetMax); int num = 0; int num2 = 0; int num3 = 0; int num4 = i; if (i < offsetMax) { num = buffer[i]; num3 = num; if ((charType[num] & 1) == 0) { num2 |= 0x80; } num2 |= num; for (i++; i < offsetMax; i++) { num = buffer[i]; if ((charType[num] & 2) == 0) { break; } num2 |= num; } } else { num2 |= 0x80; num = 0; } if (num == 58) { int num5 = i - num4; if (num5 == 1 && num3 >= 97 && num3 <= 122) { prefix.SetValue(PrefixHandle.GetAlphaPrefix(num3 - 97)); } else { prefix.SetValue(num4, num5); } i++; int num6 = i; if (i < offsetMax) { num = buffer[i]; if ((charType[num] & 1) == 0) { num2 |= 0x80; } num2 |= num; for (i++; i < offsetMax; i++) { num = buffer[i]; if ((charType[num] & 2) == 0) { break; } num2 |= num; } } else { num2 |= 0x80; num = 0; } localName.SetValue(num6, i - num6); if (num2 >= 128) { VerifyNCName(prefix.GetString()); VerifyNCName(localName.GetString()); } } else { prefix.SetValue(PrefixHandleType.Empty); localName.SetValue(num4, i - num4); if (num2 >= 128) { VerifyNCName(localName.GetString()); } } base.BufferReader.Advance(i - num4); } private int ReadAttributeText(byte[] buffer, int offset, int offsetMax) { byte[] array = charType; int num = offset; while (offset < offsetMax && (array[buffer[offset]] & 0x10u) != 0) { offset++; } return offset - num; } private void ReadAttributes() { int num = 0; if (buffered) { num = base.BufferReader.Offset; } while (true) { ReadQualifiedName(prefix, localName); if (base.BufferReader.GetByte() != 61) { SkipWhitespace(); if (base.BufferReader.GetByte() != 61) { XmlExceptionHelper.ThrowTokenExpected(this, "=", (char)base.BufferReader.GetByte()); } } base.BufferReader.SkipByte(); byte @byte = base.BufferReader.GetByte(); if (@byte != 34 && @byte != 39) { SkipWhitespace(); @byte = base.BufferReader.GetByte(); if (@byte != 34 && @byte != 39) { XmlExceptionHelper.ThrowTokenExpected(this, "\"", (char)base.BufferReader.GetByte()); } } base.BufferReader.SkipByte(); bool flag = false; int offset = base.BufferReader.Offset; byte byte2; while (true) { int offset2; int offsetMax; byte[] buffer = base.BufferReader.GetBuffer(out offset2, out offsetMax); int count = ReadAttributeText(buffer, offset2, offsetMax); base.BufferReader.Advance(count); byte2 = base.BufferReader.GetByte(); if (byte2 == @byte) { break; } switch (byte2) { case 38: ReadCharRef(); flag = true; break; case 34: case 39: base.BufferReader.SkipByte(); break; case 9: case 10: case 13: base.BufferReader.SkipByte(); flag = true; break; case 239: ReadNonFFFE(); break; default: { char c = (char)@byte; XmlExceptionHelper.ThrowTokenExpected(this, c.ToString(), (char)byte2); break; } } } int length = base.BufferReader.Offset - offset; XmlAttributeNode xmlAttributeNode; if (prefix.IsXmlns) { Namespace @namespace = AddNamespace(); localName.ToPrefixHandle(@namespace.Prefix); @namespace.Uri.SetValue(offset, length, flag); xmlAttributeNode = AddXmlnsAttribute(@namespace); } else if (prefix.IsEmpty && localName.IsXmlns) { Namespace namespace2 = AddNamespace(); namespace2.Prefix.SetValue(PrefixHandleType.Empty); namespace2.Uri.SetValue(offset, length, flag); xmlAttributeNode = AddXmlnsAttribute(namespace2); } else if (prefix.IsXml) { xmlAttributeNode = AddXmlAttribute(); xmlAttributeNode.Prefix.SetValue(prefix); xmlAttributeNode.LocalName.SetValue(localName); xmlAttributeNode.Value.SetValue(flag ? ValueHandleType.EscapedUTF8 : ValueHandleType.UTF8, offset, length); FixXmlAttribute(xmlAttributeNode); } else { xmlAttributeNode = AddAttribute(); xmlAttributeNode.Prefix.SetValue(prefix); xmlAttributeNode.LocalName.SetValue(localName); xmlAttributeNode.Value.SetValue(flag ? ValueHandleType.EscapedUTF8 : ValueHandleType.UTF8, offset, length); } xmlAttributeNode.QuoteChar = (char)@byte; base.BufferReader.SkipByte(); byte2 = base.BufferReader.GetByte(); bool flag2 = false; while ((charType[byte2] & 4u) != 0) { flag2 = true; base.BufferReader.SkipByte(); byte2 = base.BufferReader.GetByte(); } if (byte2 == 62 || byte2 == 47 || byte2 == 63) { break; } if (!flag2) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(System.Runtime.Serialization.SR.GetString("Whitespace must appear between attributes."))); } } if (buffered && base.BufferReader.Offset - num > maxBytesPerRead) { XmlExceptionHelper.ThrowMaxBytesPerReadExceeded(this, maxBytesPerRead); } ProcessAttributes(); } private void ReadNonFFFE() { int offset; byte[] buffer = base.BufferReader.GetBuffer(3, out offset); if (buffer[offset + 1] == 191 && (buffer[offset + 2] == 190 || buffer[offset + 2] == 191)) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(System.Runtime.Serialization.SR.GetString("Characters with hexadecimal values 0xFFFE and 0xFFFF are not valid."))); } base.BufferReader.Advance(3); } private bool IsNextCharacterNonFFFE(byte[] buffer, int offset) { if (buffer[offset + 1] == 191 && (buffer[offset + 2] == 190 || buffer[offset + 2] == 191)) { return false; } return true; } private void BufferElement() { int offset = base.BufferReader.Offset; bool flag = false; byte b = 0; while (!flag) { int offset2; int offsetMax; byte[] buffer = base.BufferReader.GetBuffer(128, out offset2, out offsetMax); if (offset2 + 128 != offsetMax) { break; } for (int i = offset2; i < offsetMax; i++) { if (flag) { break; } byte b2 = buffer[i]; if (b == 0) { if (b2 == 39 || b2 == 34) { b = b2; } if (b2 == 62) { flag = true; } } else if (b2 == b) { b = 0; } } base.BufferReader.Advance(128); } base.BufferReader.Offset = offset; } private new void ReadStartElement() { if (!buffered) { BufferElement(); } XmlElementNode xmlElementNode = EnterScope(); xmlElementNode.NameOffset = base.BufferReader.Offset; ReadQualifiedName(xmlElementNode.Prefix, xmlElementNode.LocalName); xmlElementNode.NameLength = base.BufferReader.Offset - xmlElementNode.NameOffset; byte @byte = base.BufferReader.GetByte(); while ((charType[@byte] & 4u) != 0) { base.BufferReader.SkipByte(); @byte = base.BufferReader.GetByte(); } if (@byte != 62 && @byte != 47) { ReadAttributes(); @byte = base.BufferReader.GetByte(); } xmlElementNode.Namespace = LookupNamespace(xmlElementNode.Prefix); bool flag = false; if (@byte == 47) { flag = true; base.BufferReader.SkipByte(); } xmlElementNode.IsEmptyElement = flag; xmlElementNode.ExitScope = flag; if (base.BufferReader.GetByte() != 62) { XmlExceptionHelper.ThrowTokenExpected(this, ">", (char)base.BufferReader.GetByte()); } base.BufferReader.SkipByte(); xmlElementNode.BufferOffset = base.BufferReader.Offset; } private new void ReadEndElement() { base.BufferReader.SkipByte(); XmlElementNode elementNode = base.ElementNode; int nameOffset = elementNode.NameOffset; int nameLength = elementNode.NameLength; int offset; byte[] buffer = base.BufferReader.GetBuffer(nameLength, out offset); for (int i = 0; i < nameLength; i++) { if (buffer[offset + i] != buffer[nameOffset + i]) { ReadQualifiedName(prefix, localName); XmlExceptionHelper.ThrowTagMismatch(this, elementNode.Prefix.GetString(), elementNode.LocalName.GetString(), prefix.GetString(), localName.GetString()); } } base.BufferReader.Advance(nameLength); if (base.BufferReader.GetByte() != 62) { SkipWhitespace(); if (base.BufferReader.GetByte() != 62) { XmlExceptionHelper.ThrowTokenExpected(this, ">", (char)base.BufferReader.GetByte()); } } base.BufferReader.SkipByte(); MoveToEndElement(); } private void ReadComment() { base.BufferReader.SkipByte(); if (base.BufferReader.GetByte() != 45) { XmlExceptionHelper.ThrowTokenExpected(this, "--", (char)base.BufferReader.GetByte()); } base.BufferReader.SkipByte(); int offset = base.BufferReader.Offset; while (true) { byte @byte = base.BufferReader.GetByte(); if (@byte != 45) { if ((charType[@byte] & 0x40) == 0) { if (@byte == 239) { ReadNonFFFE(); } else { XmlExceptionHelper.ThrowInvalidXml(this, @byte); } } else { base.BufferReader.SkipByte(); } continue; } int offset2; byte[] buffer = base.BufferReader.GetBuffer(3, out offset2); if (buffer[offset2] == 45 && buffer[offset2 + 1] == 45) { if (buffer[offset2 + 2] == 62) { break; } XmlExceptionHelper.ThrowXmlException(this, new XmlException(System.Runtime.Serialization.SR.GetString("XML comments cannot contain '--' or end with '-'."))); } base.BufferReader.SkipByte(); } int length = base.BufferReader.Offset - offset; MoveToComment().Value.SetValue(ValueHandleType.UTF8, offset, length); base.BufferReader.Advance(3); } private void ReadCData() { byte[] buffer = base.BufferReader.GetBuffer(7, out var offset); if (buffer[offset] != 91 || buffer[offset + 1] != 67 || buffer[offset + 2] != 68 || buffer[offset + 3] != 65 || buffer[offset + 4] != 84 || buffer[offset + 5] != 65 || buffer[offset + 6] != 91) { XmlExceptionHelper.ThrowTokenExpected(this, "[CDATA[", Encoding.UTF8.GetString(buffer, offset, 7)); } base.BufferReader.Advance(7); int offset2 = base.BufferReader.Offset; while (true) { switch (base.BufferReader.GetByte()) { case 239: ReadNonFFFE(); break; default: base.BufferReader.SkipByte(); break; case 93: { buffer = base.BufferReader.GetBuffer(3, out offset); if (buffer[offset] != 93 || buffer[offset + 1] != 93 || buffer[offset + 2] != 62) { base.BufferReader.SkipByte(); break; } int length = base.BufferReader.Offset - offset2; MoveToCData().Value.SetValue(ValueHandleType.UTF8, offset2, length); base.BufferReader.Advance(3); return; } } } } private int ReadCharRef() { int offset = base.BufferReader.Offset; base.BufferReader.SkipByte(); while (base.BufferReader.GetByte() != 59) { base.BufferReader.SkipByte(); } base.BufferReader.SkipByte(); int num = base.BufferReader.Offset - offset; base.BufferReader.Offset = offset; int charEntity = base.BufferReader.GetCharEntity(offset, num); base.BufferReader.Advance(num); return charEntity; } private void ReadWhitespace() { int offset; int offsetMax; int num; if (buffered) { byte[] buffer = base.BufferReader.GetBuffer(out offset, out offsetMax); num = ReadWhitespace(buffer, offset, offsetMax); } else { byte[] buffer = base.BufferReader.GetBuffer(2048, out offset, out offsetMax); num = ReadWhitespace(buffer, offset, offsetMax); num = BreakText(buffer, offset, num); } base.BufferReader.Advance(num); MoveToWhitespaceText().Value.SetValue(ValueHandleType.UTF8, offset, num); } private int ReadWhitespace(byte[] buffer, int offset, int offsetMax) { byte[] array = charType; int num = offset; while (offset < offsetMax && (array[buffer[offset]] & 0x20u) != 0) { offset++; } return offset - num; } private int ReadText(byte[] buffer, int offset, int offsetMax) { byte[] array = charType; int num = offset; while (offset < offsetMax && (array[buffer[offset]] & 8u) != 0) { offset++; } return offset - num; } private int ReadTextAndWatchForInvalidCharacters(byte[] buffer, int offset, int offsetMax) { byte[] array = charType; int num = offset; while (offset < offsetMax && ((array[buffer[offset]] & 8u) != 0 || buffer[offset] == 239)) { if (buffer[offset] != 239) { offset++; continue; } if (offset + 2 < offsetMax) { if (IsNextCharacterNonFFFE(buffer, offset)) { offset += 3; } else { XmlExceptionHelper.ThrowXmlException(this, new XmlException(System.Runtime.Serialization.SR.GetString("Characters with hexadecimal values 0xFFFE and 0xFFFF are not valid."))); } continue; } if (base.BufferReader.Offset < offset) { break; } base.BufferReader.GetBuffer(3, out var _); } return offset - num; } private int BreakText(byte[] buffer, int offset, int length) { if (length > 0 && (buffer[offset + length - 1] & 0x80) == 128) { int num = length; do { length--; } while (length > 0 && (buffer[offset + length] & 0xC0) != 192); if (length == 0) { return num; } byte b = (byte)(buffer[offset + length] << 2); int num2 = 2; while ((b & 0x80) == 128) { b <<= 1; num2++; if (num2 > 4) { return num; } } if (length + num2 == num) { return num; } if (length == 0) { return num; } } return length; } private void ReadText(bool hasLeadingByteOf0xEF) { byte[] buffer; int offset; int offsetMax; int num; if (buffered) { buffer = base.BufferReader.GetBuffer(out offset, out offsetMax); num = ((!hasLeadingByteOf0xEF) ? ReadText(buffer, offset, offsetMax) : ReadTextAndWatchForInvalidCharacters(buffer, offset, offsetMax)); } else { buffer = base.BufferReader.GetBuffer(2048, out offset, out offsetMax); num = BreakText(length: (!hasLeadingByteOf0xEF) ? ReadText(buffer, offset, offsetMax) : ReadTextAndWatchForInvalidCharacters(buffer, offset, offsetMax), buffer: buffer, offset: offset); } base.BufferReader.Advance(num); if (offset < offsetMax - 1 - num && buffer[offset + num] == 60 && buffer[offset + num + 1] != 33) { MoveToAtomicText().Value.SetValue(ValueHandleType.UTF8, offset, num); } else { MoveToComplexText().Value.SetValue(ValueHandleType.UTF8, offset, num); } } private void ReadEscapedText() { int num = ReadCharRef(); if (num < 256 && (charType[num] & 4u) != 0) { MoveToWhitespaceText().Value.SetCharValue(num); } else { MoveToComplexText().Value.SetCharValue(num); } } public override bool Read() { if (base.Node.ReadState == ReadState.Closed) { return false; } if (base.Node.CanMoveToElement) { MoveToElement(); } SignNode(); if (base.Node.ExitScope) { ExitScope(); } if (!buffered) { base.BufferReader.SetWindow(base.ElementNode.BufferOffset, maxBytesPerRead); } if (base.BufferReader.EndOfFile) { MoveToEndOfFile(); return false; } byte @byte = base.BufferReader.GetByte(); if (@byte == 60) { base.BufferReader.SkipByte(); switch (base.BufferReader.GetByte()) { case 47: ReadEndElement(); break; case 33: base.BufferReader.SkipByte(); @byte = base.BufferReader.GetByte(); if (@byte == 45) { ReadComment(); break; } if (base.OutsideRootElement) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(System.Runtime.Serialization.SR.GetString("CData elements not valid at top level of an XML document."))); } ReadCData(); break; case 63: ReadDeclaration(); break; default: ReadStartElement(); break; } } else if ((charType[@byte] & 0x20u) != 0) { ReadWhitespace(); } else if (base.OutsideRootElement && @byte != 13) { XmlExceptionHelper.ThrowInvalidRootData(this); } else if ((charType[@byte] & 8u) != 0) { ReadText(hasLeadingByteOf0xEF: false); } else { switch (@byte) { case 38: ReadEscapedText(); break; case 13: base.BufferReader.SkipByte(); if (!base.BufferReader.EndOfFile && base.BufferReader.GetByte() == 10) { ReadWhitespace(); } else { MoveToComplexText().Value.SetCharValue(10); } break; case 93: { int offset; byte[] buffer = base.BufferReader.GetBuffer(3, out offset); if (buffer[offset] == 93 && buffer[offset + 1] == 93 && buffer[offset + 2] == 62) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(System.Runtime.Serialization.SR.GetString("']]>' not valid in text node content."))); } base.BufferReader.SkipByte(); MoveToComplexText().Value.SetCharValue(93); break; } case 239: ReadText(hasLeadingByteOf0xEF: true); break; default: XmlExceptionHelper.ThrowInvalidXml(this, @byte); break; } } return true; } protected override XmlSigningNodeWriter CreateSigningNodeWriter() { return new XmlSigningNodeWriter(text: true); } public bool HasLineInfo() { return true; } private void GetPosition(out int row, out int column) { if (rowOffsets == null) { rowOffsets = base.BufferReader.GetRows(); } int offset = base.BufferReader.Offset; int i; for (i = 0; i < rowOffsets.Length - 1 && rowOffsets[i + 1] < offset; i++) { } row = i + 1; column = offset - rowOffsets[i] + 1; } } public interface IXmlTextWriterInitializer { void SetOutput(Stream stream, Encoding encoding, bool ownsStream); } internal class XmlUTF8TextWriter : XmlBaseWriter, IXmlTextWriterInitializer { private XmlUTF8NodeWriter writer; internal override bool FastAsync => true; public override bool CanFragment => writer.Encoding == null; public void SetOutput(Stream stream, Encoding encoding, bool ownsStream) { if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream"); } if (encoding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encoding"); } if (encoding.WebName != Encoding.UTF8.WebName) { stream = new EncodingStreamWrapper(stream, encoding, emitBOM: true); } if (writer == null) { writer = new XmlUTF8NodeWriter(); } writer.SetOutput(stream, ownsStream, encoding); SetOutput(writer); } protected override XmlSigningNodeWriter CreateSigningNodeWriter() { return new XmlSigningNodeWriter(text: true); } } internal class XmlUTF8NodeWriter : XmlStreamNodeWriter { private class InternalWriteBase64TextAsyncWriter { private AsyncEventArgs nodeState; private AsyncEventArgs writerState; private XmlWriteBase64AsyncArguments writerArgs; private XmlUTF8NodeWriter writer; private GetBufferAsyncEventArgs getBufferState; private GetBufferArgs getBufferArgs; private static AsyncEventArgsCallback onTrailByteComplete = new AsyncEventArgsCallback(OnTrailBytesComplete); private static AsyncEventArgsCallback onWriteComplete = new AsyncEventArgsCallback(OnWriteComplete); private static AsyncEventArgsCallback onGetBufferComplete = new AsyncEventArgsCallback(OnGetBufferComplete); public InternalWriteBase64TextAsyncWriter(XmlUTF8NodeWriter writer) { this.writer = writer; writerState = new AsyncEventArgs(); writerArgs = new XmlWriteBase64AsyncArguments(); } internal AsyncCompletionResult StartAsync(AsyncEventArgs xmlNodeWriterState) { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Invalid comparison between Unknown and I4 //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Invalid comparison between Unknown and I4 nodeState = xmlNodeWriterState; XmlNodeWriterWriteBase64TextArgs arguments = xmlNodeWriterState.Arguments; if (arguments.TrailCount > 0) { writerArgs.Buffer = arguments.TrailBuffer; writerArgs.Offset = 0; writerArgs.Count = arguments.TrailCount; writerState.Set(onTrailByteComplete, writerArgs, (object)this); if ((int)InternalWriteBase64TextAsync(writerState) != 1) { return (AsyncCompletionResult)0; } ((AsyncEventArgs)writerState).Complete(true); } if ((int)WriteBufferAsync() == 1) { nodeState = null; return (AsyncCompletionResult)1; } return (AsyncCompletionResult)0; } private static void OnTrailBytesComplete(IAsyncEventArgs eventArgs) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Invalid comparison between Unknown and I4 InternalWriteBase64TextAsyncWriter internalWriteBase64TextAsyncWriter = (InternalWriteBase64TextAsyncWriter)eventArgs.AsyncState; bool flag = false; try { if (eventArgs.Exception != null) { _ = eventArgs.Exception; flag = true; } else if ((int)internalWriteBase64TextAsyncWriter.WriteBufferAsync() == 1) { flag = true; } } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } flag = true; } if (flag) { AsyncEventArgs val = internalWriteBase64TextAsyncWriter.nodeState; internalWriteBase64TextAsyncWriter.nodeState = null; ((AsyncEventArgs)val).Complete(false, eventArgs.Exception); } } private AsyncCompletionResult WriteBufferAsync() { //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Invalid comparison between Unknown and I4 writerArgs.Buffer = nodeState.Arguments.Buffer; writerArgs.Offset = nodeState.Arguments.Offset; writerArgs.Count = nodeState.Arguments.Count; writerState.Set(onWriteComplete, writerArgs, (object)this); if ((int)InternalWriteBase64TextAsync(writerState) == 1) { ((AsyncEventArgs)writerState).Complete(true); return (AsyncCompletionResult)1; } return (AsyncCompletionResult)0; } private static void OnWriteComplete(IAsyncEventArgs eventArgs) { InternalWriteBase64TextAsyncWriter obj = (InternalWriteBase64TextAsyncWriter)eventArgs.AsyncState; AsyncEventArgs val = obj.nodeState; obj.nodeState = null; ((AsyncEventArgs)val).Complete(false, eventArgs.Exception); } private AsyncCompletionResult InternalWriteBase64TextAsync(AsyncEventArgs writerState) { //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Invalid comparison between Unknown and I4 //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Invalid comparison between Unknown and I4 GetBufferAsyncEventArgs getBufferAsyncEventArgs = getBufferState; GetBufferArgs getBufferArgs = this.getBufferArgs; XmlWriteBase64AsyncArguments arguments = writerState.Arguments; if (getBufferAsyncEventArgs == null) { getBufferAsyncEventArgs = new GetBufferAsyncEventArgs(); getBufferArgs = new GetBufferArgs(); getBufferState = getBufferAsyncEventArgs; this.getBufferArgs = getBufferArgs; } Base64Encoding base64Encoding = XmlConverter.Base64Encoding; while (arguments.Count >= 3) { int num = Math.Min(384, arguments.Count - arguments.Count % 3); int count = num / 3 * 4; getBufferArgs.Count = count; ((AsyncEventArgs)(object)getBufferAsyncEventArgs).Set(onGetBufferComplete, getBufferArgs, (object)this); if ((int)writer.GetBufferAsync(getBufferAsyncEventArgs) == 1) { GetBufferEventResult result = ((AsyncEventArgs)getBufferAsyncEventArgs).Result; ((AsyncEventArgs)getBufferAsyncEventArgs).Complete(true); writer.Advance(base64Encoding.GetChars(arguments.Buffer, arguments.Offset, num, result.Buffer, result.Offset)); arguments.Offset += num; arguments.Count -= num; continue; } return (AsyncCompletionResult)0; } if (arguments.Count > 0) { getBufferArgs.Count = 4; ((AsyncEventArgs)(object)getBufferAsyncEventArgs).Set(onGetBufferComplete, getBufferArgs, (object)this); if ((int)writer.GetBufferAsync(getBufferAsyncEventArgs) != 1) { return (AsyncCompletionResult)0; } GetBufferEventResult result2 = ((AsyncEventArgs)getBufferAsyncEventArgs).Result; ((AsyncEventArgs)getBufferAsyncEventArgs).Complete(true); writer.Advance(base64Encoding.GetChars(arguments.Buffer, arguments.Offset, arguments.Count, result2.Buffer, result2.Offset)); } return (AsyncCompletionResult)1; } private static void OnGetBufferComplete(IAsyncEventArgs state) { //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Invalid comparison between Unknown and I4 GetBufferEventResult result = ((AsyncEventArgs)(GetBufferAsyncEventArgs)(object)state).Result; InternalWriteBase64TextAsyncWriter internalWriteBase64TextAsyncWriter = (InternalWriteBase64TextAsyncWriter)state.AsyncState; XmlWriteBase64AsyncArguments arguments = internalWriteBase64TextAsyncWriter.writerState.Arguments; Exception ex = null; bool flag = false; try { if (state.Exception != null) { ex = state.Exception; flag = true; } else { byte[] buffer = result.Buffer; int offset = result.Offset; Base64Encoding base64Encoding = XmlConverter.Base64Encoding; int num = Math.Min(384, arguments.Count - arguments.Count % 3); _ = num / 3; internalWriteBase64TextAsyncWriter.writer.Advance(base64Encoding.GetChars(arguments.Buffer, arguments.Offset, num, buffer, offset)); if (num >= 3) { arguments.Offset += num; arguments.Count -= num; } if ((int)internalWriteBase64TextAsyncWriter.InternalWriteBase64TextAsync(internalWriteBase64TextAsyncWriter.writerState) == 1) { flag = true; } } } catch (Exception ex2) { if (Fx.IsFatal(ex2)) { throw; } ex = ex2; flag = true; } if (flag) { ((AsyncEventArgs)internalWriteBase64TextAsyncWriter.writerState).Complete(false, ex); } } } private class WriteBase64TextAsyncResult : AsyncResult { private static AsyncCompletion onTrailBytesComplete = new AsyncCompletion(OnTrailBytesComplete); private static AsyncCompletion onComplete = new AsyncCompletion(OnComplete); private byte[] trailBytes; private int trailByteCount; private byte[] buffer; private int offset; private int count; private XmlUTF8NodeWriter writer; public WriteBase64TextAsyncResult(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count, XmlUTF8NodeWriter writer, AsyncCallback callback, object state) : base(callback, state) { this.writer = writer; this.trailBytes = trailBytes; this.trailByteCount = trailByteCount; this.buffer = buffer; this.offset = offset; this.count = count; if (HandleWriteTrailBytes(null)) { ((AsyncResult)this).Complete(true); } } private static bool OnTrailBytesComplete(IAsyncResult result) { return ((WriteBase64TextAsyncResult)result.AsyncState).HandleWriteTrailBytes(result); } private static bool OnComplete(IAsyncResult result) { return ((WriteBase64TextAsyncResult)result.AsyncState).HandleWriteBase64Text(result); } private bool HandleWriteTrailBytes(IAsyncResult result) { if (trailByteCount > 0) { if (result == null) { result = writer.BeginInternalWriteBase64Text(trailBytes, 0, trailByteCount, ((AsyncResult)this).PrepareAsyncCompletion(onTrailBytesComplete), this); if (!result.CompletedSynchronously) { return false; } } writer.EndInternalWriteBase64Text(result); } return HandleWriteBase64Text(null); } private bool HandleWriteBase64Text(IAsyncResult result) { if (result == null) { result = writer.BeginInternalWriteBase64Text(buffer, offset, count, ((AsyncResult)this).PrepareAsyncCompletion(onComplete), this); if (!result.CompletedSynchronously) { return false; } } writer.EndInternalWriteBase64Text(result); return true; } public static void End(IAsyncResult result) { AsyncResult.End(result); } } private class InternalWriteBase64TextAsyncResult : AsyncResult { private byte[] buffer; private int offset; private int count; private Base64Encoding encoding; private XmlUTF8NodeWriter writer; private static AsyncCallback onWriteCharacters = Fx.ThunkCallback((AsyncCallback)OnWriteCharacters); private static AsyncCompletion onWriteTrailingCharacters = new AsyncCompletion(OnWriteTrailingCharacters); public InternalWriteBase64TextAsyncResult(byte[] buffer, int offset, int count, XmlUTF8NodeWriter writer, AsyncCallback callback, object state) : base(callback, state) { this.buffer = buffer; this.offset = offset; this.count = count; this.writer = writer; encoding = XmlConverter.Base64Encoding; if (ContinueWork()) { ((AsyncResult)this).Complete(true); } } private static bool OnWriteTrailingCharacters(IAsyncResult result) { return ((InternalWriteBase64TextAsyncResult)result.AsyncState).HandleWriteTrailingCharacters(result); } private bool ContinueWork() { while (count >= 3) { if (!HandleWriteCharacters(null)) { return false; } } if (count > 0) { return HandleWriteTrailingCharacters(null); } return true; } private bool HandleWriteCharacters(IAsyncResult result) { int num = Math.Min(384, count - count % 3); int num2 = num / 3 * 4; if (result == null) { result = writer.BeginGetBuffer(num2, onWriteCharacters, this); if (!result.CompletedSynchronously) { return false; } } int charIndex; byte[] chars = writer.EndGetBuffer(result, out charIndex); writer.Advance(encoding.GetChars(buffer, offset, num, chars, charIndex)); offset += num; count -= num; return true; } private bool HandleWriteTrailingCharacters(IAsyncResult result) { if (result == null) { result = writer.BeginGetBuffer(4, ((AsyncResult)this).PrepareAsyncCompletion(onWriteTrailingCharacters), this); if (!result.CompletedSynchronously) { return false; } } int charIndex; byte[] chars = writer.EndGetBuffer(result, out charIndex); writer.Advance(encoding.GetChars(buffer, offset, count, chars, charIndex)); return true; } private static void OnWriteCharacters(IAsyncResult result) { if (result.CompletedSynchronously) { return; } InternalWriteBase64TextAsyncResult internalWriteBase64TextAsyncResult = (InternalWriteBase64TextAsyncResult)result.AsyncState; Exception ex = null; bool flag = false; try { internalWriteBase64TextAsyncResult.HandleWriteCharacters(result); flag = internalWriteBase64TextAsyncResult.ContinueWork(); } catch (Exception ex2) { if (Fx.IsFatal(ex2)) { throw; } flag = true; ex = ex2; } if (flag) { ((AsyncResult)internalWriteBase64TextAsyncResult).Complete(false, ex); } } public static void End(IAsyncResult result) { AsyncResult.End(result); } } private byte[] entityChars; private bool[] isEscapedAttributeChar; private bool[] isEscapedElementChar; private bool inAttribute; private const int bufferLength = 512; private const int maxEntityLength = 32; private const int maxBytesPerChar = 3; private Encoding encoding; private char[] chars; private InternalWriteBase64TextAsyncWriter internalWriteBase64TextAsyncWriter; private static readonly byte[] startDecl = new byte[30] { 60, 63, 120, 109, 108, 32, 118, 101, 114, 115, 105, 111, 110, 61, 34, 49, 46, 48, 34, 32, 101, 110, 99, 111, 100, 105, 110, 103, 61, 34 }; private static readonly byte[] endDecl = new byte[3] { 34, 63, 62 }; private static readonly byte[] utf8Decl = new byte[38] { 60, 63, 120, 109, 108, 32, 118, 101, 114, 115, 105, 111, 110, 61, 34, 49, 46, 48, 34, 32, 101, 110, 99, 111, 100, 105, 110, 103, 61, 34, 117, 116, 102, 45, 56, 34, 63, 62 }; private static readonly byte[] digits = new byte[16] { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70 }; private static readonly bool[] defaultIsEscapedAttributeChar = new bool[64] { true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, true, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false }; private static readonly bool[] defaultIsEscapedElementChar = new bool[64] { true, true, true, true, true, true, true, true, true, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false }; public Encoding Encoding => encoding; public XmlUTF8NodeWriter() : this(defaultIsEscapedAttributeChar, defaultIsEscapedElementChar) { } public XmlUTF8NodeWriter(bool[] isEscapedAttributeChar, bool[] isEscapedElementChar) { this.isEscapedAttributeChar = isEscapedAttributeChar; this.isEscapedElementChar = isEscapedElementChar; inAttribute = false; } public new void SetOutput(Stream stream, bool ownsStream, Encoding encoding) { Encoding encoding2 = null; if (encoding != null && encoding.CodePage == Encoding.UTF8.CodePage) { encoding2 = encoding; encoding = null; } base.SetOutput(stream, ownsStream, encoding2); this.encoding = encoding; inAttribute = false; } private byte[] GetCharEntityBuffer() { if (entityChars == null) { entityChars = new byte[32]; } return entityChars; } private char[] GetCharBuffer(int charCount) { if (charCount >= 256) { return new char[charCount]; } if (chars == null || chars.Length < charCount) { chars = new char[charCount]; } return chars; } public override void WriteDeclaration() { if (encoding == null) { WriteUTF8Chars(utf8Decl, 0, utf8Decl.Length); return; } WriteUTF8Chars(startDecl, 0, startDecl.Length); if (encoding.WebName == Encoding.BigEndianUnicode.WebName) { WriteUTF8Chars("utf-16BE"); } else { WriteUTF8Chars(encoding.WebName); } WriteUTF8Chars(endDecl, 0, endDecl.Length); } public override void WriteCData(string text) { int num; byte[] array = GetBuffer(9, out num); array[num] = 60; array[num + 1] = 33; array[num + 2] = 91; array[num + 3] = 67; array[num + 4] = 68; array[num + 5] = 65; array[num + 6] = 84; array[num + 7] = 65; array[num + 8] = 91; Advance(9); WriteUTF8Chars(text); byte[] array2 = GetBuffer(3, out num); array2[num] = 93; array2[num + 1] = 93; array2[num + 2] = 62; Advance(3); } private void WriteStartComment() { int num; byte[] array = GetBuffer(4, out num); array[num] = 60; array[num + 1] = 33; array[num + 2] = 45; array[num + 3] = 45; Advance(4); } private void WriteEndComment() { int num; byte[] array = GetBuffer(3, out num); array[num] = 45; array[num + 1] = 45; array[num + 2] = 62; Advance(3); } public override void WriteComment(string text) { WriteStartComment(); WriteUTF8Chars(text); WriteEndComment(); } public override void WriteStartElement(string prefix, string localName) { WriteByte('<'); if (prefix.Length != 0) { WritePrefix(prefix); WriteByte(':'); } WriteLocalName(localName); } public override void WriteStartElement(string prefix, XmlDictionaryString localName) { WriteStartElement(prefix, localName.Value); } public override void WriteStartElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteByte('<'); if (prefixLength != 0) { WritePrefix(prefixBuffer, prefixOffset, prefixLength); WriteByte(':'); } WriteLocalName(localNameBuffer, localNameOffset, localNameLength); } public override void WriteEndStartElement(bool isEmpty) { if (!isEmpty) { WriteByte('>'); } else { WriteBytes('/', '>'); } } public override void WriteEndElement(string prefix, string localName) { WriteBytes('<', '/'); if (prefix.Length != 0) { WritePrefix(prefix); WriteByte(':'); } WriteLocalName(localName); WriteByte('>'); } public override void WriteEndElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteBytes('<', '/'); if (prefixLength != 0) { WritePrefix(prefixBuffer, prefixOffset, prefixLength); WriteByte(':'); } WriteLocalName(localNameBuffer, localNameOffset, localNameLength); WriteByte('>'); } private void WriteStartXmlnsAttribute() { int num; byte[] array = GetBuffer(6, out num); array[num] = 32; array[num + 1] = 120; array[num + 2] = 109; array[num + 3] = 108; array[num + 4] = 110; array[num + 5] = 115; Advance(6); inAttribute = true; } public override void WriteXmlnsAttribute(string prefix, string ns) { WriteStartXmlnsAttribute(); if (prefix.Length != 0) { WriteByte(':'); WritePrefix(prefix); } WriteBytes('=', '"'); WriteEscapedText(ns); WriteEndAttribute(); } public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) { WriteXmlnsAttribute(prefix, ns.Value); } public override void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] nsBuffer, int nsOffset, int nsLength) { WriteStartXmlnsAttribute(); if (prefixLength != 0) { WriteByte(':'); WritePrefix(prefixBuffer, prefixOffset, prefixLength); } WriteBytes('=', '"'); WriteEscapedText(nsBuffer, nsOffset, nsLength); WriteEndAttribute(); } public override void WriteStartAttribute(string prefix, string localName) { WriteByte(' '); if (prefix.Length != 0) { WritePrefix(prefix); WriteByte(':'); } WriteLocalName(localName); WriteBytes('=', '"'); inAttribute = true; } public override void WriteStartAttribute(string prefix, XmlDictionaryString localName) { WriteStartAttribute(prefix, localName.Value); } public override void WriteStartAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteByte(' '); if (prefixLength != 0) { WritePrefix(prefixBuffer, prefixOffset, prefixLength); WriteByte(':'); } WriteLocalName(localNameBuffer, localNameOffset, localNameLength); WriteBytes('=', '"'); inAttribute = true; } public override void WriteEndAttribute() { WriteByte('"'); inAttribute = false; } private void WritePrefix(string prefix) { if (prefix.Length == 1) { WriteUTF8Char(prefix[0]); } else { WriteUTF8Chars(prefix); } } private void WritePrefix(byte[] prefixBuffer, int prefixOffset, int prefixLength) { if (prefixLength == 1) { WriteUTF8Char(prefixBuffer[prefixOffset]); } else { WriteUTF8Chars(prefixBuffer, prefixOffset, prefixLength); } } private void WriteLocalName(string localName) { WriteUTF8Chars(localName); } private void WriteLocalName(byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteUTF8Chars(localNameBuffer, localNameOffset, localNameLength); } public override void WriteEscapedText(XmlDictionaryString s) { WriteEscapedText(s.Value); } [SecuritySafeCritical] public unsafe override void WriteEscapedText(string s) { int length = s.Length; if (length > 0) { fixed (char* ptr = s) { UnsafeWriteEscapedText(ptr, length); } } } [SecuritySafeCritical] public unsafe override void WriteEscapedText(char[] s, int offset, int count) { if (count > 0) { fixed (char* ptr = &s[offset]) { UnsafeWriteEscapedText(ptr, count); } } } [SecurityCritical] private unsafe void UnsafeWriteEscapedText(char* chars, int count) { bool[] array = (inAttribute ? isEscapedAttributeChar : isEscapedElementChar); int num = array.Length; int num2 = 0; for (int i = 0; i < count; i++) { char c = chars[i]; if ((c < num && array[(uint)c]) || c >= '\ufffe') { UnsafeWriteUTF8Chars(chars + num2, i - num2); WriteCharEntity(c); num2 = i + 1; } } UnsafeWriteUTF8Chars(chars + num2, count - num2); } public override void WriteEscapedText(byte[] chars, int offset, int count) { bool[] array = (inAttribute ? isEscapedAttributeChar : isEscapedElementChar); int num = array.Length; int num2 = 0; for (int i = 0; i < count; i++) { byte b = chars[offset + i]; if (b < num && array[b]) { WriteUTF8Chars(chars, offset + num2, i - num2); WriteCharEntity(b); num2 = i + 1; } else if (b == 239 && offset + i + 2 < count) { byte num3 = chars[offset + i + 1]; byte b2 = chars[offset + i + 2]; if (num3 == 191 && (b2 == 190 || b2 == 191)) { WriteUTF8Chars(chars, offset + num2, i - num2); WriteCharEntity((b2 == 190) ? 65534 : 65535); num2 = i + 3; } } } WriteUTF8Chars(chars, offset + num2, count - num2); } public void WriteText(int ch) { WriteUTF8Char(ch); } public override void WriteText(byte[] chars, int offset, int count) { WriteUTF8Chars(chars, offset, count); } [SecuritySafeCritical] public unsafe override void WriteText(char[] chars, int offset, int count) { if (count > 0) { fixed (char* ptr = &chars[offset]) { UnsafeWriteUTF8Chars(ptr, count); } } } public override void WriteText(string value) { WriteUTF8Chars(value); } public override void WriteText(XmlDictionaryString value) { WriteUTF8Chars(value.Value); } public void WriteLessThanCharEntity() { int num; byte[] array = GetBuffer(4, out num); array[num] = 38; array[num + 1] = 108; array[num + 2] = 116; array[num + 3] = 59; Advance(4); } public void WriteGreaterThanCharEntity() { int num; byte[] array = GetBuffer(4, out num); array[num] = 38; array[num + 1] = 103; array[num + 2] = 116; array[num + 3] = 59; Advance(4); } public void WriteAmpersandCharEntity() { int num; byte[] array = GetBuffer(5, out num); array[num] = 38; array[num + 1] = 97; array[num + 2] = 109; array[num + 3] = 112; array[num + 4] = 59; Advance(5); } public void WriteApostropheCharEntity() { int num; byte[] array = GetBuffer(6, out num); array[num] = 38; array[num + 1] = 97; array[num + 2] = 112; array[num + 3] = 111; array[num + 4] = 115; array[num + 5] = 59; Advance(6); } public void WriteQuoteCharEntity() { int num; byte[] array = GetBuffer(6, out num); array[num] = 38; array[num + 1] = 113; array[num + 2] = 117; array[num + 3] = 111; array[num + 4] = 116; array[num + 5] = 59; Advance(6); } private void WriteHexCharEntity(int ch) { byte[] charEntityBuffer = GetCharEntityBuffer(); int num = 32; charEntityBuffer[--num] = 59; num -= ToBase16(charEntityBuffer, num, (uint)ch); charEntityBuffer[--num] = 120; charEntityBuffer[--num] = 35; charEntityBuffer[--num] = 38; WriteUTF8Chars(charEntityBuffer, num, 32 - num); } public override void WriteCharEntity(int ch) { switch (ch) { case 60: WriteLessThanCharEntity(); break; case 62: WriteGreaterThanCharEntity(); break; case 38: WriteAmpersandCharEntity(); break; case 39: WriteApostropheCharEntity(); break; case 34: WriteQuoteCharEntity(); break; default: WriteHexCharEntity(ch); break; } } private int ToBase16(byte[] chars, int offset, uint value) { int num = 0; do { num++; chars[--offset] = digits[value & 0xF]; value /= 16; } while (value != 0); return num; } public override void WriteBoolText(bool value) { int num; byte[] array = GetBuffer(5, out num); Advance(XmlConverter.ToChars(value, array, num)); } public override void WriteDecimalText(decimal value) { int num; byte[] array = GetBuffer(40, out num); Advance(XmlConverter.ToChars(value, array, num)); } public override void WriteDoubleText(double value) { int num; byte[] array = GetBuffer(32, out num); Advance(XmlConverter.ToChars(value, array, num)); } public override void WriteFloatText(float value) { int num; byte[] array = GetBuffer(16, out num); Advance(XmlConverter.ToChars(value, array, num)); } public override void WriteDateTimeText(DateTime value) { int num; byte[] array = GetBuffer(64, out num); Advance(XmlConverter.ToChars(value, array, num)); } public override void WriteUniqueIdText(UniqueId value) { if (value.IsGuid) { int charArrayLength = value.CharArrayLength; char[] charBuffer = GetCharBuffer(charArrayLength); value.ToCharArray(charBuffer, 0); WriteText(charBuffer, 0, charArrayLength); } else { WriteEscapedText(value.ToString()); } } public override void WriteInt32Text(int value) { int num; byte[] array = GetBuffer(16, out num); Advance(XmlConverter.ToChars(value, array, num)); } public override void WriteInt64Text(long value) { int num; byte[] array = GetBuffer(32, out num); Advance(XmlConverter.ToChars(value, array, num)); } public override void WriteUInt64Text(ulong value) { int num; byte[] array = GetBuffer(32, out num); Advance(XmlConverter.ToChars(value, array, num)); } public override void WriteGuidText(Guid value) { WriteText(value.ToString()); } public override void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count) { if (trailByteCount > 0) { InternalWriteBase64Text(trailBytes, 0, trailByteCount); } InternalWriteBase64Text(buffer, offset, count); } private void InternalWriteBase64Text(byte[] buffer, int offset, int count) { Base64Encoding base64Encoding = XmlConverter.Base64Encoding; while (count >= 3) { int num = Math.Min(384, count - count % 3); int count2 = num / 3 * 4; int charIndex; byte[] array = GetBuffer(count2, out charIndex); Advance(base64Encoding.GetChars(buffer, offset, num, array, charIndex)); offset += num; count -= num; } if (count > 0) { int charIndex2; byte[] array2 = GetBuffer(4, out charIndex2); Advance(base64Encoding.GetChars(buffer, offset, count, array2, charIndex2)); } } internal override AsyncCompletionResult WriteBase64TextAsync(AsyncEventArgs xmlNodeWriterState) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) if (internalWriteBase64TextAsyncWriter == null) { internalWriteBase64TextAsyncWriter = new InternalWriteBase64TextAsyncWriter(this); } return internalWriteBase64TextAsyncWriter.StartAsync(xmlNodeWriterState); } public override IAsyncResult BeginWriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return (IAsyncResult)new WriteBase64TextAsyncResult(trailBytes, trailByteCount, buffer, offset, count, this, callback, state); } public override void EndWriteBase64Text(IAsyncResult result) { WriteBase64TextAsyncResult.End(result); } private IAsyncResult BeginInternalWriteBase64Text(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return (IAsyncResult)new InternalWriteBase64TextAsyncResult(buffer, offset, count, this, callback, state); } private void EndInternalWriteBase64Text(IAsyncResult result) { InternalWriteBase64TextAsyncResult.End(result); } public override void WriteTimeSpanText(TimeSpan value) { WriteText(XmlConvert.ToString(value)); } public override void WriteStartListText() { } public override void WriteListSeparator() { WriteByte(' '); } public override void WriteEndListText() { } public override void WriteQualifiedName(string prefix, XmlDictionaryString localName) { if (prefix.Length != 0) { WritePrefix(prefix); WriteByte(':'); } WriteText(localName); } } internal class XmlWriteBase64AsyncArguments { internal byte[] Buffer { get; set; } internal int Index { get; set; } internal int Count { get; set; } internal int Offset { get; set; } } internal static class XmlExceptionHelper { private static void ThrowXmlException(XmlDictionaryReader reader, string res) { ThrowXmlException(reader, res, null); } private static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1) { ThrowXmlException(reader, res, arg1, null); } private static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1, string arg2) { ThrowXmlException(reader, res, arg1, arg2, null); } private static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1, string arg2, string arg3) { string text = System.Runtime.Serialization.SR.GetString(res, arg1, arg2, arg3); if (reader is IXmlLineInfo xmlLineInfo && xmlLineInfo.HasLineInfo()) { text = text + " " + System.Runtime.Serialization.SR.GetString("Line {0}, position {1}.", xmlLineInfo.LineNumber, xmlLineInfo.LinePosition); } if (TD.ReaderQuotaExceededIsEnabled()) { TD.ReaderQuotaExceeded(text); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(text)); } public static void ThrowXmlException(XmlDictionaryReader reader, XmlException exception) { string text = exception.Message; if (reader is IXmlLineInfo xmlLineInfo && xmlLineInfo.HasLineInfo()) { text = text + " " + System.Runtime.Serialization.SR.GetString("Line {0}, position {1}.", xmlLineInfo.LineNumber, xmlLineInfo.LinePosition); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(text)); } private static string GetName(string prefix, string localName) { if (prefix.Length == 0) { return localName; } return prefix + ":" + localName; } private static string GetWhatWasFound(XmlDictionaryReader reader) { if (reader.EOF) { return System.Runtime.Serialization.SR.GetString("end of file"); } switch (reader.NodeType) { case XmlNodeType.Element: return System.Runtime.Serialization.SR.GetString("element '{0}' from namespace '{1}'", GetName(reader.Prefix, reader.LocalName), reader.NamespaceURI); case XmlNodeType.EndElement: return System.Runtime.Serialization.SR.GetString("end element '{0}' from namespace '{1}'", GetName(reader.Prefix, reader.LocalName), reader.NamespaceURI); case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: return System.Runtime.Serialization.SR.GetString("text '{0}'", reader.Value); case XmlNodeType.Comment: return System.Runtime.Serialization.SR.GetString("comment '{0}'", reader.Value); case XmlNodeType.CDATA: return System.Runtime.Serialization.SR.GetString("cdata '{0}'", reader.Value); default: return System.Runtime.Serialization.SR.GetString("node {0}", reader.NodeType); } } public static void ThrowStartElementExpected(XmlDictionaryReader reader) { ThrowXmlException(reader, "Start element expected. Found {0}.", GetWhatWasFound(reader)); } public static void ThrowStartElementExpected(XmlDictionaryReader reader, string name) { ThrowXmlException(reader, "Start element '{0}' expected. Found {1}.", name, GetWhatWasFound(reader)); } public static void ThrowStartElementExpected(XmlDictionaryReader reader, string localName, string ns) { ThrowXmlException(reader, "Start element '{0}' from namespace '{1}' expected. Found {2}.", localName, ns, GetWhatWasFound(reader)); } public static void ThrowStartElementExpected(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString ns) { ThrowStartElementExpected(reader, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(ns)); } public static void ThrowFullStartElementExpected(XmlDictionaryReader reader) { ThrowXmlException(reader, "Non-empty start element expected. Found {0}.", GetWhatWasFound(reader)); } public static void ThrowFullStartElementExpected(XmlDictionaryReader reader, string name) { ThrowXmlException(reader, "Non-empty start element '{0}' expected. Found {1}.", name, GetWhatWasFound(reader)); } public static void ThrowFullStartElementExpected(XmlDictionaryReader reader, string localName, string ns) { ThrowXmlException(reader, "Non-empty start element '{0}' from namespace '{1}' expected. Found {2}.", localName, ns, GetWhatWasFound(reader)); } public static void ThrowFullStartElementExpected(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString ns) { ThrowFullStartElementExpected(reader, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(ns)); } public static void ThrowEndElementExpected(XmlDictionaryReader reader, string localName, string ns) { ThrowXmlException(reader, "End element '{0}' from namespace '{1}' expected. Found {2}.", localName, ns, GetWhatWasFound(reader)); } public static void ThrowMaxStringContentLengthExceeded(XmlDictionaryReader reader, int maxStringContentLength) { ThrowXmlException(reader, "XML max string content length exceeded. It must be less than {0}.", maxStringContentLength.ToString(NumberFormatInfo.CurrentInfo)); } public static void ThrowMaxArrayLengthExceeded(XmlDictionaryReader reader, int maxArrayLength) { ThrowXmlException(reader, "The maximum array length quota ({0}) has been exceeded while reading XML data. This quota may be increased by changing the MaxArrayLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader.", maxArrayLength.ToString(NumberFormatInfo.CurrentInfo)); } public static void ThrowMaxArrayLengthOrMaxItemsQuotaExceeded(XmlDictionaryReader reader, int maxQuota) { ThrowXmlException(reader, "XML max array length or max items quota exceeded. It must be less than {0}.", maxQuota.ToString(NumberFormatInfo.CurrentInfo)); } public static void ThrowMaxDepthExceeded(XmlDictionaryReader reader, int maxDepth) { ThrowXmlException(reader, "XML max depth exceeded. It must be less than {0}.", maxDepth.ToString(NumberFormatInfo.CurrentInfo)); } public static void ThrowMaxBytesPerReadExceeded(XmlDictionaryReader reader, int maxBytesPerRead) { ThrowXmlException(reader, "XML max bytes per read exceeded. It must be less than {0}.", maxBytesPerRead.ToString(NumberFormatInfo.CurrentInfo)); } public static void ThrowMaxNameTableCharCountExceeded(XmlDictionaryReader reader, int maxNameTableCharCount) { ThrowXmlException(reader, "The maximum nametable character count quota ({0}) has been exceeded while reading XML data. The nametable is a data structure used to store strings encountered during XML processing - long XML documents with non-repeating element names, attribute names and attribute values may trigger this quota. This quota may be increased by changing the MaxNameTableCharCount property on the XmlDictionaryReaderQuotas object used when creating the XML reader.", maxNameTableCharCount.ToString(NumberFormatInfo.CurrentInfo)); } public static void ThrowBase64DataExpected(XmlDictionaryReader reader) { ThrowXmlException(reader, "Base64 encoded data expected. Found {0}.", GetWhatWasFound(reader)); } public static void ThrowUndefinedPrefix(XmlDictionaryReader reader, string prefix) { ThrowXmlException(reader, "The prefix '{0}' is not defined.", prefix); } public static void ThrowProcessingInstructionNotSupported(XmlDictionaryReader reader) { ThrowXmlException(reader, "Processing instructions (other than the XML declaration) and DTDs are not supported."); } public static void ThrowInvalidXml(XmlDictionaryReader reader, byte b) { ThrowXmlException(reader, "The byte 0x{0} is not valid at this location.", b.ToString("X2", CultureInfo.InvariantCulture)); } public static void ThrowUnexpectedEndOfFile(XmlDictionaryReader reader) { ThrowXmlException(reader, "Unexpected end of file. Following elements are not closed: {0}.", ((XmlBaseReader)reader).GetOpenElements()); } public static void ThrowUnexpectedEndElement(XmlDictionaryReader reader) { ThrowXmlException(reader, "No matching start tag for end element."); } public static void ThrowTokenExpected(XmlDictionaryReader reader, string expected, char found) { ThrowXmlException(reader, "The token '{0}' was expected but found '{1}'.", expected, found.ToString()); } public static void ThrowTokenExpected(XmlDictionaryReader reader, string expected, string found) { ThrowXmlException(reader, "The token '{0}' was expected but found '{1}'.", expected, found); } public static void ThrowInvalidCharRef(XmlDictionaryReader reader) { ThrowXmlException(reader, "Character reference not valid."); } public static void ThrowTagMismatch(XmlDictionaryReader reader, string expectedPrefix, string expectedLocalName, string foundPrefix, string foundLocalName) { ThrowXmlException(reader, "Start element '{0}' does not match end element '{1}'.", GetName(expectedPrefix, expectedLocalName), GetName(foundPrefix, foundLocalName)); } public static void ThrowDuplicateXmlnsAttribute(XmlDictionaryReader reader, string localName, string ns) { string text = ((localName.Length != 0) ? ("xmlns:" + localName) : "xmlns"); ThrowXmlException(reader, "Duplicate attribute found. Both '{0}' and '{1}' are from the namespace '{2}'.", text, text, ns); } public static void ThrowDuplicateAttribute(XmlDictionaryReader reader, string prefix1, string prefix2, string localName, string ns) { ThrowXmlException(reader, "Duplicate attribute found. Both '{0}' and '{1}' are from the namespace '{2}'.", GetName(prefix1, localName), GetName(prefix2, localName), ns); } public static void ThrowInvalidBinaryFormat(XmlDictionaryReader reader) { ThrowXmlException(reader, "The input source is not correctly formatted."); } public static void ThrowInvalidRootData(XmlDictionaryReader reader) { ThrowXmlException(reader, "The data at the root level is invalid."); } public static void ThrowMultipleRootElements(XmlDictionaryReader reader) { ThrowXmlException(reader, "There are multiple root elements."); } public static void ThrowDeclarationNotFirst(XmlDictionaryReader reader) { ThrowXmlException(reader, "No characters can appear before the XML declaration."); } public static void ThrowConversionOverflow(XmlDictionaryReader reader, string value, string type) { ThrowXmlException(reader, "The value '{0}' cannot be represented with the type '{1}'.", value, type); } public static void ThrowXmlDictionaryStringIDOutOfRange(XmlDictionaryReader reader) { ThrowXmlException(reader, "XmlDictionaryString IDs must be in the range from {0} to {1}.", 0.ToString(NumberFormatInfo.CurrentInfo), 536870911.ToString(NumberFormatInfo.CurrentInfo)); } public static void ThrowXmlDictionaryStringIDUndefinedStatic(XmlDictionaryReader reader, int key) { ThrowXmlException(reader, "XmlDictionaryString ID {0} not defined in the static dictionary.", key.ToString(NumberFormatInfo.CurrentInfo)); } public static void ThrowXmlDictionaryStringIDUndefinedSession(XmlDictionaryReader reader, int key) { ThrowXmlException(reader, "XmlDictionaryString ID {0} not defined in the XmlBinaryReaderSession.", key.ToString(NumberFormatInfo.CurrentInfo)); } public static void ThrowEmptyNamespace(XmlDictionaryReader reader) { ThrowXmlException(reader, "The empty namespace requires a null or empty prefix."); } public static XmlException CreateConversionException(string value, string type, Exception exception) { return new XmlException(System.Runtime.Serialization.SR.GetString("The value '{0}' cannot be parsed as the type '{1}'.", value, type), exception); } public static XmlException CreateEncodingException(byte[] buffer, int offset, int count, Exception exception) { return CreateEncodingException(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false).GetString(buffer, offset, count), exception); } public static XmlException CreateEncodingException(string value, Exception exception) { return new XmlException(System.Runtime.Serialization.SR.GetString("'{0}' contains invalid UTF8 bytes.", value), exception); } } } namespace System.Text { internal class Base64Encoding : Encoding { private static byte[] char2val = new byte[128] { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 64, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255, 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 255, 255, 255, 255, 255 }; private static string val2char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; private static byte[] val2byte = new byte[64] { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47 }; public override int GetMaxByteCount(int charCount) { if (charCount < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charCount", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (charCount % 4 != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("Base64 sequence length ({0}) not valid. Must be a multiple of 4.", charCount.ToString(NumberFormatInfo.CurrentInfo)))); } return charCount / 4 * 3; } private bool IsValidLeadBytes(int v1, int v2, int v3, int v4) { if ((v1 | v2) < 64) { return (v3 | v4) != 255; } return false; } private bool IsValidTailBytes(int v3, int v4) { if (v3 == 64) { return v4 == 64; } return true; } [SecuritySafeCritical] public unsafe override int GetByteCount(char[] chars, int index, int count) { if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); } if (index < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (index > chars.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (count > chars.Length - index) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", chars.Length - index))); } if (count == 0) { return 0; } if (count % 4 != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("Base64 sequence length ({0}) not valid. Must be a multiple of 4.", count.ToString(NumberFormatInfo.CurrentInfo)))); } fixed (byte* ptr4 = char2val) { fixed (char* ptr = &chars[index]) { int num = 0; char* ptr2 = ptr; for (char* ptr3 = ptr + count; ptr2 < ptr3; ptr2 += 4) { char c = *ptr2; char c2 = ptr2[1]; char c3 = ptr2[2]; char c4 = ptr2[3]; if ((c | c2 | c3 | c4) >= 128) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("The characters '{0}' at offset {1} are not a valid Base64 sequence.", new string(ptr2, 0, 4), index + (int)(ptr2 - ptr)))); } int v = ptr4[(int)c]; int v2 = ptr4[(int)c2]; int num2 = ptr4[(int)c3]; int num3 = ptr4[(int)c4]; if (!IsValidLeadBytes(v, v2, num2, num3) || !IsValidTailBytes(num2, num3)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("The characters '{0}' at offset {1} are not a valid Base64 sequence.", new string(ptr2, 0, 4), index + (int)(ptr2 - ptr)))); } int num4 = ((num3 != 64) ? 3 : ((num2 == 64) ? 1 : 2)); num += num4; } return num; } } } [SecuritySafeCritical] public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); } if (charIndex < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (charIndex > chars.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length))); } if (charCount < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charCount", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (charCount > chars.Length - charIndex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charCount", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", chars.Length - charIndex))); } if (bytes == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bytes")); } if (byteIndex < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (byteIndex > bytes.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", bytes.Length))); } if (charCount == 0) { return 0; } if (charCount % 4 != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("Base64 sequence length ({0}) not valid. Must be a multiple of 4.", charCount.ToString(NumberFormatInfo.CurrentInfo)))); } fixed (byte* ptr7 = char2val) { fixed (char* ptr = &chars[charIndex]) { fixed (byte* ptr4 = &bytes[byteIndex]) { char* ptr2 = ptr; char* ptr3 = ptr + charCount; byte* ptr5 = ptr4; byte* ptr6 = ptr4 + bytes.Length - byteIndex; for (; ptr2 < ptr3; ptr2 += 4) { char c = *ptr2; char c2 = ptr2[1]; char c3 = ptr2[2]; char c4 = ptr2[3]; if ((c | c2 | c3 | c4) >= 128) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("The characters '{0}' at offset {1} are not a valid Base64 sequence.", new string(ptr2, 0, 4), charIndex + (int)(ptr2 - ptr)))); } int num = ptr7[(int)c]; int num2 = ptr7[(int)c2]; int num3 = ptr7[(int)c3]; int num4 = ptr7[(int)c4]; if (!IsValidLeadBytes(num, num2, num3, num4) || !IsValidTailBytes(num3, num4)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("The characters '{0}' at offset {1} are not a valid Base64 sequence.", new string(ptr2, 0, 4), charIndex + (int)(ptr2 - ptr)))); } int num5 = ((num4 != 64) ? 3 : ((num3 == 64) ? 1 : 2)); if (ptr5 + num5 > ptr6) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Array too small."), "bytes")); } *ptr5 = (byte)((uint)(num << 2) | ((uint)(num2 >> 4) & 3u)); if (num5 > 1) { ptr5[1] = (byte)((uint)(num2 << 4) | ((uint)(num3 >> 2) & 0xFu)); if (num5 > 2) { ptr5[2] = (byte)((uint)(num3 << 6) | ((uint)num4 & 0x3Fu)); } } ptr5 += num5; } return (int)(ptr5 - ptr4); } } } } [SecuritySafeCritical] public unsafe virtual int GetBytes(byte[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); } if (charIndex < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (charIndex > chars.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length))); } if (charCount < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charCount", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (charCount > chars.Length - charIndex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charCount", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", chars.Length - charIndex))); } if (bytes == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bytes")); } if (byteIndex < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (byteIndex > bytes.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", bytes.Length))); } if (charCount == 0) { return 0; } if (charCount % 4 != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("Base64 sequence length ({0}) not valid. Must be a multiple of 4.", charCount.ToString(NumberFormatInfo.CurrentInfo)))); } fixed (byte* ptr7 = char2val) { fixed (byte* ptr = &chars[charIndex]) { fixed (byte* ptr4 = &bytes[byteIndex]) { byte* ptr2 = ptr; byte* ptr3 = ptr + charCount; byte* ptr5 = ptr4; byte* ptr6 = ptr4 + bytes.Length - byteIndex; for (; ptr2 < ptr3; ptr2 += 4) { byte b = *ptr2; byte b2 = ptr2[1]; byte b3 = ptr2[2]; byte b4 = ptr2[3]; if ((b | b2 | b3 | b4) >= 128) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("The characters '{0}' at offset {1} are not a valid Base64 sequence.", new string((sbyte*)ptr2, 0, 4), charIndex + (int)(ptr2 - ptr)))); } int num = ptr7[(int)b]; int num2 = ptr7[(int)b2]; int num3 = ptr7[(int)b3]; int num4 = ptr7[(int)b4]; if (!IsValidLeadBytes(num, num2, num3, num4) || !IsValidTailBytes(num3, num4)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("The characters '{0}' at offset {1} are not a valid Base64 sequence.", new string((sbyte*)ptr2, 0, 4), charIndex + (int)(ptr2 - ptr)))); } int num5 = ((num4 != 64) ? 3 : ((num3 == 64) ? 1 : 2)); if (ptr5 + num5 > ptr6) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Array too small."), "bytes")); } *ptr5 = (byte)((uint)(num << 2) | ((uint)(num2 >> 4) & 3u)); if (num5 > 1) { ptr5[1] = (byte)((uint)(num2 << 4) | ((uint)(num3 >> 2) & 0xFu)); if (num5 > 2) { ptr5[2] = (byte)((uint)(num3 << 6) | ((uint)num4 & 0x3Fu)); } } ptr5 += num5; } return (int)(ptr5 - ptr4); } } } } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0 || byteCount > 1610612731) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteCount", System.Runtime.Serialization.SR.GetString("The value of this argument must fall within the range {0} to {1}.", 0, 1610612731))); } return (byteCount + 2) / 3 * 4; } public override int GetCharCount(byte[] bytes, int index, int count) { return GetMaxCharCount(count); } [SecuritySafeCritical] public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { if (bytes == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bytes")); } if (byteIndex < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (byteIndex > bytes.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", bytes.Length))); } if (byteCount < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteCount", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (byteCount > bytes.Length - byteIndex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteCount", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", bytes.Length - byteIndex))); } int charCount = GetCharCount(bytes, byteIndex, byteCount); if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); } if (charIndex < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (charIndex > chars.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length))); } if (charCount < 0 || charCount > chars.Length - charIndex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Array too small."), "chars")); } if (byteCount > 0) { fixed (char* ptr6 = val2char) { fixed (byte* ptr = &bytes[byteIndex]) { fixed (char* ptr4 = &chars[charIndex]) { byte* ptr2 = ptr; byte* ptr3 = ptr2 + byteCount - 3; char* ptr5 = ptr4; while (ptr2 <= ptr3) { *ptr5 = ptr6[*ptr2 >> 2]; ptr5[1] = ptr6[((*ptr2 & 3) << 4) | (ptr2[1] >> 4)]; ptr5[2] = ptr6[((ptr2[1] & 0xF) << 2) | (ptr2[2] >> 6)]; ptr5[3] = ptr6[ptr2[2] & 0x3F]; ptr2 += 3; ptr5 += 4; } if (ptr2 - ptr3 == 2) { *ptr5 = ptr6[*ptr2 >> 2]; ptr5[1] = ptr6[(*ptr2 & 3) << 4]; ptr5[2] = '='; ptr5[3] = '='; } else if (ptr2 - ptr3 == 1) { *ptr5 = ptr6[*ptr2 >> 2]; ptr5[1] = ptr6[((*ptr2 & 3) << 4) | (ptr2[1] >> 4)]; ptr5[2] = ptr6[(ptr2[1] & 0xF) << 2]; ptr5[3] = '='; } } } } } return charCount; } [SecuritySafeCritical] public unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, byte[] chars, int charIndex) { if (bytes == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bytes")); } if (byteIndex < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (byteIndex > bytes.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", bytes.Length))); } if (byteCount < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteCount", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (byteCount > bytes.Length - byteIndex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteCount", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", bytes.Length - byteIndex))); } int charCount = GetCharCount(bytes, byteIndex, byteCount); if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); } if (charIndex < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (charIndex > chars.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length))); } if (charCount < 0 || charCount > chars.Length - charIndex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Array too small."), "chars")); } if (byteCount > 0) { fixed (byte* ptr6 = val2byte) { fixed (byte* ptr = &bytes[byteIndex]) { fixed (byte* ptr4 = &chars[charIndex]) { byte* ptr2 = ptr; byte* ptr3 = ptr2 + byteCount - 3; byte* ptr5 = ptr4; while (ptr2 <= ptr3) { *ptr5 = ptr6[*ptr2 >> 2]; ptr5[1] = ptr6[((*ptr2 & 3) << 4) | (ptr2[1] >> 4)]; ptr5[2] = ptr6[((ptr2[1] & 0xF) << 2) | (ptr2[2] >> 6)]; ptr5[3] = ptr6[ptr2[2] & 0x3F]; ptr2 += 3; ptr5 += 4; } if (ptr2 - ptr3 == 2) { *ptr5 = ptr6[*ptr2 >> 2]; ptr5[1] = ptr6[(*ptr2 & 3) << 4]; ptr5[2] = 61; ptr5[3] = 61; } else if (ptr2 - ptr3 == 1) { *ptr5 = ptr6[*ptr2 >> 2]; ptr5[1] = ptr6[((*ptr2 & 3) << 4) | (ptr2[1] >> 4)]; ptr5[2] = ptr6[(ptr2[1] & 0xF) << 2]; ptr5[3] = 61; } } } } } return charCount; } } internal class BinHexEncoding : Encoding { private static byte[] char2val = new byte[128] { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; private static string val2char = "0123456789ABCDEF"; public override int GetMaxByteCount(int charCount) { if (charCount < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charCount", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (charCount % 2 != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("BinHex sequence length ({0}) not valid. Must be a multiple of 2.", charCount.ToString(NumberFormatInfo.CurrentInfo)))); } return charCount / 2; } public override int GetByteCount(char[] chars, int index, int count) { return GetMaxByteCount(count); } [SecuritySafeCritical] public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); } if (charIndex < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (charIndex > chars.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length))); } if (charCount < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charCount", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (charCount > chars.Length - charIndex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charCount", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", chars.Length - charIndex))); } if (bytes == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bytes")); } if (byteIndex < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (byteIndex > bytes.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", bytes.Length))); } int byteCount = GetByteCount(chars, charIndex, charCount); if (byteCount < 0 || byteCount > bytes.Length - byteIndex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Array too small."), "bytes")); } if (charCount > 0) { fixed (byte* ptr6 = char2val) { fixed (byte* ptr4 = &bytes[byteIndex]) { fixed (char* ptr = &chars[charIndex]) { char* ptr2 = ptr; char* ptr3 = ptr + charCount; byte* ptr5 = ptr4; while (ptr2 < ptr3) { char c = *ptr2; char c2 = ptr2[1]; if ((c | c2) >= 128) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("The characters '{0}' at offset {1} are not a valid BinHex sequence.", new string(ptr2, 0, 2), charIndex + (int)(ptr2 - ptr)))); } byte b = ptr6[(int)c]; byte b2 = ptr6[(int)c2]; if ((b | b2) == 255) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("The characters '{0}' at offset {1} are not a valid BinHex sequence.", new string(ptr2, 0, 2), charIndex + (int)(ptr2 - ptr)))); } *ptr5 = (byte)((b << 4) + b2); ptr2 += 2; ptr5++; } } } } } return byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0 || byteCount > 1073741823) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteCount", System.Runtime.Serialization.SR.GetString("The value of this argument must fall within the range {0} to {1}.", 0, 1073741823))); } return byteCount * 2; } public override int GetCharCount(byte[] bytes, int index, int count) { return GetMaxCharCount(count); } [SecuritySafeCritical] public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { if (bytes == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bytes")); } if (byteIndex < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (byteIndex > bytes.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteIndex", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", bytes.Length))); } if (byteCount < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteCount", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (byteCount > bytes.Length - byteIndex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("byteCount", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", bytes.Length - byteIndex))); } int charCount = GetCharCount(bytes, byteIndex, byteCount); if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); } if (charIndex < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative."))); } if (charIndex > chars.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("charIndex", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length))); } if (charCount < 0 || charCount > chars.Length - charIndex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Array too small."), "chars")); } if (byteCount > 0) { fixed (char* ptr6 = val2char) { fixed (byte* ptr3 = &bytes[byteIndex]) { fixed (char* ptr = &chars[charIndex]) { char* ptr2 = ptr; byte* ptr4 = ptr3; byte* ptr5 = ptr3 + byteCount; while (ptr4 < ptr5) { *ptr2 = ptr6[*ptr4 >> 4]; ptr2[1] = ptr6[*ptr4 & 0xF]; ptr4++; ptr2 += 2; } } } } } return charCount; } } internal struct SurrogateChar { private char lowChar; private char highChar; public const int MinValue = 65536; public const int MaxValue = 1114111; private const char surHighMin = '\ud800'; private const char surHighMax = '\udbff'; private const char surLowMin = '\udc00'; private const char surLowMax = '\udfff'; public char LowChar => lowChar; public char HighChar => highChar; public int Char => (lowChar - 56320) | ((highChar - 55296 << 10) + 65536); public SurrogateChar(int ch) { if (ch < 65536 || ch > 1114111) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Surrogate char '0x{0}' not valid. Surrogate chars range from 0x10000 to 0x10FFFF.", ch.ToString("X", CultureInfo.InvariantCulture)), "ch")); } lowChar = (char)(((ch - 65536) & 0x3FF) + 56320); highChar = (char)(((ch - 65536 >> 10) & 0x3FF) + 55296); } public SurrogateChar(char lowChar, char highChar) { if (lowChar < '\udc00' || lowChar > '\udfff') { object[] array = new object[1]; int num = lowChar; array[0] = num.ToString("X", CultureInfo.InvariantCulture); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Low surrogate char '0x{0}' not valid. Low surrogate chars range from 0xDC00 to 0xDFFF.", array), "lowChar")); } if (highChar < '\ud800' || highChar > '\udbff') { object[] array2 = new object[1]; int num = highChar; array2[0] = num.ToString("X", CultureInfo.InvariantCulture); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("High surrogate char '0x{0}' not valid. High surrogate chars range from 0xD800 to 0xDBFF.", array2), "highChar")); } this.lowChar = lowChar; this.highChar = highChar; } } } namespace System.Runtime.CompilerServices { internal class FriendAccessAllowedAttribute : Attribute { } } namespace System.Runtime.Serialization { public interface ISerializationSurrogateProvider { Type GetSurrogateType(Type type); object GetObjectToSerialize(object obj, Type targetType); object GetDeserializedObject(object obj, Type targetType); } internal static class AppSettings { internal const string MaxMimePartsAppSettingsString = "microsoft:xmldictionaryreader:maxmimeparts"; private const int DefaultMaxMimeParts = 1000; private static int maxMimeParts; private static volatile bool settingsInitalized = false; private static object appSettingsLock = new object(); internal static int MaxMimeParts { get { EnsureSettingsLoaded(); return maxMimeParts; } } private static void EnsureSettingsLoaded() { if (settingsInitalized) { return; } lock (appSettingsLock) { if (!settingsInitalized) { NameValueCollection nameValueCollection = null; if (nameValueCollection == null || !int.TryParse(nameValueCollection["microsoft:xmldictionaryreader:maxmimeparts"], out maxMimeParts)) { maxMimeParts = 1000; } settingsInitalized = true; } } } } internal class Attributes { [SecurityCritical] private static XmlDictionaryString[] serializationLocalNames; [SecurityCritical] private static XmlDictionaryString[] schemaInstanceLocalNames; internal string Id; internal string Ref; internal string XsiTypeName; internal string XsiTypeNamespace; internal string XsiTypePrefix; internal bool XsiNil; internal string ClrAssembly; internal string ClrType; internal int ArraySZSize; internal string FactoryTypeName; internal string FactoryTypeNamespace; internal string FactoryTypePrefix; internal bool UnrecognizedAttributesFound; [SecuritySafeCritical] static Attributes() { serializationLocalNames = new XmlDictionaryString[6] { DictionaryGlobals.IdLocalName, DictionaryGlobals.ArraySizeLocalName, DictionaryGlobals.RefLocalName, DictionaryGlobals.ClrTypeLocalName, DictionaryGlobals.ClrAssemblyLocalName, DictionaryGlobals.ISerializableFactoryTypeLocalName }; schemaInstanceLocalNames = new XmlDictionaryString[2] { DictionaryGlobals.XsiNilLocalName, DictionaryGlobals.XsiTypeLocalName }; } [SecuritySafeCritical] internal void Read(XmlReaderDelegator reader) { Reset(); while (reader.MoveToNextAttribute()) { switch (reader.IndexOfLocalName(serializationLocalNames, DictionaryGlobals.SerializationNamespace)) { case 0: ReadId(reader); continue; case 1: ReadArraySize(reader); continue; case 2: ReadRef(reader); continue; case 3: ClrType = reader.Value; continue; case 4: ClrAssembly = reader.Value; continue; case 5: ReadFactoryType(reader); continue; } switch (reader.IndexOfLocalName(schemaInstanceLocalNames, DictionaryGlobals.SchemaInstanceNamespace)) { case 0: ReadXsiNil(reader); continue; case 1: ReadXsiType(reader); continue; } if (!reader.IsNamespaceUri(DictionaryGlobals.XmlnsNamespace)) { UnrecognizedAttributesFound = true; } } reader.MoveToElement(); } internal void Reset() { Id = Globals.NewObjectId; Ref = Globals.NewObjectId; XsiTypeName = null; XsiTypeNamespace = null; XsiTypePrefix = null; XsiNil = false; ClrAssembly = null; ClrType = null; ArraySZSize = -1; FactoryTypeName = null; FactoryTypeNamespace = null; FactoryTypePrefix = null; UnrecognizedAttributesFound = false; } private void ReadId(XmlReaderDelegator reader) { Id = reader.ReadContentAsString(); if (string.IsNullOrEmpty(Id)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Invalid Id '{0}'. Must not be null or empty.", Id))); } } private void ReadRef(XmlReaderDelegator reader) { Ref = reader.ReadContentAsString(); if (string.IsNullOrEmpty(Ref)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Invalid Ref '{0}'. Must not be null or empty.", Ref))); } } private void ReadXsiNil(XmlReaderDelegator reader) { XsiNil = reader.ReadContentAsBoolean(); } private void ReadArraySize(XmlReaderDelegator reader) { ArraySZSize = reader.ReadContentAsInt(); if (ArraySZSize < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Invalid Size '{0}'. Must be non-negative integer.", ArraySZSize))); } } private void ReadXsiType(XmlReaderDelegator reader) { string value = reader.Value; if (value != null && value.Length > 0) { XmlObjectSerializerReadContext.ParseQualifiedName(value, reader, out XsiTypeName, out XsiTypeNamespace, out XsiTypePrefix); } } private void ReadFactoryType(XmlReaderDelegator reader) { string value = reader.Value; if (value != null && value.Length > 0) { XmlObjectSerializerReadContext.ParseQualifiedName(value, reader, out FactoryTypeName, out FactoryTypeNamespace, out FactoryTypePrefix); } } } internal sealed class ClassDataContract : DataContract { private class ClassDataContractCriticalHelper : DataContractCriticalHelper { internal struct Member { internal DataMember member; internal string ns; internal int baseTypeIndex; internal Member(DataMember member, string ns, int baseTypeIndex) { this.member = member; this.ns = ns; this.baseTypeIndex = baseTypeIndex; } } internal class DataMemberConflictComparer : IComparer { internal static DataMemberConflictComparer Singleton = new DataMemberConflictComparer(); public int Compare(Member x, Member y) { int num = string.CompareOrdinal(x.ns, y.ns); if (num != 0) { return num; } int num2 = string.CompareOrdinal(x.member.Name, y.member.Name); if (num2 != 0) { return num2; } return x.baseTypeIndex - y.baseTypeIndex; } } private ClassDataContract baseContract; private List members; private MethodInfo onSerializing; private MethodInfo onSerialized; private MethodInfo onDeserializing; private MethodInfo onDeserialized; private MethodInfo extensionDataSetMethod; private Dictionary knownDataContracts; private string serializationExceptionMessage; private bool isISerializable; private bool isKnownTypeAttributeChecked; private bool isMethodChecked; private bool hasExtensionData; private bool isNonAttributedType; private bool hasDataContract; private XmlDictionaryString[] childElementNamespaces; private XmlFormatClassReaderDelegate xmlFormatReaderDelegate; private XmlFormatClassWriterDelegate xmlFormatWriterDelegate; public XmlDictionaryString[] ContractNamespaces; public XmlDictionaryString[] MemberNames; public XmlDictionaryString[] MemberNamespaces; private static Type[] serInfoCtorArgs; internal ClassDataContract BaseContract { get { return baseContract; } set { baseContract = value; if (baseContract != null && base.IsValueType) { ThrowInvalidDataContractException(SR.GetString("Data contract '{0}' from namespace '{1}' is a value type and cannot have base contract '{2}' from namespace '{3}'.", base.StableName.Name, base.StableName.Namespace, baseContract.StableName.Name, baseContract.StableName.Namespace)); } } } internal List Members { get { return members; } set { members = value; } } internal MethodInfo OnSerializing { get { EnsureMethodsImported(); return onSerializing; } } internal MethodInfo OnSerialized { get { EnsureMethodsImported(); return onSerialized; } } internal MethodInfo OnDeserializing { get { EnsureMethodsImported(); return onDeserializing; } } internal MethodInfo OnDeserialized { get { EnsureMethodsImported(); return onDeserialized; } } internal MethodInfo ExtensionDataSetMethod { get { EnsureMethodsImported(); return extensionDataSetMethod; } } internal override Dictionary KnownDataContracts { get { if (!isKnownTypeAttributeChecked && base.UnderlyingType != null) { lock (this) { if (!isKnownTypeAttributeChecked) { knownDataContracts = DataContract.ImportKnownTypeAttributes(base.UnderlyingType); Thread.MemoryBarrier(); isKnownTypeAttributeChecked = true; } } } return knownDataContracts; } set { knownDataContracts = value; } } internal string SerializationExceptionMessage => serializationExceptionMessage; internal string DeserializationExceptionMessage { get { if (serializationExceptionMessage == null) { return null; } return SR.GetString("Error on deserializing read-only members in the class: {0}", serializationExceptionMessage); } } internal override bool IsISerializable { get { return isISerializable; } set { isISerializable = value; } } internal bool HasDataContract => hasDataContract; internal bool HasExtensionData => hasExtensionData; internal bool IsNonAttributedType => isNonAttributedType; internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate { get { return xmlFormatWriterDelegate; } set { xmlFormatWriterDelegate = value; } } internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate { get { return xmlFormatReaderDelegate; } set { xmlFormatReaderDelegate = value; } } public XmlDictionaryString[] ChildElementNamespaces { get { return childElementNamespaces; } set { childElementNamespaces = value; } } private static Type[] SerInfoCtorArgs { get { if (serInfoCtorArgs == null) { serInfoCtorArgs = new Type[2] { typeof(SerializationInfo), typeof(StreamingContext) }; } return serInfoCtorArgs; } } internal ClassDataContractCriticalHelper() { } internal ClassDataContractCriticalHelper(Type type) : base(type) { XmlQualifiedName stableNameAndSetHasDataContract = GetStableNameAndSetHasDataContract(type); if (type == Globals.TypeOfDBNull) { base.StableName = stableNameAndSetHasDataContract; members = new List(); XmlDictionary xmlDictionary = new XmlDictionary(2); base.Name = xmlDictionary.Add(base.StableName.Name); base.Namespace = xmlDictionary.Add(base.StableName.Namespace); ContractNamespaces = (MemberNames = (MemberNamespaces = new XmlDictionaryString[0])); EnsureMethodsImported(); return; } Type type2 = type.BaseType; isISerializable = Globals.TypeOfISerializable.IsAssignableFrom(type); SetIsNonAttributedType(type); if (isISerializable) { if (HasDataContract) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("ISerializable type '{0}' cannot have DataContract.", DataContract.GetClrTypeFullName(type)))); } if (type2 != null && (!type2.IsSerializable || !Globals.TypeOfISerializable.IsAssignableFrom(type2))) { type2 = null; } } base.IsValueType = type.IsValueType; if (type2 != null && type2 != Globals.TypeOfObject && type2 != Globals.TypeOfValueType && type2 != Globals.TypeOfUri) { DataContract dataContract = DataContract.GetDataContract(type2); if (dataContract is CollectionDataContract) { BaseContract = ((CollectionDataContract)dataContract).SharedTypeContract as ClassDataContract; } else { BaseContract = dataContract as ClassDataContract; } if (BaseContract != null && BaseContract.IsNonAttributedType && !isNonAttributedType) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Type '{0}' cannot inherit from a type that is not marked with DataContractAttribute or SerializableAttribute. Consider marking the base type '{1}' with DataContractAttribute or SerializableAttribute, or removing them from the derived type.", DataContract.GetClrTypeFullName(type), DataContract.GetClrTypeFullName(type2)))); } } else { BaseContract = null; } hasExtensionData = Globals.TypeOfIExtensibleDataObject.IsAssignableFrom(type); if (hasExtensionData && !HasDataContract && !IsNonAttributedType) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("On '{0}' type, only DataContract types can have extension data.", DataContract.GetClrTypeFullName(type)))); } if (isISerializable) { SetDataContractName(stableNameAndSetHasDataContract); } else { base.StableName = stableNameAndSetHasDataContract; ImportDataMembers(); XmlDictionary xmlDictionary2 = new XmlDictionary(2 + Members.Count); base.Name = xmlDictionary2.Add(base.StableName.Name); base.Namespace = xmlDictionary2.Add(base.StableName.Namespace); int num = 0; int num2 = 0; if (BaseContract == null) { MemberNames = new XmlDictionaryString[Members.Count]; MemberNamespaces = new XmlDictionaryString[Members.Count]; ContractNamespaces = new XmlDictionaryString[1]; } else { if (BaseContract.IsReadOnlyContract) { serializationExceptionMessage = BaseContract.SerializationExceptionMessage; } num = BaseContract.MemberNames.Length; MemberNames = new XmlDictionaryString[Members.Count + num]; Array.Copy(BaseContract.MemberNames, MemberNames, num); MemberNamespaces = new XmlDictionaryString[Members.Count + num]; Array.Copy(BaseContract.MemberNamespaces, MemberNamespaces, num); num2 = BaseContract.ContractNamespaces.Length; ContractNamespaces = new XmlDictionaryString[1 + num2]; Array.Copy(BaseContract.ContractNamespaces, ContractNamespaces, num2); } ContractNamespaces[num2] = base.Namespace; for (int i = 0; i < Members.Count; i++) { MemberNames[i + num] = xmlDictionary2.Add(Members[i].Name); MemberNamespaces[i + num] = base.Namespace; } } EnsureMethodsImported(); } internal ClassDataContractCriticalHelper(Type type, XmlDictionaryString ns, string[] memberNames) : base(type) { base.StableName = new XmlQualifiedName(GetStableNameAndSetHasDataContract(type).Name, ns.Value); ImportDataMembers(); XmlDictionary xmlDictionary = new XmlDictionary(1 + Members.Count); base.Name = xmlDictionary.Add(base.StableName.Name); base.Namespace = ns; ContractNamespaces = new XmlDictionaryString[1] { base.Namespace }; MemberNames = new XmlDictionaryString[Members.Count]; MemberNamespaces = new XmlDictionaryString[Members.Count]; for (int i = 0; i < Members.Count; i++) { Members[i].Name = memberNames[i]; MemberNames[i] = xmlDictionary.Add(Members[i].Name); MemberNamespaces[i] = base.Namespace; } EnsureMethodsImported(); } private void EnsureIsReferenceImported(Type type) { bool flag = false; DataContractAttribute dataContractAttribute; bool flag2 = DataContract.TryGetDCAttribute(type, out dataContractAttribute); if (BaseContract != null) { if (flag2 && dataContractAttribute.IsReferenceSetExplicitly) { bool flag3 = BaseContract.IsReference; if ((flag3 && !dataContractAttribute.IsReference) || (!flag3 && dataContractAttribute.IsReference)) { DataContract.ThrowInvalidDataContractException(SR.GetString("The IsReference setting for type '{0}' is '{1}', but the same setting for its parent class '{2}' is '{3}'. Derived types must have the same value for IsReference as the base type. Change the setting on type '{0}' to '{3}', or on type '{2}' to '{1}', or do not set IsReference explicitly.", DataContract.GetClrTypeFullName(type), dataContractAttribute.IsReference, DataContract.GetClrTypeFullName(BaseContract.UnderlyingType), BaseContract.IsReference), type); } else { flag = dataContractAttribute.IsReference; } } else { flag = BaseContract.IsReference; } } else if (flag2 && dataContractAttribute.IsReference) { flag = dataContractAttribute.IsReference; } if (flag && type.IsValueType) { DataContract.ThrowInvalidDataContractException(SR.GetString("Value type '{0}' cannot have the IsReference setting of '{1}'. Either change the setting to '{2}', or remove it completely.", DataContract.GetClrTypeFullName(type), true, false), type); } else { base.IsReference = flag; } } private void ImportDataMembers() { Type type = base.UnderlyingType; EnsureIsReferenceImported(type); List list = new List(); Dictionary memberNamesTable = new Dictionary(); MemberInfo[] array = ((!isNonAttributedType) ? type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) : type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)); foreach (MemberInfo memberInfo in array) { if (HasDataContract) { object[] customAttributes = memberInfo.GetCustomAttributes(typeof(DataMemberAttribute), inherit: false); if (customAttributes == null || customAttributes.Length == 0) { continue; } if (customAttributes.Length > 1) { ThrowInvalidDataContractException(SR.GetString("Member '{0}.{1}' has more than one DataMemberAttribute attribute.", DataContract.GetClrTypeFullName(memberInfo.DeclaringType), memberInfo.Name)); } DataMember dataMember = new DataMember(memberInfo); if (memberInfo.MemberType == MemberTypes.Property) { PropertyInfo propertyInfo = (PropertyInfo)memberInfo; MethodInfo getMethod = propertyInfo.GetGetMethod(nonPublic: true); if (getMethod != null && IsMethodOverriding(getMethod)) { continue; } MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true); if (setMethod != null && IsMethodOverriding(setMethod)) { continue; } if (getMethod == null) { ThrowInvalidDataContractException(SR.GetString("No get method for property '{1}' in type '{0}'.", propertyInfo.DeclaringType, propertyInfo.Name)); } if (setMethod == null && !SetIfGetOnlyCollection(dataMember, skipIfReadOnlyContract: false)) { serializationExceptionMessage = SR.GetString("No set method for property '{1}' in type '{0}'.", propertyInfo.DeclaringType, propertyInfo.Name); } if (getMethod.GetParameters().Length != 0) { ThrowInvalidDataContractException(SR.GetString("Property '{1}' in type '{0}' cannot be serialized because serialization of indexed properties is not supported.", propertyInfo.DeclaringType, propertyInfo.Name)); } } else if (memberInfo.MemberType != MemberTypes.Field) { ThrowInvalidDataContractException(SR.GetString("Member '{0}.{1}' cannot be serialized since it is neither a field nor a property, and therefore cannot be marked with the DataMemberAttribute attribute. Remove the DataMemberAttribute attribute from the '{1}' member.", DataContract.GetClrTypeFullName(type), memberInfo.Name)); } DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)customAttributes[0]; if (dataMemberAttribute.IsNameSetExplicitly) { if (dataMemberAttribute.Name == null || dataMemberAttribute.Name.Length == 0) { ThrowInvalidDataContractException(SR.GetString("Member '{0}' in type '{1}' cannot have DataMemberAttribute attribute Name set to null or empty string.", memberInfo.Name, DataContract.GetClrTypeFullName(type))); } dataMember.Name = dataMemberAttribute.Name; } else { dataMember.Name = memberInfo.Name; } dataMember.Name = DataContract.EncodeLocalName(dataMember.Name); dataMember.IsNullable = DataContract.IsTypeNullable(dataMember.MemberType); dataMember.IsRequired = dataMemberAttribute.IsRequired; if (dataMemberAttribute.IsRequired && base.IsReference) { DataContractCriticalHelper.ThrowInvalidDataContractException(SR.GetString("'{0}.{1}' has the IsRequired setting of '{2}. However, '{0}' has the IsReference setting of '{2}', because either it is set explicitly, or it is derived from a base class. Set IsRequired on '{0}.{1}' to false, or disable IsReference on '{0}'.", DataContract.GetClrTypeFullName(memberInfo.DeclaringType), memberInfo.Name, true), type); } dataMember.EmitDefaultValue = dataMemberAttribute.EmitDefaultValue; dataMember.Order = dataMemberAttribute.Order; CheckAndAddMember(list, dataMember, memberNamesTable); continue; } if (isNonAttributedType) { FieldInfo fieldInfo = memberInfo as FieldInfo; PropertyInfo propertyInfo2 = memberInfo as PropertyInfo; if ((fieldInfo == null && propertyInfo2 == null) || (fieldInfo != null && fieldInfo.IsInitOnly)) { continue; } object[] customAttributes2 = memberInfo.GetCustomAttributes(typeof(IgnoreDataMemberAttribute), inherit: false); if (customAttributes2 != null && customAttributes2.Length != 0) { if (customAttributes2.Length <= 1) { continue; } ThrowInvalidDataContractException(SR.GetString("Member '{0}.{1}' has more than one IgnoreDataMemberAttribute attribute.", DataContract.GetClrTypeFullName(memberInfo.DeclaringType), memberInfo.Name)); } DataMember dataMember2 = new DataMember(memberInfo); if (propertyInfo2 != null) { MethodInfo getMethod2 = propertyInfo2.GetGetMethod(); if (getMethod2 == null || IsMethodOverriding(getMethod2) || getMethod2.GetParameters().Length != 0) { continue; } MethodInfo setMethod2 = propertyInfo2.GetSetMethod(nonPublic: true); if (setMethod2 == null) { if (!SetIfGetOnlyCollection(dataMember2, skipIfReadOnlyContract: true)) { continue; } } else if (!setMethod2.IsPublic || IsMethodOverriding(setMethod2)) { continue; } if (hasExtensionData && dataMember2.MemberType == Globals.TypeOfExtensionDataObject && memberInfo.Name == "ExtensionData") { continue; } } dataMember2.Name = DataContract.EncodeLocalName(memberInfo.Name); dataMember2.IsNullable = DataContract.IsTypeNullable(dataMember2.MemberType); CheckAndAddMember(list, dataMember2, memberNamesTable); continue; } FieldInfo fieldInfo2 = memberInfo as FieldInfo; if (!(fieldInfo2 != null) || fieldInfo2.IsNotSerialized) { continue; } DataMember dataMember3 = new DataMember(memberInfo); dataMember3.Name = DataContract.EncodeLocalName(memberInfo.Name); object[] customAttributes3 = fieldInfo2.GetCustomAttributes(Globals.TypeOfOptionalFieldAttribute, inherit: false); if (customAttributes3 == null || customAttributes3.Length == 0) { if (base.IsReference) { DataContractCriticalHelper.ThrowInvalidDataContractException(SR.GetString("For type '{0}', non-optional field member '{1}' is on the Serializable type that has IsReference as {2}.", DataContract.GetClrTypeFullName(memberInfo.DeclaringType), memberInfo.Name, true), type); } dataMember3.IsRequired = true; } dataMember3.IsNullable = DataContract.IsTypeNullable(dataMember3.MemberType); CheckAndAddMember(list, dataMember3, memberNamesTable); } if (list.Count > 1) { list.Sort(DataMemberComparer.Singleton); } SetIfMembersHaveConflict(list); Thread.MemoryBarrier(); members = list; } private bool SetIfGetOnlyCollection(DataMember memberContract, bool skipIfReadOnlyContract) { if (CollectionDataContract.IsCollection(memberContract.MemberType, constructorRequired: false, skipIfReadOnlyContract) && !memberContract.MemberType.IsValueType) { memberContract.IsGetOnlyCollection = true; return true; } return false; } private void SetIfMembersHaveConflict(List members) { if (BaseContract == null) { return; } int num = 0; List list = new List(); foreach (DataMember member in members) { list.Add(new Member(member, base.StableName.Namespace, num)); } for (ClassDataContract classDataContract = BaseContract; classDataContract != null; classDataContract = classDataContract.BaseContract) { num++; foreach (DataMember member2 in classDataContract.Members) { list.Add(new Member(member2, classDataContract.StableName.Namespace, num)); } } IComparer singleton = DataMemberConflictComparer.Singleton; list.Sort(singleton); int num2; for (num2 = 0; num2 < list.Count - 1; num2++) { int num3 = num2; int i = num2; bool flag = false; for (; i < list.Count - 1 && string.CompareOrdinal(list[i].member.Name, list[i + 1].member.Name) == 0 && string.CompareOrdinal(list[i].ns, list[i + 1].ns) == 0; i++) { list[i].member.ConflictingMember = list[i + 1].member; if (!flag) { flag = list[i + 1].member.HasConflictingNameAndType || list[i].member.MemberType != list[i + 1].member.MemberType; } } if (flag) { for (int j = num3; j <= i; j++) { list[j].member.HasConflictingNameAndType = true; } } num2 = i + 1; } } [SecuritySafeCritical] private XmlQualifiedName GetStableNameAndSetHasDataContract(Type type) { return DataContract.GetStableName(type, out hasDataContract); } private void SetIsNonAttributedType(Type type) { isNonAttributedType = !type.IsSerializable && !hasDataContract && IsNonAttributedTypeValidForSerialization(type); } private static bool IsMethodOverriding(MethodInfo method) { if (method.IsVirtual) { return (method.Attributes & MethodAttributes.VtableLayoutMask) == 0; } return false; } internal void EnsureMethodsImported() { if (isMethodChecked || !(base.UnderlyingType != null)) { return; } lock (this) { if (isMethodChecked) { return; } MethodInfo[] methods = base.UnderlyingType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { Type prevAttributeType = null; ParameterInfo[] parameters = methodInfo.GetParameters(); if (HasExtensionData && IsValidExtensionDataSetMethod(methodInfo, parameters)) { if (methodInfo.Name == "System.Runtime.Serialization.IExtensibleDataObject.set_ExtensionData" || !methodInfo.IsPublic) { extensionDataSetMethod = XmlFormatGeneratorStatics.ExtensionDataSetExplicitMethodInfo; } else { extensionDataSetMethod = methodInfo; } } if (IsValidCallback(methodInfo, parameters, Globals.TypeOfOnSerializingAttribute, onSerializing, ref prevAttributeType)) { onSerializing = methodInfo; } if (IsValidCallback(methodInfo, parameters, Globals.TypeOfOnSerializedAttribute, onSerialized, ref prevAttributeType)) { onSerialized = methodInfo; } if (IsValidCallback(methodInfo, parameters, Globals.TypeOfOnDeserializingAttribute, onDeserializing, ref prevAttributeType)) { onDeserializing = methodInfo; } if (IsValidCallback(methodInfo, parameters, Globals.TypeOfOnDeserializedAttribute, onDeserialized, ref prevAttributeType)) { onDeserialized = methodInfo; } } Thread.MemoryBarrier(); isMethodChecked = true; } } private bool IsValidExtensionDataSetMethod(MethodInfo method, ParameterInfo[] parameters) { if (method.Name == "System.Runtime.Serialization.IExtensibleDataObject.set_ExtensionData" || method.Name == "set_ExtensionData") { if (extensionDataSetMethod != null) { ThrowInvalidDataContractException(SR.GetString("Duplicate extension data set method was found, for method '{0}', existing method is '{1}', on data contract type '{2}'.", method, extensionDataSetMethod, DataContract.GetClrTypeFullName(method.DeclaringType))); } if (method.ReturnType != Globals.TypeOfVoid) { DataContract.ThrowInvalidDataContractException(SR.GetString("For type '{0}' method '{1}', extension data set method must return void.", DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); } if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfExtensionDataObject) { DataContract.ThrowInvalidDataContractException(SR.GetString("For type '{0}' method '{1}', extension data set method has invalid type of parameter '{2}'.", DataContract.GetClrTypeFullName(method.DeclaringType), method, Globals.TypeOfExtensionDataObject), method.DeclaringType); } return true; } return false; } private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType) { if (method.IsDefined(attributeType, inherit: false)) { if (currentCallback != null) { DataContract.ThrowInvalidDataContractException(SR.GetString("Invalid attribute. Both '{0}' and '{1}' in type '{2}' have '{3}'.", method, currentCallback, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType); } else if (prevAttributeType != null) { DataContract.ThrowInvalidDataContractException(SR.GetString("Invalid Callback. Method '{3}' in type '{2}' has both '{0}' and '{1}'.", prevAttributeType, attributeType, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); } else if (method.IsVirtual) { DataContract.ThrowInvalidDataContractException(SR.GetString("Virtual Method '{0}' of type '{1}' cannot be marked with '{2}' attribute.", method, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType); } else { if (method.ReturnType != Globals.TypeOfVoid) { DataContract.ThrowInvalidDataContractException(SR.GetString("Serialization Callback '{1}' in type '{0}' must return void.", DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); } if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfStreamingContext) { DataContract.ThrowInvalidDataContractException(SR.GetString("Serialization Callback '{1}' in type '{0}' must have a single parameter of type '{2}'.", DataContract.GetClrTypeFullName(method.DeclaringType), method, Globals.TypeOfStreamingContext), method.DeclaringType); } prevAttributeType = attributeType; } return true; } return false; } internal ConstructorInfo GetISerializableConstructor() { if (!IsISerializable) { return null; } ConstructorInfo constructor = base.UnderlyingType.GetConstructor(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, SerInfoCtorArgs, null); if (constructor == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Constructor that takes SerializationInfo and StreamingContext is not found for '{0}'.", DataContract.GetClrTypeFullName(base.UnderlyingType)))); } return constructor; } internal ConstructorInfo GetNonAttributedTypeConstructor() { if (!IsNonAttributedType) { return null; } Type type = base.UnderlyingType; if (type.IsValueType) { return null; } ConstructorInfo constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Globals.EmptyTypeArray, null); if (constructor == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("The Type '{0}' must have a parameterless constructor.", DataContract.GetClrTypeFullName(type)))); } return constructor; } } internal class DataMemberComparer : IComparer { internal static DataMemberComparer Singleton = new DataMemberComparer(); public int Compare(DataMember x, DataMember y) { int num = x.Order - y.Order; if (num != 0) { return num; } return string.CompareOrdinal(x.Name, y.Name); } } public XmlDictionaryString[] ContractNamespaces; public XmlDictionaryString[] MemberNames; public XmlDictionaryString[] MemberNamespaces; private XmlDictionaryString[] childElementNamespaces; private ClassDataContractCriticalHelper helper; internal ClassDataContract BaseContract { [SecuritySafeCritical] get { return helper.BaseContract; } [SecurityCritical] set { helper.BaseContract = value; } } internal List Members { [SecuritySafeCritical] get { return helper.Members; } [SecurityCritical] set { helper.Members = value; } } public XmlDictionaryString[] ChildElementNamespaces { [SecuritySafeCritical] get { if (childElementNamespaces == null) { lock (this) { if (childElementNamespaces == null) { if (helper.ChildElementNamespaces == null) { XmlDictionaryString[] array = CreateChildElementNamespaces(); Thread.MemoryBarrier(); helper.ChildElementNamespaces = array; } childElementNamespaces = helper.ChildElementNamespaces; } } } return childElementNamespaces; } } internal MethodInfo OnSerializing { [SecuritySafeCritical] get { return helper.OnSerializing; } } internal MethodInfo OnSerialized { [SecuritySafeCritical] get { return helper.OnSerialized; } } internal MethodInfo OnDeserializing { [SecuritySafeCritical] get { return helper.OnDeserializing; } } internal MethodInfo OnDeserialized { [SecuritySafeCritical] get { return helper.OnDeserialized; } } internal MethodInfo ExtensionDataSetMethod { [SecuritySafeCritical] get { return helper.ExtensionDataSetMethod; } } internal override Dictionary KnownDataContracts { [SecuritySafeCritical] get { return helper.KnownDataContracts; } [SecurityCritical] set { helper.KnownDataContracts = value; } } internal override bool IsISerializable { [SecuritySafeCritical] get { return helper.IsISerializable; } [SecurityCritical] set { helper.IsISerializable = value; } } internal bool IsNonAttributedType { [SecuritySafeCritical] get { return helper.IsNonAttributedType; } } internal bool HasDataContract { [SecuritySafeCritical] get { return helper.HasDataContract; } } internal bool HasExtensionData { [SecuritySafeCritical] get { return helper.HasExtensionData; } } internal string SerializationExceptionMessage { [SecuritySafeCritical] get { return helper.SerializationExceptionMessage; } } internal string DeserializationExceptionMessage { [SecuritySafeCritical] get { return helper.DeserializationExceptionMessage; } } internal bool IsReadOnlyContract => DeserializationExceptionMessage != null; internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate { [SecuritySafeCritical] get { if (helper.XmlFormatWriterDelegate == null) { lock (this) { if (helper.XmlFormatWriterDelegate == null) { XmlFormatClassWriterDelegate xmlFormatWriterDelegate = new XmlFormatWriterGenerator().GenerateClassWriter(this); Thread.MemoryBarrier(); helper.XmlFormatWriterDelegate = xmlFormatWriterDelegate; } } } return helper.XmlFormatWriterDelegate; } } internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate { [SecuritySafeCritical] get { if (helper.XmlFormatReaderDelegate == null) { lock (this) { if (helper.XmlFormatReaderDelegate == null) { if (IsReadOnlyContract) { DataContract.ThrowInvalidDataContractException(helper.DeserializationExceptionMessage, null); } XmlFormatClassReaderDelegate xmlFormatReaderDelegate = new XmlFormatReaderGenerator().GenerateClassReader(this); Thread.MemoryBarrier(); helper.XmlFormatReaderDelegate = xmlFormatReaderDelegate; } } } return helper.XmlFormatReaderDelegate; } } [SecuritySafeCritical] internal ClassDataContract() : base(new ClassDataContractCriticalHelper()) { InitClassDataContract(); } internal ClassDataContract(Type type) : base(new ClassDataContractCriticalHelper(type)) { InitClassDataContract(); } private ClassDataContract(Type type, XmlDictionaryString ns, string[] memberNames) : base(new ClassDataContractCriticalHelper(type, ns, memberNames)) { InitClassDataContract(); } private void InitClassDataContract() { helper = base.Helper as ClassDataContractCriticalHelper; ContractNamespaces = helper.ContractNamespaces; MemberNames = helper.MemberNames; MemberNamespaces = helper.MemberNamespaces; } [SecuritySafeCritical] internal ConstructorInfo GetISerializableConstructor() { return helper.GetISerializableConstructor(); } [SecuritySafeCritical] internal ConstructorInfo GetNonAttributedTypeConstructor() { return helper.GetNonAttributedTypeConstructor(); } internal static ClassDataContract CreateClassDataContractForKeyValue(Type type, XmlDictionaryString ns, string[] memberNames) { return new ClassDataContract(type, ns, memberNames); } internal static void CheckAndAddMember(List members, DataMember memberContract, Dictionary memberNamesTable) { if (memberNamesTable.TryGetValue(memberContract.Name, out var value)) { Type declaringType = memberContract.MemberInfo.DeclaringType; DataContract.ThrowInvalidDataContractException(SR.GetString(declaringType.IsEnum ? "Type '{2}' contains two members '{0}' 'and '{1}' with the same name '{3}'. Multiple members with the same name in one type are not supported. Consider changing one of the member names using EnumMemberAttribute attribute." : "Type '{2}' contains two members '{0}' 'and '{1}' with the same data member name '{3}'. Multiple members with the same name in one type are not supported. Consider changing one of the member names using DataMemberAttribute attribute.", value.MemberInfo.Name, memberContract.MemberInfo.Name, DataContract.GetClrTypeFullName(declaringType), memberContract.Name), declaringType); } memberNamesTable.Add(memberContract.Name, memberContract); members.Add(memberContract); } internal static XmlDictionaryString GetChildNamespaceToDeclare(DataContract dataContract, Type childType, XmlDictionary dictionary) { childType = DataContract.UnwrapNullableType(childType); if (!childType.IsEnum && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(childType) && DataContract.GetBuiltInDataContract(childType) == null && childType != Globals.TypeOfDBNull) { string @namespace = DataContract.GetStableName(childType).Namespace; if (@namespace.Length > 0 && @namespace != dataContract.Namespace.Value) { return dictionary.Add(@namespace); } } return null; } internal static bool IsNonAttributedTypeValidForSerialization(Type type) { if (type.IsArray) { return false; } if (type.IsEnum) { return false; } if (type.IsGenericParameter) { return false; } if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) { return false; } if (type.IsPointer) { return false; } if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, inherit: false)) { return false; } Type[] interfaces = type.GetInterfaces(); for (int i = 0; i < interfaces.Length; i++) { if (CollectionDataContract.IsCollectionInterface(interfaces[i])) { return false; } } if (type.IsSerializable) { return false; } if (Globals.TypeOfISerializable.IsAssignableFrom(type)) { return false; } if (type.IsDefined(Globals.TypeOfDataContractAttribute, inherit: false)) { return false; } if (type == Globals.TypeOfExtensionDataObject) { return false; } if (type.IsValueType) { return type.IsVisible; } if (type.IsVisible) { return type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Globals.EmptyTypeArray, null) != null; } return false; } private XmlDictionaryString[] CreateChildElementNamespaces() { if (Members == null) { return null; } XmlDictionaryString[] array = null; if (BaseContract != null) { array = BaseContract.ChildElementNamespaces; } int num = ((array != null) ? array.Length : 0); XmlDictionaryString[] array2 = new XmlDictionaryString[Members.Count + num]; if (num > 0) { Array.Copy(array, 0, array2, 0, array.Length); } XmlDictionary dictionary = new XmlDictionary(); for (int i = 0; i < Members.Count; i++) { array2[i + num] = GetChildNamespaceToDeclare(this, Members[i].MemberType, dictionary); } return array2; } [SecuritySafeCritical] private void EnsureMethodsImported() { helper.EnsureMethodsImported(); } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { XmlFormatWriterDelegate(xmlWriter, obj, context, this); } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { xmlReader.Read(); object result = XmlFormatReaderDelegate(xmlReader, context, MemberNames, MemberNamespaces); xmlReader.ReadEndElement(); return result; } [SecuritySafeCritical] internal override DataContract BindGenericParameters(DataContract[] paramContracts, Dictionary boundContracts) { Type underlyingType = base.UnderlyingType; if (!underlyingType.IsGenericType || !underlyingType.ContainsGenericParameters) { return this; } lock (this) { if (boundContracts.TryGetValue(this, out var value)) { return value; } ClassDataContract classDataContract = new ClassDataContract(); boundContracts.Add(this, classDataContract); XmlQualifiedName stableName; object[] array; if (underlyingType.IsGenericTypeDefinition) { stableName = base.StableName; array = paramContracts; } else { stableName = DataContract.GetStableName(underlyingType.GetGenericTypeDefinition()); Type[] genericArguments = underlyingType.GetGenericArguments(); array = new object[genericArguments.Length]; for (int i = 0; i < genericArguments.Length; i++) { Type type = genericArguments[i]; if (type.IsGenericParameter) { array[i] = paramContracts[type.GenericParameterPosition]; } else { array[i] = type; } } } classDataContract.StableName = DataContract.CreateQualifiedName(DataContract.ExpandGenericParameters(XmlConvert.DecodeName(stableName.Name), new GenericNameProvider(DataContract.GetClrTypeFullName(base.UnderlyingType), array)), stableName.Namespace); if (BaseContract != null) { classDataContract.BaseContract = (ClassDataContract)BaseContract.BindGenericParameters(paramContracts, boundContracts); } classDataContract.IsISerializable = IsISerializable; classDataContract.IsValueType = base.IsValueType; classDataContract.IsReference = base.IsReference; if (Members != null) { classDataContract.Members = new List(Members.Count); foreach (DataMember member in Members) { classDataContract.Members.Add(member.BindGenericParameters(paramContracts, boundContracts)); } } return classDataContract; } } internal override bool Equals(object other, Dictionary checkedContracts) { if (IsEqualOrChecked(other, checkedContracts)) { return true; } if (base.Equals(other, checkedContracts) && other is ClassDataContract classDataContract) { if (IsISerializable) { if (!classDataContract.IsISerializable) { return false; } } else { if (classDataContract.IsISerializable) { return false; } if (Members == null) { if (classDataContract.Members != null && !IsEveryDataMemberOptional(classDataContract.Members)) { return false; } } else if (classDataContract.Members == null) { if (!IsEveryDataMemberOptional(Members)) { return false; } } else { Dictionary dictionary = new Dictionary(Members.Count); List list = new List(); for (int i = 0; i < Members.Count; i++) { dictionary.Add(Members[i].Name, Members[i]); } for (int j = 0; j < classDataContract.Members.Count; j++) { if (dictionary.TryGetValue(classDataContract.Members[j].Name, out var value)) { if (!value.Equals(classDataContract.Members[j], checkedContracts)) { return false; } dictionary.Remove(value.Name); } else { list.Add(classDataContract.Members[j]); } } if (!IsEveryDataMemberOptional(dictionary.Values)) { return false; } if (!IsEveryDataMemberOptional(list)) { return false; } } } if (BaseContract == null) { return classDataContract.BaseContract == null; } if (classDataContract.BaseContract == null) { return false; } return BaseContract.Equals(classDataContract.BaseContract, checkedContracts); } return false; } private bool IsEveryDataMemberOptional(IEnumerable dataMembers) { foreach (DataMember dataMember in dataMembers) { if (dataMember.IsRequired) { return false; } } return true; } public override int GetHashCode() { return base.GetHashCode(); } } [DataContract(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")] internal struct KeyValue { private K key; private V value; [DataMember(IsRequired = true)] public K Key { get { return key; } set { key = value; } } [DataMember(IsRequired = true)] public V Value { get { return value; } set { this.value = value; } } internal KeyValue(K key, V value) { this.key = key; this.value = value; } } internal enum CollectionKind : byte { None, GenericDictionary, Dictionary, GenericList, GenericCollection, List, GenericEnumerable, Collection, Enumerable, Array } internal sealed class CollectionDataContract : DataContract { private class CollectionDataContractCriticalHelper : DataContractCriticalHelper { private static Type[] _knownInterfaces; private Type itemType; private bool isItemTypeNullable; private CollectionKind kind; private readonly MethodInfo getEnumeratorMethod; private readonly MethodInfo addMethod; private readonly ConstructorInfo constructor; private readonly string serializationExceptionMessage; private readonly string deserializationExceptionMessage; private DataContract itemContract; private DataContract sharedTypeContract; private Dictionary knownDataContracts; private bool isKnownTypeAttributeChecked; private string itemName; private bool itemNameSetExplicit; private XmlDictionaryString collectionItemName; private string keyName; private string valueName; private XmlDictionaryString childElementNamespace; private string invalidCollectionInSharedContractMessage; private XmlFormatCollectionReaderDelegate xmlFormatReaderDelegate; private XmlFormatGetOnlyCollectionReaderDelegate xmlFormatGetOnlyCollectionReaderDelegate; private XmlFormatCollectionWriterDelegate xmlFormatWriterDelegate; private bool isConstructorCheckRequired; internal static Type[] KnownInterfaces { get { if (_knownInterfaces == null) { _knownInterfaces = new Type[8] { Globals.TypeOfIDictionaryGeneric, Globals.TypeOfIDictionary, Globals.TypeOfIListGeneric, Globals.TypeOfICollectionGeneric, Globals.TypeOfIList, Globals.TypeOfIEnumerableGeneric, Globals.TypeOfICollection, Globals.TypeOfIEnumerable }; } return _knownInterfaces; } } internal CollectionKind Kind => kind; internal Type ItemType => itemType; internal DataContract ItemContract { get { if (itemContract == null && base.UnderlyingType != null) { if (IsDictionary) { if (string.CompareOrdinal(KeyName, ValueName) == 0) { DataContract.ThrowInvalidDataContractException(SR.GetString("The collection data contract type '{0}' specifies the same value '{1}' for both the KeyName and the ValueName properties. This is not allowed. Consider changing either the KeyName or the ValueName property.", DataContract.GetClrTypeFullName(base.UnderlyingType), KeyName), base.UnderlyingType); } itemContract = ClassDataContract.CreateClassDataContractForKeyValue(ItemType, base.Namespace, new string[2] { KeyName, ValueName }); DataContract.GetDataContract(ItemType); } else { itemContract = DataContract.GetDataContract(ItemType); } } return itemContract; } set { itemContract = value; } } internal DataContract SharedTypeContract { get { return sharedTypeContract; } set { sharedTypeContract = value; } } internal string ItemName { get { return itemName; } set { itemName = value; } } internal bool IsConstructorCheckRequired { get { return isConstructorCheckRequired; } set { isConstructorCheckRequired = value; } } public XmlDictionaryString CollectionItemName => collectionItemName; internal string KeyName { get { return keyName; } set { keyName = value; } } internal string ValueName { get { return valueName; } set { valueName = value; } } internal bool IsDictionary => KeyName != null; public string SerializationExceptionMessage => serializationExceptionMessage; public string DeserializationExceptionMessage => deserializationExceptionMessage; public XmlDictionaryString ChildElementNamespace { get { return childElementNamespace; } set { childElementNamespace = value; } } internal bool IsItemTypeNullable { get { return isItemTypeNullable; } set { isItemTypeNullable = value; } } internal MethodInfo GetEnumeratorMethod => getEnumeratorMethod; internal MethodInfo AddMethod => addMethod; internal ConstructorInfo Constructor => constructor; internal override Dictionary KnownDataContracts { get { if (!isKnownTypeAttributeChecked && base.UnderlyingType != null) { lock (this) { if (!isKnownTypeAttributeChecked) { knownDataContracts = DataContract.ImportKnownTypeAttributes(base.UnderlyingType); Thread.MemoryBarrier(); isKnownTypeAttributeChecked = true; } } } return knownDataContracts; } set { knownDataContracts = value; } } internal string InvalidCollectionInSharedContractMessage => invalidCollectionInSharedContractMessage; internal bool ItemNameSetExplicit => itemNameSetExplicit; internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate { get { return xmlFormatWriterDelegate; } set { xmlFormatWriterDelegate = value; } } internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate { get { return xmlFormatReaderDelegate; } set { xmlFormatReaderDelegate = value; } } internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate { get { return xmlFormatGetOnlyCollectionReaderDelegate; } set { xmlFormatGetOnlyCollectionReaderDelegate = value; } } private void Init(CollectionKind kind, Type itemType, CollectionDataContractAttribute collectionContractAttribute) { this.kind = kind; if (itemType != null) { this.itemType = itemType; isItemTypeNullable = DataContract.IsTypeNullable(itemType); bool flag = kind == CollectionKind.Dictionary || kind == CollectionKind.GenericDictionary; string text = null; string text2 = null; string text3 = null; if (collectionContractAttribute != null) { if (collectionContractAttribute.IsItemNameSetExplicitly) { if (collectionContractAttribute.ItemName == null || collectionContractAttribute.ItemName.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Type '{0}' cannot have CollectionDataContractAttribute attribute ItemName set to null or empty string.", DataContract.GetClrTypeFullName(base.UnderlyingType)))); } text = DataContract.EncodeLocalName(collectionContractAttribute.ItemName); itemNameSetExplicit = true; } if (collectionContractAttribute.IsKeyNameSetExplicitly) { if (collectionContractAttribute.KeyName == null || collectionContractAttribute.KeyName.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Type '{0}' cannot have CollectionDataContractAttribute attribute KeyName set to null or empty string.", DataContract.GetClrTypeFullName(base.UnderlyingType)))); } if (!flag) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("The collection data contract type '{0}' specifies '{1}' for the KeyName property. This is not allowed since the type is not IDictionary. Remove the setting for the KeyName property.", DataContract.GetClrTypeFullName(base.UnderlyingType), collectionContractAttribute.KeyName))); } text2 = DataContract.EncodeLocalName(collectionContractAttribute.KeyName); } if (collectionContractAttribute.IsValueNameSetExplicitly) { if (collectionContractAttribute.ValueName == null || collectionContractAttribute.ValueName.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Type '{0}' cannot have CollectionDataContractAttribute attribute ValueName set to null or empty string.", DataContract.GetClrTypeFullName(base.UnderlyingType)))); } if (!flag) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("The collection data contract type '{0}' specifies '{1}' for the ValueName property. This is not allowed since the type is not IDictionary. Remove the setting for the ValueName property.", DataContract.GetClrTypeFullName(base.UnderlyingType), collectionContractAttribute.ValueName))); } text3 = DataContract.EncodeLocalName(collectionContractAttribute.ValueName); } } XmlDictionary xmlDictionary = (flag ? new XmlDictionary(5) : new XmlDictionary(3)); base.Name = xmlDictionary.Add(base.StableName.Name); base.Namespace = xmlDictionary.Add(base.StableName.Namespace); itemName = text ?? DataContract.GetStableName(DataContract.UnwrapNullableType(itemType)).Name; collectionItemName = xmlDictionary.Add(itemName); if (flag) { keyName = text2 ?? "Key"; valueName = text3 ?? "Value"; } } if (collectionContractAttribute != null) { base.IsReference = collectionContractAttribute.IsReference; } } internal CollectionDataContractCriticalHelper(CollectionKind kind) { Init(kind, null, null); } internal CollectionDataContractCriticalHelper(Type type) : base(type) { if (type == Globals.TypeOfArray) { type = Globals.TypeOfObjectArray; } if (type.GetArrayRank() > 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("Multi-dimensional arrays are not supported."))); } base.StableName = DataContract.GetStableName(type); Init(CollectionKind.Array, type.GetElementType(), null); } internal CollectionDataContractCriticalHelper(Type type, DataContract itemContract) : base(type) { if (type.GetArrayRank() > 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("Multi-dimensional arrays are not supported."))); } base.StableName = DataContract.CreateQualifiedName("ArrayOf" + itemContract.StableName.Name, itemContract.StableName.Namespace); this.itemContract = itemContract; Init(CollectionKind.Array, type.GetElementType(), null); } internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string serializationExceptionMessage, string deserializationExceptionMessage) : base(type) { if (getEnumeratorMethod == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Collection type '{0}' does not have a valid GetEnumerator method.", DataContract.GetClrTypeFullName(type)))); } if (itemType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Collection type '{0}' must have a non-null item type.", DataContract.GetClrTypeFullName(type)))); } base.StableName = DataContract.GetCollectionStableName(type, itemType, out var collectionContractAttribute); Init(kind, itemType, collectionContractAttribute); this.getEnumeratorMethod = getEnumeratorMethod; this.serializationExceptionMessage = serializationExceptionMessage; this.deserializationExceptionMessage = deserializationExceptionMessage; } internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor) : this(type, kind, itemType, getEnumeratorMethod, (string)null, (string)null) { if (addMethod == null && !type.IsInterface) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Collection type '{0}' does not have a valid Add method.", DataContract.GetClrTypeFullName(type)))); } this.addMethod = addMethod; this.constructor = constructor; } internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired) : this(type, kind, itemType, getEnumeratorMethod, addMethod, constructor) { this.isConstructorCheckRequired = isConstructorCheckRequired; } internal CollectionDataContractCriticalHelper(Type type, string invalidCollectionInSharedContractMessage) : base(type) { Init(CollectionKind.Collection, null, null); this.invalidCollectionInSharedContractMessage = invalidCollectionInSharedContractMessage; } } public class DictionaryEnumerator : IEnumerator>, IDisposable, IEnumerator { private IDictionaryEnumerator enumerator; public KeyValue Current => new KeyValue(enumerator.Key, enumerator.Value); object IEnumerator.Current => Current; public DictionaryEnumerator(IDictionaryEnumerator enumerator) { this.enumerator = enumerator; } public void Dispose() { } public bool MoveNext() { return enumerator.MoveNext(); } public void Reset() { enumerator.Reset(); } } public class GenericDictionaryEnumerator : IEnumerator>, IDisposable, IEnumerator { private IEnumerator> enumerator; public KeyValue Current { get { KeyValuePair current = enumerator.Current; return new KeyValue(current.Key, current.Value); } } object IEnumerator.Current => Current; public GenericDictionaryEnumerator(IEnumerator> enumerator) { this.enumerator = enumerator; } public void Dispose() { } public bool MoveNext() { return enumerator.MoveNext(); } public void Reset() { enumerator.Reset(); } } [SecurityCritical] private XmlDictionaryString collectionItemName; [SecurityCritical] private XmlDictionaryString childElementNamespace; [SecurityCritical] private DataContract itemContract; [SecurityCritical] private CollectionDataContractCriticalHelper helper; private static Type[] KnownInterfaces { [SecuritySafeCritical] get { return CollectionDataContractCriticalHelper.KnownInterfaces; } } internal CollectionKind Kind { [SecuritySafeCritical] get { return helper.Kind; } } internal Type ItemType { [SecuritySafeCritical] get { return helper.ItemType; } } public DataContract ItemContract { [SecuritySafeCritical] get { return itemContract ?? helper.ItemContract; } [SecurityCritical] set { itemContract = value; helper.ItemContract = value; } } internal DataContract SharedTypeContract { [SecuritySafeCritical] get { return helper.SharedTypeContract; } } internal string ItemName { [SecuritySafeCritical] get { return helper.ItemName; } [SecurityCritical] set { helper.ItemName = value; } } public XmlDictionaryString CollectionItemName { [SecuritySafeCritical] get { return collectionItemName; } } internal string KeyName { [SecuritySafeCritical] get { return helper.KeyName; } [SecurityCritical] set { helper.KeyName = value; } } internal string ValueName { [SecuritySafeCritical] get { return helper.ValueName; } [SecurityCritical] set { helper.ValueName = value; } } internal bool IsDictionary => KeyName != null; public XmlDictionaryString ChildElementNamespace { [SecuritySafeCritical] get { if (childElementNamespace == null) { lock (this) { if (childElementNamespace == null) { if (helper.ChildElementNamespace == null && !IsDictionary) { XmlDictionaryString childNamespaceToDeclare = ClassDataContract.GetChildNamespaceToDeclare(this, ItemType, new XmlDictionary()); Thread.MemoryBarrier(); helper.ChildElementNamespace = childNamespaceToDeclare; } childElementNamespace = helper.ChildElementNamespace; } } } return childElementNamespace; } } internal bool IsItemTypeNullable { [SecuritySafeCritical] get { return helper.IsItemTypeNullable; } [SecurityCritical] set { helper.IsItemTypeNullable = value; } } internal bool IsConstructorCheckRequired { [SecuritySafeCritical] get { return helper.IsConstructorCheckRequired; } [SecurityCritical] set { helper.IsConstructorCheckRequired = value; } } internal MethodInfo GetEnumeratorMethod { [SecuritySafeCritical] get { return helper.GetEnumeratorMethod; } } internal MethodInfo AddMethod { [SecuritySafeCritical] get { return helper.AddMethod; } } internal ConstructorInfo Constructor { [SecuritySafeCritical] get { return helper.Constructor; } } internal override Dictionary KnownDataContracts { [SecuritySafeCritical] get { return helper.KnownDataContracts; } [SecurityCritical] set { helper.KnownDataContracts = value; } } internal string InvalidCollectionInSharedContractMessage { [SecuritySafeCritical] get { return helper.InvalidCollectionInSharedContractMessage; } } internal string SerializationExceptionMessage { [SecuritySafeCritical] get { return helper.SerializationExceptionMessage; } } internal string DeserializationExceptionMessage { [SecuritySafeCritical] get { return helper.DeserializationExceptionMessage; } } internal bool IsReadOnlyContract => DeserializationExceptionMessage != null; private bool ItemNameSetExplicit { [SecuritySafeCritical] get { return helper.ItemNameSetExplicit; } } internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate { [SecuritySafeCritical] get { if (helper.XmlFormatWriterDelegate == null) { lock (this) { if (helper.XmlFormatWriterDelegate == null) { XmlFormatCollectionWriterDelegate xmlFormatWriterDelegate = new XmlFormatWriterGenerator().GenerateCollectionWriter(this); Thread.MemoryBarrier(); helper.XmlFormatWriterDelegate = xmlFormatWriterDelegate; } } } return helper.XmlFormatWriterDelegate; } } internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate { [SecuritySafeCritical] get { if (helper.XmlFormatReaderDelegate == null) { lock (this) { if (helper.XmlFormatReaderDelegate == null) { if (IsReadOnlyContract) { DataContract.ThrowInvalidDataContractException(helper.DeserializationExceptionMessage, null); } XmlFormatCollectionReaderDelegate xmlFormatReaderDelegate = new XmlFormatReaderGenerator().GenerateCollectionReader(this); Thread.MemoryBarrier(); helper.XmlFormatReaderDelegate = xmlFormatReaderDelegate; } } } return helper.XmlFormatReaderDelegate; } } internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate { [SecuritySafeCritical] get { if (helper.XmlFormatGetOnlyCollectionReaderDelegate == null) { lock (this) { if (helper.XmlFormatGetOnlyCollectionReaderDelegate == null) { if (base.UnderlyingType.IsInterface && (Kind == CollectionKind.Enumerable || Kind == CollectionKind.Collection || Kind == CollectionKind.GenericEnumerable)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("On type '{0}', get-only collection must have an Add method.", DataContract.GetClrTypeFullName(base.UnderlyingType)))); } if (IsReadOnlyContract) { DataContract.ThrowInvalidDataContractException(helper.DeserializationExceptionMessage, null); } XmlFormatGetOnlyCollectionReaderDelegate xmlFormatGetOnlyCollectionReaderDelegate = new XmlFormatReaderGenerator().GenerateGetOnlyCollectionReader(this); Thread.MemoryBarrier(); helper.XmlFormatGetOnlyCollectionReaderDelegate = xmlFormatGetOnlyCollectionReaderDelegate; } } } return helper.XmlFormatGetOnlyCollectionReaderDelegate; } } [SecuritySafeCritical] internal CollectionDataContract(CollectionKind kind) : base(new CollectionDataContractCriticalHelper(kind)) { InitCollectionDataContract(this); } [SecuritySafeCritical] internal CollectionDataContract(Type type) : base(new CollectionDataContractCriticalHelper(type)) { InitCollectionDataContract(this); } [SecuritySafeCritical] internal CollectionDataContract(Type type, DataContract itemContract) : base(new CollectionDataContractCriticalHelper(type, itemContract)) { InitCollectionDataContract(this); } [SecuritySafeCritical] private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string serializationExceptionMessage, string deserializationExceptionMessage) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, serializationExceptionMessage, deserializationExceptionMessage)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [SecuritySafeCritical] private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [SecuritySafeCritical] private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor, isConstructorCheckRequired)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [SecuritySafeCritical] private CollectionDataContract(Type type, string invalidCollectionInSharedContractMessage) : base(new CollectionDataContractCriticalHelper(type, invalidCollectionInSharedContractMessage)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [SecurityCritical] private void InitCollectionDataContract(DataContract sharedTypeContract) { helper = base.Helper as CollectionDataContractCriticalHelper; collectionItemName = helper.CollectionItemName; if (helper.Kind == CollectionKind.Dictionary || helper.Kind == CollectionKind.GenericDictionary) { itemContract = helper.ItemContract; } helper.SharedTypeContract = sharedTypeContract; } private void InitSharedTypeContract() { } private DataContract GetSharedTypeContract(Type type) { if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, inherit: false)) { return this; } if (type.IsSerializable || type.IsDefined(Globals.TypeOfDataContractAttribute, inherit: false)) { return new ClassDataContract(type); } return null; } internal static bool IsCollectionInterface(Type type) { if (type.IsGenericType) { type = type.GetGenericTypeDefinition(); } return ((ICollection)KnownInterfaces).Contains(type); } internal static bool IsCollection(Type type) { Type itemType; return IsCollection(type, out itemType); } internal static bool IsCollection(Type type, out Type itemType) { return IsCollectionHelper(type, out itemType, constructorRequired: true); } internal static bool IsCollection(Type type, bool constructorRequired, bool skipIfReadOnlyContract) { Type itemType; return IsCollectionHelper(type, out itemType, constructorRequired, skipIfReadOnlyContract); } private static bool IsCollectionHelper(Type type, out Type itemType, bool constructorRequired, bool skipIfReadOnlyContract = false) { if (type.IsArray && DataContract.GetBuiltInDataContract(type) == null) { itemType = type.GetElementType(); return true; } DataContract dataContract; return IsCollectionOrTryCreate(type, tryCreate: false, out dataContract, out itemType, constructorRequired, skipIfReadOnlyContract); } internal static bool TryCreate(Type type, out DataContract dataContract) { Type itemType; return IsCollectionOrTryCreate(type, tryCreate: true, out dataContract, out itemType, constructorRequired: true); } internal static bool TryCreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract) { if (type.IsArray) { dataContract = new CollectionDataContract(type); return true; } Type itemType; return IsCollectionOrTryCreate(type, tryCreate: true, out dataContract, out itemType, constructorRequired: false); } internal static MethodInfo GetTargetMethodWithName(string name, Type type, Type interfaceType) { InterfaceMapping interfaceMap = type.GetInterfaceMap(interfaceType); for (int i = 0; i < interfaceMap.TargetMethods.Length; i++) { if (interfaceMap.InterfaceMethods[i].Name == name) { return interfaceMap.InterfaceMethods[i]; } } return null; } private static bool IsArraySegment(Type t) { if (t.IsGenericType) { return t.GetGenericTypeDefinition() == typeof(ArraySegment<>); } return false; } private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataContract dataContract, out Type itemType, bool constructorRequired, bool skipIfReadOnlyContract = false) { dataContract = null; itemType = Globals.TypeOfObject; if (DataContract.GetBuiltInDataContract(type) != null) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract: false, createContractWithException: false, "{0} is a built-in type and cannot be a collection.", null, ref dataContract); } bool hasCollectionDataContract = IsCollectionDataContract(type); bool flag = false; string serializationExceptionMessage = null; string deserializationExceptionMessage = null; Type baseType = type.BaseType; bool flag2 = baseType != null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri && IsCollection(baseType) && !type.IsSerializable; if (type.IsDefined(Globals.TypeOfDataContractAttribute, inherit: false)) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, flag2, "{0} has DataContractAttribute attribute.", null, ref dataContract); } if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type) || IsArraySegment(type)) { return false; } if (!Globals.TypeOfIEnumerable.IsAssignableFrom(type)) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, flag2, "{0} does not implement IEnumerable interface.", null, ref dataContract); } MethodInfo method; MethodInfo addMethod; if (type.IsInterface) { Type type2 = (type.IsGenericType ? type.GetGenericTypeDefinition() : type); Type[] knownInterfaces = KnownInterfaces; for (int i = 0; i < knownInterfaces.Length; i++) { if (!(knownInterfaces[i] == type2)) { continue; } addMethod = null; if (type.IsGenericType) { Type[] genericArguments = type.GetGenericArguments(); if (type2 == Globals.TypeOfIDictionaryGeneric) { itemType = Globals.TypeOfKeyValue.MakeGenericType(genericArguments); addMethod = type.GetMethod("Add"); method = Globals.TypeOfIEnumerableGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(genericArguments)).GetMethod("GetEnumerator"); } else { itemType = genericArguments[0]; if (type2 == Globals.TypeOfICollectionGeneric || type2 == Globals.TypeOfIListGeneric) { addMethod = Globals.TypeOfICollectionGeneric.MakeGenericType(itemType).GetMethod("Add"); } method = Globals.TypeOfIEnumerableGeneric.MakeGenericType(itemType).GetMethod("GetEnumerator"); } } else { if (type2 == Globals.TypeOfIDictionary) { itemType = typeof(KeyValue); addMethod = type.GetMethod("Add"); } else { itemType = Globals.TypeOfObject; if (type2 == Globals.TypeOfIList) { addMethod = Globals.TypeOfIList.GetMethod("Add"); } } method = Globals.TypeOfIEnumerable.GetMethod("GetEnumerator"); } if (tryCreate) { dataContract = new CollectionDataContract(type, (CollectionKind)(i + 1), itemType, method, addMethod, null); } return true; } } ConstructorInfo constructorInfo = null; if (!type.IsValueType) { constructorInfo = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Globals.EmptyTypeArray, null); if (constructorInfo == null && constructorRequired) { if (type.IsSerializable) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, flag2, "{0} does not have a default constructor.", null, ref dataContract); } flag = true; GetReadOnlyCollectionExceptionMessages(type, hasCollectionDataContract, "{0} does not have a default constructor.", null, out serializationExceptionMessage, out deserializationExceptionMessage); } } Type type3 = null; CollectionKind collectionKind = CollectionKind.None; bool flag3 = false; Type[] interfaces = type.GetInterfaces(); foreach (Type type4 in interfaces) { Type type5 = (type4.IsGenericType ? type4.GetGenericTypeDefinition() : type4); Type[] knownInterfaces2 = KnownInterfaces; for (int k = 0; k < knownInterfaces2.Length; k++) { if (knownInterfaces2[k] == type5) { CollectionKind collectionKind2 = (CollectionKind)(k + 1); if (collectionKind == CollectionKind.None || (int)collectionKind2 < (int)collectionKind) { collectionKind = collectionKind2; type3 = type4; flag3 = false; } else if ((collectionKind & collectionKind2) == collectionKind2) { flag3 = true; } break; } } } switch (collectionKind) { case CollectionKind.None: return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, flag2, "{0} does not implement IEnumerable interface.", null, ref dataContract); case CollectionKind.GenericEnumerable: case CollectionKind.Collection: case CollectionKind.Enumerable: if (flag3) { type3 = Globals.TypeOfIEnumerable; } itemType = (type3.IsGenericType ? type3.GetGenericArguments()[0] : Globals.TypeOfObject); GetCollectionMethods(type, type3, new Type[1] { itemType }, addMethodOnInterface: false, out method, out addMethod); if (addMethod == null) { if (type.IsSerializable || skipIfReadOnlyContract) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, flag2 && !skipIfReadOnlyContract, "{0} does not have a valid Add method with parameter of type '{1}'.", DataContract.GetClrTypeFullName(itemType), ref dataContract); } flag = true; GetReadOnlyCollectionExceptionMessages(type, hasCollectionDataContract, "{0} does not have a valid Add method with parameter of type '{1}'.", DataContract.GetClrTypeFullName(itemType), out serializationExceptionMessage, out deserializationExceptionMessage); } if (tryCreate) { dataContract = (flag ? new CollectionDataContract(type, collectionKind, itemType, method, serializationExceptionMessage, deserializationExceptionMessage) : new CollectionDataContract(type, collectionKind, itemType, method, addMethod, constructorInfo, !constructorRequired)); } break; default: { if (flag3) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, flag2, "{0} has multiple definitions of interface '{1}'.", KnownInterfaces[(uint)(collectionKind - 1)].Name, ref dataContract); } Type[] array = null; switch (collectionKind) { case CollectionKind.GenericDictionary: { array = type3.GetGenericArguments(); bool flag4 = type3.IsGenericTypeDefinition || (array[0].IsGenericParameter && array[1].IsGenericParameter); itemType = (flag4 ? Globals.TypeOfKeyValue : Globals.TypeOfKeyValue.MakeGenericType(array)); break; } case CollectionKind.Dictionary: array = new Type[2] { Globals.TypeOfObject, Globals.TypeOfObject }; itemType = Globals.TypeOfKeyValue.MakeGenericType(array); break; case CollectionKind.GenericList: case CollectionKind.GenericCollection: array = type3.GetGenericArguments(); itemType = array[0]; break; case CollectionKind.List: itemType = Globals.TypeOfObject; array = new Type[1] { itemType }; break; } if (tryCreate) { GetCollectionMethods(type, type3, array, addMethodOnInterface: true, out method, out addMethod); dataContract = (flag ? new CollectionDataContract(type, collectionKind, itemType, method, serializationExceptionMessage, deserializationExceptionMessage) : new CollectionDataContract(type, collectionKind, itemType, method, addMethod, constructorInfo, !constructorRequired)); } break; } } return !(flag && skipIfReadOnlyContract); } internal static bool IsCollectionDataContract(Type type) { return type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, inherit: false); } private static bool HandleIfInvalidCollection(Type type, bool tryCreate, bool hasCollectionDataContract, bool createContractWithException, string message, string param, ref DataContract dataContract) { if (hasCollectionDataContract) { if (tryCreate) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(GetInvalidCollectionMessage(message, SR.GetString("Type '{0}' with CollectionDataContractAttribute attribute is an invalid collection type since it", DataContract.GetClrTypeFullName(type)), param))); } return true; } if (createContractWithException) { if (tryCreate) { dataContract = new CollectionDataContract(type, GetInvalidCollectionMessage(message, SR.GetString("Type '{0}' is an invalid collection type since it", DataContract.GetClrTypeFullName(type)), param)); } return true; } return false; } private static void GetReadOnlyCollectionExceptionMessages(Type type, bool hasCollectionDataContract, string message, string param, out string serializationExceptionMessage, out string deserializationExceptionMessage) { serializationExceptionMessage = GetInvalidCollectionMessage(message, SR.GetString(hasCollectionDataContract ? "Type '{0}' with CollectionDataContractAttribute attribute is an invalid collection type since it" : "Type '{0}' is an invalid collection type since it", DataContract.GetClrTypeFullName(type)), param); deserializationExceptionMessage = GetInvalidCollectionMessage(message, SR.GetString("Error on deserializing read-only collection: {0}", DataContract.GetClrTypeFullName(type)), param); } private static string GetInvalidCollectionMessage(string message, string nestedMessage, string param) { if (param != null) { return SR.GetString(message, nestedMessage, param); } return SR.GetString(message, nestedMessage); } private static void FindCollectionMethodsOnInterface(Type type, Type interfaceType, ref MethodInfo addMethod, ref MethodInfo getEnumeratorMethod) { InterfaceMapping interfaceMap = type.GetInterfaceMap(interfaceType); for (int i = 0; i < interfaceMap.TargetMethods.Length; i++) { if (interfaceMap.InterfaceMethods[i].Name == "Add") { addMethod = interfaceMap.InterfaceMethods[i]; } else if (interfaceMap.InterfaceMethods[i].Name == "GetEnumerator") { getEnumeratorMethod = interfaceMap.InterfaceMethods[i]; } } } private static void GetCollectionMethods(Type type, Type interfaceType, Type[] addMethodTypeArray, bool addMethodOnInterface, out MethodInfo getEnumeratorMethod, out MethodInfo addMethod) { addMethod = (getEnumeratorMethod = null); if (addMethodOnInterface) { addMethod = type.GetMethod("Add", BindingFlags.Instance | BindingFlags.Public, null, addMethodTypeArray, null); if (addMethod == null || addMethod.GetParameters()[0].ParameterType != addMethodTypeArray[0]) { FindCollectionMethodsOnInterface(type, interfaceType, ref addMethod, ref getEnumeratorMethod); if (addMethod == null) { Type[] interfaces = interfaceType.GetInterfaces(); foreach (Type type2 in interfaces) { if (IsKnownInterface(type2)) { FindCollectionMethodsOnInterface(type, type2, ref addMethod, ref getEnumeratorMethod); if (addMethod == null) { break; } } } } } } else { addMethod = type.GetMethod("Add", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, addMethodTypeArray, null); } if (!(getEnumeratorMethod == null)) { return; } getEnumeratorMethod = type.GetMethod("GetEnumerator", BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null); if (getEnumeratorMethod == null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType)) { Type type3 = interfaceType.GetInterface("System.Collections.Generic.IEnumerable*"); if (type3 == null) { type3 = Globals.TypeOfIEnumerable; } getEnumeratorMethod = GetTargetMethodWithName("GetEnumerator", type, type3); } } private static bool IsKnownInterface(Type type) { Type type2 = (type.IsGenericType ? type.GetGenericTypeDefinition() : type); Type[] knownInterfaces = KnownInterfaces; foreach (Type type3 in knownInterfaces) { if (type2 == type3) { return true; } } return false; } [SecuritySafeCritical] internal override DataContract BindGenericParameters(DataContract[] paramContracts, Dictionary boundContracts) { if (boundContracts.TryGetValue(this, out var value)) { return value; } CollectionDataContract collectionDataContract = new CollectionDataContract(Kind); boundContracts.Add(this, collectionDataContract); collectionDataContract.ItemContract = ItemContract.BindGenericParameters(paramContracts, boundContracts); collectionDataContract.IsItemTypeNullable = !collectionDataContract.ItemContract.IsValueType; collectionDataContract.ItemName = (ItemNameSetExplicit ? ItemName : collectionDataContract.ItemContract.StableName.Name); collectionDataContract.KeyName = KeyName; collectionDataContract.ValueName = ValueName; collectionDataContract.StableName = DataContract.CreateQualifiedName(DataContract.ExpandGenericParameters(XmlConvert.DecodeName(base.StableName.Name), new GenericNameProvider(DataContract.GetClrTypeFullName(base.UnderlyingType), paramContracts)), IsCollectionDataContract(base.UnderlyingType) ? base.StableName.Namespace : DataContract.GetCollectionNamespace(collectionDataContract.ItemContract.StableName.Namespace)); return collectionDataContract; } internal override DataContract GetValidContract(SerializationMode mode) { if (mode == SerializationMode.SharedType) { if (SharedTypeContract == null) { DataContract.ThrowTypeNotSerializable(base.UnderlyingType); } return SharedTypeContract; } ThrowIfInvalid(); return this; } private void ThrowIfInvalid() { if (InvalidCollectionInSharedContractMessage != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(InvalidCollectionInSharedContractMessage)); } } internal override DataContract GetValidContract() { if (IsConstructorCheckRequired) { CheckConstructor(); } return this; } [SecuritySafeCritical] private void CheckConstructor() { if (Constructor == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("{0} does not have a default constructor.", DataContract.GetClrTypeFullName(base.UnderlyingType)))); } IsConstructorCheckRequired = false; } internal override bool IsValidContract(SerializationMode mode) { if (mode == SerializationMode.SharedType) { return SharedTypeContract != null; } return InvalidCollectionInSharedContractMessage == null; } internal override bool Equals(object other, Dictionary checkedContracts) { if (IsEqualOrChecked(other, checkedContracts)) { return true; } if (base.Equals(other, checkedContracts) && other is CollectionDataContract collectionDataContract) { bool flag = ItemContract != null && !ItemContract.IsValueType; bool flag2 = collectionDataContract.ItemContract != null && !collectionDataContract.ItemContract.IsValueType; if (ItemName == collectionDataContract.ItemName && (IsItemTypeNullable || flag) == (collectionDataContract.IsItemTypeNullable || flag2)) { return ItemContract.Equals(collectionDataContract.ItemContract, checkedContracts); } return false; } return false; } public override int GetHashCode() { return base.GetHashCode(); } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { context.IsGetOnlyCollection = false; XmlFormatWriterDelegate(xmlWriter, obj, context, this); } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { xmlReader.Read(); object result = null; if (context.IsGetOnlyCollection) { context.IsGetOnlyCollection = false; XmlFormatGetOnlyCollectionReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this); } else { result = XmlFormatReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this); } xmlReader.ReadEndElement(); return result; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false, AllowMultiple = false)] public sealed class CollectionDataContractAttribute : Attribute { private string name; private string ns; private string itemName; private string keyName; private string valueName; private bool isReference; private bool isNameSetExplicitly; private bool isNamespaceSetExplicitly; private bool isReferenceSetExplicitly; private bool isItemNameSetExplicitly; private bool isKeyNameSetExplicitly; private bool isValueNameSetExplicitly; public string Namespace { get { return ns; } set { ns = value; isNamespaceSetExplicitly = true; } } public bool IsNamespaceSetExplicitly => isNamespaceSetExplicitly; public string Name { get { return name; } set { name = value; isNameSetExplicitly = true; } } public bool IsNameSetExplicitly => isNameSetExplicitly; public string ItemName { get { return itemName; } set { itemName = value; isItemNameSetExplicitly = true; } } public bool IsItemNameSetExplicitly => isItemNameSetExplicitly; public string KeyName { get { return keyName; } set { keyName = value; isKeyNameSetExplicitly = true; } } public bool IsReference { get { return isReference; } set { isReference = value; isReferenceSetExplicitly = true; } } public bool IsReferenceSetExplicitly => isReferenceSetExplicitly; public bool IsKeyNameSetExplicitly => isKeyNameSetExplicitly; public string ValueName { get { return valueName; } set { valueName = value; isValueNameSetExplicitly = true; } } public bool IsValueNameSetExplicitly => isValueNameSetExplicitly; } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module, Inherited = false, AllowMultiple = true)] public sealed class ContractNamespaceAttribute : Attribute { private string clrNamespace; private string contractNamespace; public string ClrNamespace { get { return clrNamespace; } set { clrNamespace = value; } } public string ContractNamespace => contractNamespace; public ContractNamespaceAttribute(string contractNamespace) { this.contractNamespace = contractNamespace; } } internal abstract class DataContract { protected class DataContractCriticalHelper { private static Dictionary typeToIDCache; private static DataContract[] dataContractCache; private static int dataContractID; private static Dictionary typeToBuiltInContract; private static Dictionary nameToBuiltInContract; private static Dictionary typeNameToBuiltInContract; private static Dictionary namespaces; private static Dictionary clrTypeStrings; private static XmlDictionary clrTypeStringsDictionary; private static TypeHandleRef typeHandleRef; private static object cacheLock; private static object createDataContractLock; private static object initBuiltInContractsLock; private static object namespacesLock; private static object clrTypeStringsLock; private readonly Type underlyingType; private Type originalUnderlyingType; private bool isReference; private bool isValueType; private XmlQualifiedName stableName; private GenericInfo genericInfo; private XmlDictionaryString name; private XmlDictionaryString ns; private Type typeForInitialization; private MethodInfo parseMethod; private bool parseMethodSet; internal Type UnderlyingType => underlyingType; internal Type OriginalUnderlyingType { get { if (originalUnderlyingType == null) { originalUnderlyingType = GetDataContractOriginalType(underlyingType); } return originalUnderlyingType; } } internal virtual bool IsBuiltInDataContract => false; internal Type TypeForInitialization => typeForInitialization; internal bool IsReference { get { return isReference; } set { isReference = value; } } internal bool IsValueType { get { return isValueType; } set { isValueType = value; } } internal XmlQualifiedName StableName { get { return stableName; } set { stableName = value; } } internal GenericInfo GenericInfo { get { return genericInfo; } set { genericInfo = value; } } internal virtual Dictionary KnownDataContracts { get { return null; } set { } } internal virtual bool IsISerializable { get { return false; } set { ThrowInvalidDataContractException(SR.GetString("To set IsISerializable, class data cotnract is required.")); } } internal XmlDictionaryString Name { get { return name; } set { name = value; } } public XmlDictionaryString Namespace { get { return ns; } set { ns = value; } } internal virtual bool HasRoot { get { return true; } set { } } internal virtual XmlDictionaryString TopLevelElementName { get { return name; } set { name = value; } } internal virtual XmlDictionaryString TopLevelElementNamespace { get { return ns; } set { ns = value; } } internal virtual bool CanContainReferences => true; internal virtual bool IsPrimitive => false; internal MethodInfo ParseMethod { get { if (!parseMethodSet) { MethodInfo method = UnderlyingType.GetMethod("Parse", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { Globals.TypeOfString }, null); if (method != null && method.ReturnType == UnderlyingType) { parseMethod = method; } parseMethodSet = true; } return parseMethod; } } static DataContractCriticalHelper() { typeHandleRef = new TypeHandleRef(); cacheLock = new object(); createDataContractLock = new object(); initBuiltInContractsLock = new object(); namespacesLock = new object(); clrTypeStringsLock = new object(); typeToIDCache = new Dictionary(new TypeHandleRefEqualityComparer()); dataContractCache = new DataContract[32]; dataContractID = 0; } internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type) { DataContract dataContract = dataContractCache[id]; if (dataContract == null) { return CreateDataContract(id, typeHandle, type); } return dataContract.GetValidContract(); } internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type) { DataContract dataContract = dataContractCache[id]; if (dataContract == null) { dataContract = CreateGetOnlyCollectionDataContract(id, typeHandle, type); AssignDataContractToId(dataContract, id); } return dataContract; } internal static DataContract GetDataContractForInitialization(int id) { return dataContractCache[id] ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString("An internal error has occurred. DataContract cache overflow."))); } internal static int GetIdForInitialization(ClassDataContract classContract) { int id = DataContract.GetId(classContract.TypeForInitialization.TypeHandle); if (id < dataContractCache.Length && ContractMatches(classContract, dataContractCache[id])) { return id; } int num = dataContractID; for (int i = 0; i < num; i++) { if (ContractMatches(classContract, dataContractCache[i])) { return i; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString("An internal error has occurred. DataContract cache overflow."))); } private static bool ContractMatches(DataContract contract, DataContract cachedContract) { if (cachedContract != null) { return cachedContract.UnderlyingType == contract.UnderlyingType; } return false; } internal static int GetId(RuntimeTypeHandle typeHandle) { lock (cacheLock) { typeHandle = GetDataContractAdapterTypeHandle(typeHandle); typeHandleRef.Value = typeHandle; if (!typeToIDCache.TryGetValue(typeHandleRef, out var value)) { value = GetNextId(); try { typeToIDCache.Add(new TypeHandleRef(typeHandle), value); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } } return value.Value; } } private static IntRef GetNextId() { int num = dataContractID++; if (num >= dataContractCache.Length) { int num2 = ((num < 1073741823) ? (num * 2) : int.MaxValue); if (num2 <= num) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString("An internal error has occurred. DataContract cache overflow."))); } Array.Resize(ref dataContractCache, num2); } return new IntRef(num); } private static DataContract CreateDataContract(int id, RuntimeTypeHandle typeHandle, Type type) { DataContract dataContract = dataContractCache[id]; if (dataContract == null) { lock (createDataContractLock) { dataContract = dataContractCache[id]; if (dataContract == null) { if (type == null) { type = Type.GetTypeFromHandle(typeHandle); } type = UnwrapNullableType(type); type = GetDataContractAdapterType(type); dataContract = GetBuiltInDataContract(type); if (dataContract == null) { if (type.IsArray) { dataContract = new CollectionDataContract(type); } else if (type.IsEnum) { dataContract = new EnumDataContract(type); } else if (type.IsGenericParameter) { dataContract = new GenericParameterDataContract(type); } else if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) { dataContract = new XmlDataContract(type); } else { if (type.IsPointer) { type = Globals.TypeOfReflectionPointer; } if (!CollectionDataContract.TryCreate(type, out dataContract)) { if (type.IsSerializable || type.IsDefined(Globals.TypeOfDataContractAttribute, inherit: false) || ClassDataContract.IsNonAttributedTypeValidForSerialization(type)) { dataContract = new ClassDataContract(type); } else { ThrowInvalidDataContractException(SR.GetString("Type '{0}' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required.", type), type); } } } } AssignDataContractToId(dataContract, id); } } } return dataContract; } [MethodImpl(MethodImplOptions.NoInlining)] private static void AssignDataContractToId(DataContract dataContract, int id) { lock (cacheLock) { dataContractCache[id] = dataContract; } } private static DataContract CreateGetOnlyCollectionDataContract(int id, RuntimeTypeHandle typeHandle, Type type) { DataContract dataContract = null; lock (createDataContractLock) { dataContract = dataContractCache[id]; if (dataContract == null) { if (type == null) { type = Type.GetTypeFromHandle(typeHandle); } type = UnwrapNullableType(type); type = GetDataContractAdapterType(type); if (!CollectionDataContract.TryCreateGetOnlyCollectionDataContract(type, out dataContract)) { ThrowInvalidDataContractException(SR.GetString("Type '{0}' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required.", type), type); } } } return dataContract; } internal static Type GetDataContractAdapterType(Type type) { if (type == Globals.TypeOfDateTimeOffset) { return Globals.TypeOfDateTimeOffsetAdapter; } return type; } internal static Type GetDataContractOriginalType(Type type) { if (type == Globals.TypeOfDateTimeOffsetAdapter) { return Globals.TypeOfDateTimeOffset; } return type; } private static RuntimeTypeHandle GetDataContractAdapterTypeHandle(RuntimeTypeHandle typeHandle) { if (Globals.TypeOfDateTimeOffset.TypeHandle.Equals(typeHandle)) { return Globals.TypeOfDateTimeOffsetAdapter.TypeHandle; } return typeHandle; } public static DataContract GetBuiltInDataContract(Type type) { if (type.IsInterface && !CollectionDataContract.IsCollectionInterface(type)) { type = Globals.TypeOfObject; } lock (initBuiltInContractsLock) { if (typeToBuiltInContract == null) { typeToBuiltInContract = new Dictionary(); } DataContract value = null; if (!typeToBuiltInContract.TryGetValue(type, out value)) { TryCreateBuiltInDataContract(type, out value); typeToBuiltInContract.Add(type, value); } return value; } } public static DataContract GetBuiltInDataContract(string name, string ns) { lock (initBuiltInContractsLock) { if (nameToBuiltInContract == null) { nameToBuiltInContract = new Dictionary(); } DataContract value = null; XmlQualifiedName key = new XmlQualifiedName(name, ns); if (!nameToBuiltInContract.TryGetValue(key, out value) && TryCreateBuiltInDataContract(name, ns, out value)) { nameToBuiltInContract.Add(key, value); } return value; } } public static DataContract GetBuiltInDataContract(string typeName) { if (!typeName.StartsWith("System.", StringComparison.Ordinal)) { return null; } lock (initBuiltInContractsLock) { if (typeNameToBuiltInContract == null) { typeNameToBuiltInContract = new Dictionary(); } DataContract value = null; if (!typeNameToBuiltInContract.TryGetValue(typeName, out value)) { Type type = null; switch (typeName.Substring(7)) { case "Char": type = typeof(char); break; case "Boolean": type = typeof(bool); break; case "SByte": type = typeof(sbyte); break; case "Byte": type = typeof(byte); break; case "Int16": type = typeof(short); break; case "UInt16": type = typeof(ushort); break; case "Int32": type = typeof(int); break; case "UInt32": type = typeof(uint); break; case "Int64": type = typeof(long); break; case "UInt64": type = typeof(ulong); break; case "Single": type = typeof(float); break; case "Double": type = typeof(double); break; case "Decimal": type = typeof(decimal); break; case "DateTime": type = typeof(DateTime); break; case "String": type = typeof(string); break; case "Byte[]": type = typeof(byte[]); break; case "Object": type = typeof(object); break; case "TimeSpan": type = typeof(TimeSpan); break; case "Guid": type = typeof(Guid); break; case "Uri": type = typeof(Uri); break; case "Xml.XmlQualifiedName": type = typeof(XmlQualifiedName); break; case "Enum": type = typeof(Enum); break; case "ValueType": type = typeof(ValueType); break; case "Array": type = typeof(Array); break; case "Xml.XmlElement": type = typeof(XmlElement); break; case "Xml.XmlNode[]": type = typeof(XmlNode[]); break; } if (type != null) { TryCreateBuiltInDataContract(type, out value); } typeNameToBuiltInContract.Add(typeName, value); } return value; } } public static bool TryCreateBuiltInDataContract(Type type, out DataContract dataContract) { if (type.IsEnum) { dataContract = null; return false; } dataContract = null; switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: dataContract = new BooleanDataContract(); break; case TypeCode.Byte: dataContract = new UnsignedByteDataContract(); break; case TypeCode.Char: dataContract = new CharDataContract(); break; case TypeCode.DateTime: dataContract = new DateTimeDataContract(); break; case TypeCode.Decimal: dataContract = new DecimalDataContract(); break; case TypeCode.Double: dataContract = new DoubleDataContract(); break; case TypeCode.Int16: dataContract = new ShortDataContract(); break; case TypeCode.Int32: dataContract = new IntDataContract(); break; case TypeCode.Int64: dataContract = new LongDataContract(); break; case TypeCode.SByte: dataContract = new SignedByteDataContract(); break; case TypeCode.Single: dataContract = new FloatDataContract(); break; case TypeCode.String: dataContract = new StringDataContract(); break; case TypeCode.UInt16: dataContract = new UnsignedShortDataContract(); break; case TypeCode.UInt32: dataContract = new UnsignedIntDataContract(); break; case TypeCode.UInt64: dataContract = new UnsignedLongDataContract(); break; default: if (type == typeof(byte[])) { dataContract = new ByteArrayDataContract(); } else if (type == typeof(object)) { dataContract = new ObjectDataContract(); } else if (type == typeof(Uri)) { dataContract = new UriDataContract(); } else if (type == typeof(XmlQualifiedName)) { dataContract = new QNameDataContract(); } else if (type == typeof(TimeSpan)) { dataContract = new TimeSpanDataContract(); } else if (type == typeof(Guid)) { dataContract = new GuidDataContract(); } else if (type == typeof(Enum) || type == typeof(ValueType)) { dataContract = new SpecialTypeDataContract(type, DictionaryGlobals.ObjectLocalName, DictionaryGlobals.SchemaNamespace); } else if (type == typeof(Array)) { dataContract = new CollectionDataContract(type); } else if (type == typeof(XmlElement) || type == typeof(XmlNode[])) { dataContract = new XmlDataContract(type); } break; } return dataContract != null; } public static bool TryCreateBuiltInDataContract(string name, string ns, out DataContract dataContract) { dataContract = null; if (ns == DictionaryGlobals.SchemaNamespace.Value) { if (DictionaryGlobals.BooleanLocalName.Value == name) { dataContract = new BooleanDataContract(); } else if (DictionaryGlobals.SignedByteLocalName.Value == name) { dataContract = new SignedByteDataContract(); } else if (DictionaryGlobals.UnsignedByteLocalName.Value == name) { dataContract = new UnsignedByteDataContract(); } else if (DictionaryGlobals.ShortLocalName.Value == name) { dataContract = new ShortDataContract(); } else if (DictionaryGlobals.UnsignedShortLocalName.Value == name) { dataContract = new UnsignedShortDataContract(); } else if (DictionaryGlobals.IntLocalName.Value == name) { dataContract = new IntDataContract(); } else if (DictionaryGlobals.UnsignedIntLocalName.Value == name) { dataContract = new UnsignedIntDataContract(); } else if (DictionaryGlobals.LongLocalName.Value == name) { dataContract = new LongDataContract(); } else if (DictionaryGlobals.integerLocalName.Value == name) { dataContract = new IntegerDataContract(); } else if (DictionaryGlobals.positiveIntegerLocalName.Value == name) { dataContract = new PositiveIntegerDataContract(); } else if (DictionaryGlobals.negativeIntegerLocalName.Value == name) { dataContract = new NegativeIntegerDataContract(); } else if (DictionaryGlobals.nonPositiveIntegerLocalName.Value == name) { dataContract = new NonPositiveIntegerDataContract(); } else if (DictionaryGlobals.nonNegativeIntegerLocalName.Value == name) { dataContract = new NonNegativeIntegerDataContract(); } else if (DictionaryGlobals.UnsignedLongLocalName.Value == name) { dataContract = new UnsignedLongDataContract(); } else if (DictionaryGlobals.FloatLocalName.Value == name) { dataContract = new FloatDataContract(); } else if (DictionaryGlobals.DoubleLocalName.Value == name) { dataContract = new DoubleDataContract(); } else if (DictionaryGlobals.DecimalLocalName.Value == name) { dataContract = new DecimalDataContract(); } else if (DictionaryGlobals.DateTimeLocalName.Value == name) { dataContract = new DateTimeDataContract(); } else if (DictionaryGlobals.StringLocalName.Value == name) { dataContract = new StringDataContract(); } else if (DictionaryGlobals.timeLocalName.Value == name) { dataContract = new TimeDataContract(); } else if (DictionaryGlobals.dateLocalName.Value == name) { dataContract = new DateDataContract(); } else if (DictionaryGlobals.hexBinaryLocalName.Value == name) { dataContract = new HexBinaryDataContract(); } else if (DictionaryGlobals.gYearMonthLocalName.Value == name) { dataContract = new GYearMonthDataContract(); } else if (DictionaryGlobals.gYearLocalName.Value == name) { dataContract = new GYearDataContract(); } else if (DictionaryGlobals.gMonthDayLocalName.Value == name) { dataContract = new GMonthDayDataContract(); } else if (DictionaryGlobals.gDayLocalName.Value == name) { dataContract = new GDayDataContract(); } else if (DictionaryGlobals.gMonthLocalName.Value == name) { dataContract = new GMonthDataContract(); } else if (DictionaryGlobals.normalizedStringLocalName.Value == name) { dataContract = new NormalizedStringDataContract(); } else if (DictionaryGlobals.tokenLocalName.Value == name) { dataContract = new TokenDataContract(); } else if (DictionaryGlobals.languageLocalName.Value == name) { dataContract = new LanguageDataContract(); } else if (DictionaryGlobals.NameLocalName.Value == name) { dataContract = new NameDataContract(); } else if (DictionaryGlobals.NCNameLocalName.Value == name) { dataContract = new NCNameDataContract(); } else if (DictionaryGlobals.XSDIDLocalName.Value == name) { dataContract = new IDDataContract(); } else if (DictionaryGlobals.IDREFLocalName.Value == name) { dataContract = new IDREFDataContract(); } else if (DictionaryGlobals.IDREFSLocalName.Value == name) { dataContract = new IDREFSDataContract(); } else if (DictionaryGlobals.ENTITYLocalName.Value == name) { dataContract = new ENTITYDataContract(); } else if (DictionaryGlobals.ENTITIESLocalName.Value == name) { dataContract = new ENTITIESDataContract(); } else if (DictionaryGlobals.NMTOKENLocalName.Value == name) { dataContract = new NMTOKENDataContract(); } else if (DictionaryGlobals.NMTOKENSLocalName.Value == name) { dataContract = new NMTOKENDataContract(); } else if (DictionaryGlobals.ByteArrayLocalName.Value == name) { dataContract = new ByteArrayDataContract(); } else if (DictionaryGlobals.ObjectLocalName.Value == name) { dataContract = new ObjectDataContract(); } else if (DictionaryGlobals.TimeSpanLocalName.Value == name) { dataContract = new XsDurationDataContract(); } else if (DictionaryGlobals.UriLocalName.Value == name) { dataContract = new UriDataContract(); } else if (DictionaryGlobals.QNameLocalName.Value == name) { dataContract = new QNameDataContract(); } } else if (ns == DictionaryGlobals.SerializationNamespace.Value) { if (DictionaryGlobals.TimeSpanLocalName.Value == name) { dataContract = new TimeSpanDataContract(); } else if (DictionaryGlobals.GuidLocalName.Value == name) { dataContract = new GuidDataContract(); } else if (DictionaryGlobals.CharLocalName.Value == name) { dataContract = new CharDataContract(); } else if ("ArrayOfanyType" == name) { dataContract = new CollectionDataContract(typeof(Array)); } } else if (ns == DictionaryGlobals.AsmxTypesNamespace.Value) { if (DictionaryGlobals.CharLocalName.Value == name) { dataContract = new AsmxCharDataContract(); } else if (DictionaryGlobals.GuidLocalName.Value == name) { dataContract = new AsmxGuidDataContract(); } } else if (ns == "http://schemas.datacontract.org/2004/07/System.Xml") { if (name == "XmlElement") { dataContract = new XmlDataContract(typeof(XmlElement)); } else if (name == "ArrayOfXmlNode") { dataContract = new XmlDataContract(typeof(XmlNode[])); } } return dataContract != null; } internal static string GetNamespace(string key) { lock (namespacesLock) { if (namespaces == null) { namespaces = new Dictionary(); } if (namespaces.TryGetValue(key, out var value)) { return value; } try { namespaces.Add(key, key); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } return key; } } internal static XmlDictionaryString GetClrTypeString(string key) { lock (clrTypeStringsLock) { if (clrTypeStrings == null) { clrTypeStringsDictionary = new XmlDictionary(); clrTypeStrings = new Dictionary(); try { clrTypeStrings.Add(Globals.TypeOfInt.Assembly.FullName, clrTypeStringsDictionary.Add("0")); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } } if (clrTypeStrings.TryGetValue(key, out var value)) { return value; } value = clrTypeStringsDictionary.Add(key); try { clrTypeStrings.Add(key, value); } catch (Exception ex2) { if (Fx.IsFatal(ex2)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex2.Message, ex2); } return value; } } internal static void ThrowInvalidDataContractException(string message, Type type) { if (type != null) { lock (cacheLock) { typeHandleRef.Value = GetDataContractAdapterTypeHandle(type.TypeHandle); try { typeToIDCache.Remove(typeHandleRef); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(message)); } internal DataContractCriticalHelper() { } internal DataContractCriticalHelper(Type type) { underlyingType = type; SetTypeForInitialization(type); isValueType = type.IsValueType; } [SecuritySafeCritical] private void SetTypeForInitialization(Type classType) { if (classType.IsSerializable || classType.IsDefined(Globals.TypeOfDataContractAttribute, inherit: false)) { typeForInitialization = classType; } } internal virtual void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString ns) { if (ns == DictionaryGlobals.SerializationNamespace && !IsPrimitive) { writer.WriteStartElement("z", name, ns); } else { writer.WriteStartElement(name, ns); } } internal void SetDataContractName(XmlQualifiedName stableName) { XmlDictionary xmlDictionary = new XmlDictionary(2); Name = xmlDictionary.Add(stableName.Name); Namespace = xmlDictionary.Add(stableName.Namespace); StableName = stableName; } internal void SetDataContractName(XmlDictionaryString name, XmlDictionaryString ns) { Name = name; Namespace = ns; StableName = CreateQualifiedName(name.Value, ns.Value); } internal void ThrowInvalidDataContractException(string message) { ThrowInvalidDataContractException(message, UnderlyingType); } } [SecurityCritical] private XmlDictionaryString name; [SecurityCritical] private XmlDictionaryString ns; [SecurityCritical] private DataContractCriticalHelper helper; protected DataContractCriticalHelper Helper { [SecurityCritical] get { return helper; } } internal Type UnderlyingType { [SecuritySafeCritical] get { return helper.UnderlyingType; } } internal Type OriginalUnderlyingType { [SecuritySafeCritical] get { return helper.OriginalUnderlyingType; } } internal virtual bool IsBuiltInDataContract { [SecuritySafeCritical] get { return helper.IsBuiltInDataContract; } } internal Type TypeForInitialization { [SecuritySafeCritical] get { return helper.TypeForInitialization; } } internal bool IsValueType { [SecuritySafeCritical] get { return helper.IsValueType; } [SecurityCritical] set { helper.IsValueType = value; } } internal bool IsReference { [SecuritySafeCritical] get { return helper.IsReference; } [SecurityCritical] set { helper.IsReference = value; } } internal XmlQualifiedName StableName { [SecuritySafeCritical] get { return helper.StableName; } [SecurityCritical] set { helper.StableName = value; } } internal GenericInfo GenericInfo { [SecuritySafeCritical] get { return helper.GenericInfo; } [SecurityCritical] set { helper.GenericInfo = value; } } internal virtual Dictionary KnownDataContracts { [SecuritySafeCritical] get { return helper.KnownDataContracts; } [SecurityCritical] set { helper.KnownDataContracts = value; } } internal virtual bool IsISerializable { [SecuritySafeCritical] get { return helper.IsISerializable; } [SecurityCritical] set { helper.IsISerializable = value; } } internal XmlDictionaryString Name { [SecuritySafeCritical] get { return name; } } public virtual XmlDictionaryString Namespace { [SecuritySafeCritical] get { return ns; } } internal virtual bool HasRoot { get { return true; } set { } } internal virtual XmlDictionaryString TopLevelElementName { [SecuritySafeCritical] get { return helper.TopLevelElementName; } [SecurityCritical] set { helper.TopLevelElementName = value; } } internal virtual XmlDictionaryString TopLevelElementNamespace { [SecuritySafeCritical] get { return helper.TopLevelElementNamespace; } [SecurityCritical] set { helper.TopLevelElementNamespace = value; } } internal virtual bool CanContainReferences => true; internal virtual bool IsPrimitive => false; internal MethodInfo ParseMethod { [SecuritySafeCritical] get { return helper.ParseMethod; } } [SecuritySafeCritical] protected DataContract(DataContractCriticalHelper helper) { this.helper = helper; name = helper.Name; ns = helper.Namespace; } internal static DataContract GetDataContract(Type type) { return GetDataContract(type.TypeHandle, type, SerializationMode.SharedContract); } internal static DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type, SerializationMode mode) { return GetDataContract(GetId(typeHandle), typeHandle, mode); } internal static DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle, SerializationMode mode) { return GetDataContractSkipValidation(id, typeHandle, null).GetValidContract(mode); } [SecuritySafeCritical] internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type) { return DataContractCriticalHelper.GetDataContractSkipValidation(id, typeHandle, type); } internal static DataContract GetGetOnlyCollectionDataContract(int id, RuntimeTypeHandle typeHandle, Type type, SerializationMode mode) { DataContract getOnlyCollectionDataContractSkipValidation = GetGetOnlyCollectionDataContractSkipValidation(id, typeHandle, type); getOnlyCollectionDataContractSkipValidation = getOnlyCollectionDataContractSkipValidation.GetValidContract(mode); if (getOnlyCollectionDataContractSkipValidation is ClassDataContract) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString("For '{0}' type, class data contract was returned for get-only collection.", GetClrTypeFullName(getOnlyCollectionDataContractSkipValidation.UnderlyingType)))); } return getOnlyCollectionDataContractSkipValidation; } [SecuritySafeCritical] internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type) { return DataContractCriticalHelper.GetGetOnlyCollectionDataContractSkipValidation(id, typeHandle, type); } [SecuritySafeCritical] internal static DataContract GetDataContractForInitialization(int id) { return DataContractCriticalHelper.GetDataContractForInitialization(id); } [SecuritySafeCritical] internal static int GetIdForInitialization(ClassDataContract classContract) { return DataContractCriticalHelper.GetIdForInitialization(classContract); } [SecuritySafeCritical] internal static int GetId(RuntimeTypeHandle typeHandle) { return DataContractCriticalHelper.GetId(typeHandle); } [SecuritySafeCritical] public static DataContract GetBuiltInDataContract(Type type) { return DataContractCriticalHelper.GetBuiltInDataContract(type); } [SecuritySafeCritical] public static DataContract GetBuiltInDataContract(string name, string ns) { return DataContractCriticalHelper.GetBuiltInDataContract(name, ns); } [SecuritySafeCritical] public static DataContract GetBuiltInDataContract(string typeName) { return DataContractCriticalHelper.GetBuiltInDataContract(typeName); } [SecuritySafeCritical] internal static string GetNamespace(string key) { return DataContractCriticalHelper.GetNamespace(key); } [SecuritySafeCritical] internal static XmlDictionaryString GetClrTypeString(string key) { return DataContractCriticalHelper.GetClrTypeString(key); } [SecuritySafeCritical] internal static void ThrowInvalidDataContractException(string message, Type type) { DataContractCriticalHelper.ThrowInvalidDataContractException(message, type); } public virtual void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("An internal error has occurred. Unexpected contract type '{0}' for type '{1}' encountered.", GetClrTypeFullName(GetType()), GetClrTypeFullName(UnderlyingType)))); } public virtual object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("An internal error has occurred. Unexpected contract type '{0}' for type '{1}' encountered.", GetClrTypeFullName(GetType()), GetClrTypeFullName(UnderlyingType)))); } internal virtual void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString ns) { if (ns == DictionaryGlobals.SerializationNamespace && !IsPrimitive) { writer.WriteStartElement("z", name, ns); } else { writer.WriteStartElement(name, ns); } } internal virtual DataContract BindGenericParameters(DataContract[] paramContracts, Dictionary boundContracts) { return this; } internal virtual DataContract GetValidContract(SerializationMode mode) { return this; } internal virtual DataContract GetValidContract() { return this; } internal virtual bool IsValidContract(SerializationMode mode) { return true; } internal static bool IsTypeSerializable(Type type) { return IsTypeSerializable(type, new Dictionary()); } private static bool IsTypeSerializable(Type type, Dictionary previousCollectionTypes) { if (type.IsSerializable || type.IsDefined(Globals.TypeOfDataContractAttribute, inherit: false) || type.IsInterface || type.IsPointer || Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) { return true; } if (CollectionDataContract.IsCollection(type, out var itemType)) { ValidatePreviousCollectionTypes(type, itemType, previousCollectionTypes); if (IsTypeSerializable(itemType, previousCollectionTypes)) { return true; } } if (GetBuiltInDataContract(type) == null) { return ClassDataContract.IsNonAttributedTypeValidForSerialization(type); } return true; } private static void ValidatePreviousCollectionTypes(Type collectionType, Type itemType, Dictionary previousCollectionTypes) { previousCollectionTypes.Add(collectionType, collectionType); while (itemType.IsArray) { itemType = itemType.GetElementType(); } List list = new List(); Queue queue = new Queue(); queue.Enqueue(itemType); list.Add(itemType); while (queue.Count > 0) { itemType = queue.Dequeue(); if (previousCollectionTypes.ContainsKey(itemType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Type '{0}' involves recursive collection.", GetClrTypeFullName(itemType)))); } if (!itemType.IsGenericType) { continue; } Type[] genericArguments = itemType.GetGenericArguments(); foreach (Type item in genericArguments) { if (!list.Contains(item)) { queue.Enqueue(item); list.Add(item); } } } } internal static Type UnwrapRedundantNullableType(Type type) { Type result = type; while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) { result = type; type = type.GetGenericArguments()[0]; } return result; } internal static Type UnwrapNullableType(Type type) { while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) { type = type.GetGenericArguments()[0]; } return type; } private static bool IsAlpha(char ch) { if (ch < 'A' || ch > 'Z') { if (ch >= 'a') { return ch <= 'z'; } return false; } return true; } private static bool IsDigit(char ch) { if (ch >= '0') { return ch <= '9'; } return false; } private static bool IsAsciiLocalName(string localName) { if (localName.Length == 0) { return false; } if (!IsAlpha(localName[0])) { return false; } for (int i = 1; i < localName.Length; i++) { char ch = localName[i]; if (!IsAlpha(ch) && !IsDigit(ch)) { return false; } } return true; } internal static string EncodeLocalName(string localName) { if (IsAsciiLocalName(localName)) { return localName; } if (IsValidNCName(localName)) { return localName; } return XmlConvert.EncodeLocalName(localName); } internal static bool IsValidNCName(string name) { try { XmlConvert.VerifyNCName(name); return true; } catch (XmlException) { return false; } } internal static XmlQualifiedName GetStableName(Type type) { bool hasDataContract; return GetStableName(type, out hasDataContract); } internal static XmlQualifiedName GetStableName(Type type, out bool hasDataContract) { return GetStableName(type, new Dictionary(), out hasDataContract); } private static XmlQualifiedName GetStableName(Type type, Dictionary previousCollectionTypes, out bool hasDataContract) { type = UnwrapRedundantNullableType(type); DataContractAttribute dataContractAttribute; if (TryGetBuiltInXmlAndArrayTypeStableName(type, previousCollectionTypes, out var stableName)) { hasDataContract = false; } else if (TryGetDCAttribute(type, out dataContractAttribute)) { stableName = GetDCTypeStableName(type, dataContractAttribute); hasDataContract = true; } else { stableName = GetNonDCTypeStableName(type, previousCollectionTypes); hasDataContract = false; } return stableName; } private static XmlQualifiedName GetDCTypeStableName(Type type, DataContractAttribute dataContractAttribute) { string text = null; string text2 = null; if (dataContractAttribute.IsNameSetExplicitly) { text = dataContractAttribute.Name; if (text == null || text.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Type '{0}' cannot have DataContractAttribute attribute Name set to null or empty string.", GetClrTypeFullName(type)))); } if (type.IsGenericType && !type.IsGenericTypeDefinition) { text = ExpandGenericParameters(text, type); } text = EncodeLocalName(text); } else { text = GetDefaultStableLocalName(type); } if (dataContractAttribute.IsNamespaceSetExplicitly) { text2 = dataContractAttribute.Namespace; if (text2 == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Type '{0}' cannot have DataContractAttribute attribute Namespace set to null.", GetClrTypeFullName(type)))); } CheckExplicitDataContractNamespaceUri(text2, type); } else { text2 = GetDefaultDataContractNamespace(type); } return CreateQualifiedName(text, text2); } private static XmlQualifiedName GetNonDCTypeStableName(Type type, Dictionary previousCollectionTypes) { string text = null; if (CollectionDataContract.IsCollection(type, out var itemType)) { ValidatePreviousCollectionTypes(type, itemType, previousCollectionTypes); CollectionDataContractAttribute collectionContractAttribute; return GetCollectionStableName(type, itemType, previousCollectionTypes, out collectionContractAttribute); } string defaultStableLocalName = GetDefaultStableLocalName(type); text = ((!ClassDataContract.IsNonAttributedTypeValidForSerialization(type)) ? GetDefaultStableNamespace(type) : GetDefaultDataContractNamespace(type)); return CreateQualifiedName(defaultStableLocalName, text); } private static bool TryGetBuiltInXmlAndArrayTypeStableName(Type type, Dictionary previousCollectionTypes, out XmlQualifiedName stableName) { stableName = null; DataContract builtInDataContract = GetBuiltInDataContract(type); if (builtInDataContract != null) { stableName = builtInDataContract.StableName; } else if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) { SchemaExporter.GetXmlTypeInfo(type, out var stableName2, out var _, out var _); stableName = stableName2; } else if (type.IsArray) { Type elementType = type.GetElementType(); ValidatePreviousCollectionTypes(type, elementType, previousCollectionTypes); stableName = GetCollectionStableName(type, elementType, previousCollectionTypes, out var _); } return stableName != null; } [SecuritySafeCritical] internal static bool TryGetDCAttribute(Type type, out DataContractAttribute dataContractAttribute) { dataContractAttribute = null; object[] customAttributes = type.GetCustomAttributes(Globals.TypeOfDataContractAttribute, inherit: false); if (customAttributes != null && customAttributes.Length != 0) { dataContractAttribute = (DataContractAttribute)customAttributes[0]; } return dataContractAttribute != null; } internal static XmlQualifiedName GetCollectionStableName(Type type, Type itemType, out CollectionDataContractAttribute collectionContractAttribute) { return GetCollectionStableName(type, itemType, new Dictionary(), out collectionContractAttribute); } private static XmlQualifiedName GetCollectionStableName(Type type, Type itemType, Dictionary previousCollectionTypes, out CollectionDataContractAttribute collectionContractAttribute) { object[] customAttributes = type.GetCustomAttributes(Globals.TypeOfCollectionDataContractAttribute, inherit: false); string text; string text2; if (customAttributes != null && customAttributes.Length != 0) { collectionContractAttribute = (CollectionDataContractAttribute)customAttributes[0]; if (collectionContractAttribute.IsNameSetExplicitly) { text = collectionContractAttribute.Name; if (text == null || text.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Type '{0}' cannot have CollectionDataContractAttribute attribute Name set to null or empty string.", GetClrTypeFullName(type)))); } if (type.IsGenericType && !type.IsGenericTypeDefinition) { text = ExpandGenericParameters(text, type); } text = EncodeLocalName(text); } else { text = GetDefaultStableLocalName(type); } if (collectionContractAttribute.IsNamespaceSetExplicitly) { text2 = collectionContractAttribute.Namespace; if (text2 == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Type '{0}' cannot have CollectionDataContractAttribute attribute Namespace set to null.", GetClrTypeFullName(type)))); } CheckExplicitDataContractNamespaceUri(text2, type); } else { text2 = GetDefaultDataContractNamespace(type); } } else { collectionContractAttribute = null; string text3 = "ArrayOf" + GetArrayPrefix(ref itemType); bool hasDataContract; XmlQualifiedName stableName = GetStableName(itemType, previousCollectionTypes, out hasDataContract); text = text3 + stableName.Name; text2 = GetCollectionNamespace(stableName.Namespace); } return CreateQualifiedName(text, text2); } private static string GetArrayPrefix(ref Type itemType) { string text = string.Empty; while (itemType.IsArray && GetBuiltInDataContract(itemType) == null) { text += "ArrayOf"; itemType = itemType.GetElementType(); } return text; } internal XmlQualifiedName GetArrayTypeName(bool isNullable) { XmlQualifiedName xmlQualifiedName; if (IsValueType && isNullable) { GenericInfo genericInfo = new GenericInfo(GetStableName(Globals.TypeOfNullable), Globals.TypeOfNullable.FullName); genericInfo.Add(new GenericInfo(StableName, null)); genericInfo.AddToLevel(0, 1); xmlQualifiedName = genericInfo.GetExpandedStableName(); } else { xmlQualifiedName = StableName; } string collectionNamespace = GetCollectionNamespace(xmlQualifiedName.Namespace); return new XmlQualifiedName("ArrayOf" + xmlQualifiedName.Name, collectionNamespace); } internal static string GetCollectionNamespace(string elementNs) { if (!IsBuiltInNamespace(elementNs)) { return elementNs; } return "http://schemas.microsoft.com/2003/10/Serialization/Arrays"; } internal static XmlQualifiedName GetDefaultStableName(Type type) { return CreateQualifiedName(GetDefaultStableLocalName(type), GetDefaultStableNamespace(type)); } private static string GetDefaultStableLocalName(Type type) { if (type.IsGenericParameter) { return "{" + type.GenericParameterPosition + "}"; } string text = null; if (type.IsArray) { text = GetArrayPrefix(ref type); } string text2; if (type.DeclaringType == null) { text2 = type.Name; } else { int num = ((type.Namespace != null) ? type.Namespace.Length : 0); if (num > 0) { num++; } text2 = GetClrTypeFullName(type).Substring(num).Replace('+', '.'); } if (text != null) { text2 = text + text2; } if (type.IsGenericType) { StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder2 = new StringBuilder(); bool flag = true; int num2 = text2.IndexOf('['); if (num2 >= 0) { text2 = text2.Substring(0, num2); } IList dataContractNameForGenericName = GetDataContractNameForGenericName(text2, stringBuilder); bool isGenericTypeDefinition = type.IsGenericTypeDefinition; Type[] genericArguments = type.GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { Type type2 = genericArguments[i]; if (isGenericTypeDefinition) { stringBuilder.Append("{").Append(i).Append("}"); continue; } XmlQualifiedName stableName = GetStableName(type2); stringBuilder.Append(stableName.Name); stringBuilder2.Append(" ").Append(stableName.Namespace); if (flag) { flag = IsBuiltInNamespace(stableName.Namespace); } } if (isGenericTypeDefinition) { stringBuilder.Append("{#}"); } else if (dataContractNameForGenericName.Count > 1 || !flag) { foreach (int item in dataContractNameForGenericName) { stringBuilder2.Insert(0, item).Insert(0, " "); } stringBuilder.Append(GetNamespacesDigest(stringBuilder2.ToString())); } text2 = stringBuilder.ToString(); } return EncodeLocalName(text2); } private static string GetDefaultDataContractNamespace(Type type) { string text = type.Namespace; if (text == null) { text = string.Empty; } string text2 = GetGlobalDataContractNamespace(text, ((MemberInfo)type).Module); if (text2 == null) { text2 = GetGlobalDataContractNamespace(text, type.Assembly); } if (text2 == null) { text2 = GetDefaultStableNamespace(type); } else { CheckExplicitDataContractNamespaceUri(text2, type); } return text2; } internal static IList GetDataContractNameForGenericName(string typeName, StringBuilder localName) { List list = new List(); int num = 0; while (true) { int num2 = typeName.IndexOf('`', num); if (num2 < 0) { localName?.Append(typeName.Substring(num)); list.Add(0); break; } localName?.Append(typeName.Substring(num, num2 - num)); while ((num = typeName.IndexOf('.', num + 1, num2 - num - 1)) >= 0) { list.Add(0); } num = typeName.IndexOf('.', num2); if (num < 0) { list.Add(int.Parse(typeName.Substring(num2 + 1), CultureInfo.InvariantCulture)); break; } list.Add(int.Parse(typeName.Substring(num2 + 1, num - num2 - 1), CultureInfo.InvariantCulture)); } localName?.Append("Of"); return list; } internal static bool IsBuiltInNamespace(string ns) { if (!(ns == "http://www.w3.org/2001/XMLSchema")) { return ns == "http://schemas.microsoft.com/2003/10/Serialization/"; } return true; } internal static string GetDefaultStableNamespace(Type type) { if (type.IsGenericParameter) { return "{ns}"; } return GetDefaultStableNamespace(type.Namespace); } internal static XmlQualifiedName CreateQualifiedName(string localName, string ns) { return new XmlQualifiedName(localName, GetNamespace(ns)); } internal static string GetDefaultStableNamespace(string clrNs) { if (clrNs == null) { clrNs = string.Empty; } return new Uri(Globals.DataContractXsdBaseNamespaceUri, clrNs).AbsoluteUri; } private static void CheckExplicitDataContractNamespaceUri(string dataContractNs, Type type) { if (dataContractNs.Length > 0) { string text = dataContractNs.Trim(); if (text.Length == 0 || text.IndexOf("##", StringComparison.Ordinal) != -1) { ThrowInvalidDataContractException(SR.GetString("DataContract namespace '{0}' is not a valid URI.", dataContractNs), type); } dataContractNs = text; } if (Uri.TryCreate(dataContractNs, UriKind.RelativeOrAbsolute, out Uri result)) { if (result.ToString() == "http://schemas.microsoft.com/2003/10/Serialization/") { ThrowInvalidDataContractException(SR.GetString("DataContract namespace '{0}' cannot be specified since it is reserved.", "http://schemas.microsoft.com/2003/10/Serialization/"), type); } } else { ThrowInvalidDataContractException(SR.GetString("DataContract namespace '{0}' is not a valid URI.", dataContractNs), type); } } internal static string GetClrTypeFullName(Type type) { if (type.IsGenericTypeDefinition || !type.ContainsGenericParameters) { return type.FullName; } return string.Format(CultureInfo.InvariantCulture, "{0}.{1}", type.Namespace, type.Name); } internal static string GetClrAssemblyName(Type type, out bool hasTypeForwardedFrom) { hasTypeForwardedFrom = false; object[] customAttributes = type.GetCustomAttributes(typeof(TypeForwardedFromAttribute), inherit: false); if (customAttributes != null && customAttributes.Length != 0) { TypeForwardedFromAttribute obj = (TypeForwardedFromAttribute)customAttributes[0]; hasTypeForwardedFrom = true; return obj.AssemblyFullName; } return type.Assembly.FullName; } internal static string GetClrTypeFullNameUsingTypeForwardedFromAttribute(Type type) { if (type.IsArray) { return GetClrTypeFullNameForArray(type); } return GetClrTypeFullNameForNonArrayTypes(type); } private static string GetClrTypeFullNameForArray(Type type) { return string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", GetClrTypeFullNameUsingTypeForwardedFromAttribute(type.GetElementType()), "[", "]"); } private static string GetClrTypeFullNameForNonArrayTypes(Type type) { if (!type.IsGenericType) { return GetClrTypeFullName(type); } Type[] genericArguments = type.GetGenericArguments(); StringBuilder stringBuilder = new StringBuilder(type.GetGenericTypeDefinition().FullName).Append("["); Type[] array = genericArguments; foreach (Type type2 in array) { stringBuilder.Append("[").Append(GetClrTypeFullNameUsingTypeForwardedFromAttribute(type2)).Append(","); stringBuilder.Append(" ").Append(GetClrAssemblyName(type2, out var _)); stringBuilder.Append("]").Append(","); } return stringBuilder.Remove(stringBuilder.Length - 1, 1).Append("]").ToString(); } internal static void GetClrNameAndNamespace(string fullTypeName, out string localName, out string ns) { int num = fullTypeName.LastIndexOf('.'); if (num < 0) { ns = string.Empty; localName = fullTypeName.Replace('+', '.'); } else { ns = fullTypeName.Substring(0, num); localName = fullTypeName.Substring(num + 1).Replace('+', '.'); } int num2 = localName.IndexOf('['); if (num2 >= 0) { localName = localName.Substring(0, num2); } } internal static void GetDefaultStableName(string fullTypeName, out string localName, out string ns) { GetDefaultStableName(new CodeTypeReference(fullTypeName), out localName, out ns); } private static void GetDefaultStableName(CodeTypeReference typeReference, out string localName, out string ns) { string baseType = typeReference.BaseType; DataContract builtInDataContract = GetBuiltInDataContract(baseType); if (builtInDataContract != null) { localName = builtInDataContract.StableName.Name; ns = builtInDataContract.StableName.Namespace; return; } GetClrNameAndNamespace(baseType, out localName, out ns); if (typeReference.TypeArguments.Count > 0) { StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder2 = new StringBuilder(); bool flag = true; IList dataContractNameForGenericName = GetDataContractNameForGenericName(localName, stringBuilder); foreach (CodeTypeReference typeArgument in typeReference.TypeArguments) { GetDefaultStableName(typeArgument, out var localName2, out var value); stringBuilder.Append(localName2); stringBuilder2.Append(" ").Append(value); if (flag) { flag = IsBuiltInNamespace(value); } } if (dataContractNameForGenericName.Count > 1 || !flag) { foreach (int item in dataContractNameForGenericName) { stringBuilder2.Insert(0, item).Insert(0, " "); } stringBuilder.Append(GetNamespacesDigest(stringBuilder2.ToString())); } localName = stringBuilder.ToString(); } localName = EncodeLocalName(localName); ns = GetDefaultStableNamespace(ns); } internal static string GetDataContractNamespaceFromUri(string uriString) { if (!uriString.StartsWith("http://schemas.datacontract.org/2004/07/", StringComparison.Ordinal)) { return uriString; } return uriString.Substring("http://schemas.datacontract.org/2004/07/".Length); } private static string GetGlobalDataContractNamespace(string clrNs, ICustomAttributeProvider customAttribuetProvider) { object[] customAttributes = customAttribuetProvider.GetCustomAttributes(typeof(ContractNamespaceAttribute), inherit: false); string text = null; for (int i = 0; i < customAttributes.Length; i++) { ContractNamespaceAttribute contractNamespaceAttribute = (ContractNamespaceAttribute)customAttributes[i]; string text2 = contractNamespaceAttribute.ClrNamespace; if (text2 == null) { text2 = string.Empty; } if (text2 == clrNs) { if (contractNamespaceAttribute.ContractNamespace == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("CLR namespace '{0}' cannot have ContractNamespace set to null.", clrNs))); } if (text != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("ContractNamespaceAttribute attribute maps CLR namespace '{2}' to multiple data contract namespaces '{0}' and '{1}'. You can map a CLR namespace to only one data contract namespace.", text, contractNamespaceAttribute.ContractNamespace, clrNs))); } text = contractNamespaceAttribute.ContractNamespace; } } return text; } private static string GetNamespacesDigest(string namespaces) { byte[] inArray = HashHelper.ComputeHash(Encoding.UTF8.GetBytes(namespaces)); char[] array = new char[24]; int num = Convert.ToBase64CharArray(inArray, 0, 6, array, 0); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < num; i++) { char c = array[i]; switch (c) { case '/': stringBuilder.Append("_S"); break; case '+': stringBuilder.Append("_P"); break; default: stringBuilder.Append(c); break; case '=': break; } } return stringBuilder.ToString(); } private static string ExpandGenericParameters(string format, Type type) { GenericNameProvider genericNameProvider = new GenericNameProvider(type); return ExpandGenericParameters(format, genericNameProvider); } internal static string ExpandGenericParameters(string format, IGenericNameProvider genericNameProvider) { string text = null; StringBuilder stringBuilder = new StringBuilder(); IList nestedParameterCounts = genericNameProvider.GetNestedParameterCounts(); for (int i = 0; i < format.Length; i++) { char c = format[i]; if (c == '{') { i++; int num = i; for (; i < format.Length && format[i] != '}'; i++) { } if (i == format.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("The data contract name '{0}' for type '{1}' has a curly brace '{{' that is not matched with a closing curly brace. Curly braces have special meaning in data contract names - they are used to customize the naming of data contracts for generic types.", format, genericNameProvider.GetGenericTypeName()))); } if (format[num] == '#' && i == num + 1) { if (nestedParameterCounts.Count <= 1 && genericNameProvider.ParametersFromBuiltInNamespaces) { continue; } if (text == null) { StringBuilder stringBuilder2 = new StringBuilder(genericNameProvider.GetNamespaces()); foreach (int item in nestedParameterCounts) { stringBuilder2.Insert(0, item).Insert(0, " "); } text = GetNamespacesDigest(stringBuilder2.ToString()); } stringBuilder.Append(text); } else { if (!int.TryParse(format.Substring(num, i - num), out var result) || result < 0 || result >= genericNameProvider.GetParameterCount()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("In the data contract name for type '{1}', there are curly braces with '{0}' inside, which is an invalid value. Curly braces have special meaning in data contract names - they are used to customize the naming of data contracts for generic types. Based on the number of generic parameters this type has, the contents of the curly braces must either be a number between 0 and '{2}' to insert the name of the generic parameter at that index or the '#' symbol to insert a digest of the generic parameter namespaces.", format.Substring(num, i - num), genericNameProvider.GetGenericTypeName(), genericNameProvider.GetParameterCount() - 1))); } stringBuilder.Append(genericNameProvider.GetParameterName(result)); } } else { stringBuilder.Append(c); } } return stringBuilder.ToString(); } internal static bool IsTypeNullable(Type type) { if (type.IsValueType) { if (type.IsGenericType) { return type.GetGenericTypeDefinition() == Globals.TypeOfNullable; } return false; } return true; } public static void ThrowTypeNotSerializable(Type type) { ThrowInvalidDataContractException(SR.GetString("Type '{0}' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required.", type), type); } internal static Dictionary ImportKnownTypeAttributes(Type type) { Dictionary knownDataContracts = null; Dictionary typesChecked = new Dictionary(); ImportKnownTypeAttributes(type, typesChecked, ref knownDataContracts); return knownDataContracts; } private static void ImportKnownTypeAttributes(Type type, Dictionary typesChecked, ref Dictionary knownDataContracts) { if (TD.ImportKnownTypesStartIsEnabled()) { TD.ImportKnownTypesStart(); } while (type != null && IsTypeSerializable(type)) { if (typesChecked.ContainsKey(type)) { return; } typesChecked.Add(type, type); object[] customAttributes = type.GetCustomAttributes(Globals.TypeOfKnownTypeAttribute, inherit: false); if (customAttributes != null) { bool flag = false; bool flag2 = false; for (int i = 0; i < customAttributes.Length; i++) { KnownTypeAttribute knownTypeAttribute = (KnownTypeAttribute)customAttributes[i]; if (knownTypeAttribute.Type != null) { if (flag) { ThrowInvalidDataContractException(SR.GetString("Type '{0}': If a KnownTypeAttribute attribute specifies a method it must be the only KnownTypeAttribute attribute on that type.", GetClrTypeFullName(type)), type); } CheckAndAdd(knownTypeAttribute.Type, typesChecked, ref knownDataContracts); flag2 = true; continue; } if (flag || flag2) { ThrowInvalidDataContractException(SR.GetString("Type '{0}': If a KnownTypeAttribute attribute specifies a method it must be the only KnownTypeAttribute attribute on that type.", GetClrTypeFullName(type)), type); } string methodName = knownTypeAttribute.MethodName; if (methodName == null) { ThrowInvalidDataContractException(SR.GetString("KnownTypeAttribute attribute on type '{0}' contains no data.", GetClrTypeFullName(type)), type); } if (methodName.Length == 0) { ThrowInvalidDataContractException(SR.GetString("Method name specified by KnownTypeAttribute attribute on type '{0}' cannot be the empty string.", GetClrTypeFullName(type)), type); } MethodInfo method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, Globals.EmptyTypeArray, null); if (method == null) { ThrowInvalidDataContractException(SR.GetString("KnownTypeAttribute attribute on type '{1}' specifies a method named '{0}' to provide known types. Static method '{0}()' was not found on this type. Ensure that the method exists and is marked as static.", methodName, GetClrTypeFullName(type)), type); } if (!Globals.TypeOfTypeEnumerable.IsAssignableFrom(method.ReturnType)) { ThrowInvalidDataContractException(SR.GetString("KnownTypeAttribute attribute on type '{0}' specifies a method named '{1}' to provide known types. The return type of this method is invalid because it is not assignable to IEnumerable. Ensure that the method exists and has a valid signature.", GetClrTypeFullName(type), methodName), type); } object obj = method.Invoke(null, Globals.EmptyObjectArray); if (obj == null) { ThrowInvalidDataContractException(SR.GetString("Method specified by KnownTypeAttribute attribute on type '{0}' returned null.", GetClrTypeFullName(type)), type); } foreach (Type item in (IEnumerable)obj) { if (item == null) { ThrowInvalidDataContractException(SR.GetString("Method specified by KnownTypeAttribute attribute on type '{0}' does not expose valid types.", GetClrTypeFullName(type)), type); } CheckAndAdd(item, typesChecked, ref knownDataContracts); } flag = true; } } LoadKnownTypesFromConfig(type, typesChecked, ref knownDataContracts); type = type.BaseType; } if (TD.ImportKnownTypesStopIsEnabled()) { TD.ImportKnownTypesStop(); } } [SecuritySafeCritical] private static void LoadKnownTypesFromConfig(Type type, Dictionary typesChecked, ref Dictionary knownDataContracts) { } private static void CheckRootTypeInConfigIsGeneric(Type type, ref Type rootType, ref Type[] genArgs) { if (rootType.IsGenericType) { if (!rootType.ContainsGenericParameters) { genArgs = rootType.GetGenericArguments(); rootType = rootType.GetGenericTypeDefinition(); } else { ThrowInvalidDataContractException(SR.GetString("Error while getting known types for Type '{0}'. The type must not be an open or partial generic class.", type), type); } } } private static bool IsElemTypeNullOrNotEqualToRootType(string elemTypeName, Type rootType) { Type type = Type.GetType(elemTypeName, throwOnError: false); if (type == null || !rootType.Equals(type)) { return true; } return false; } private static bool IsCollectionElementTypeEqualToRootType(string collectionElementTypeName, Type rootType) { if (collectionElementTypeName.StartsWith(GetClrTypeFullName(rootType), StringComparison.Ordinal)) { Type type = Type.GetType(collectionElementTypeName, throwOnError: false); if (type != null) { if (type.IsGenericType && !IsOpenGenericType(type)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString("Declared type '{0}' in config cannot be a closed or partial generic type.", collectionElementTypeName))); } if (rootType.Equals(type)) { return true; } } } return false; } [SecurityCritical] [SecurityTreatAsSafe] internal static void CheckAndAdd(Type type, Dictionary typesChecked, ref Dictionary nameToDataContractTable) { type = UnwrapNullableType(type); DataContract dataContract = GetDataContract(type); DataContract value; if (nameToDataContractTable == null) { nameToDataContractTable = new Dictionary(); } else if (nameToDataContractTable.TryGetValue(dataContract.StableName, out value)) { if (value.UnderlyingType != DataContractCriticalHelper.GetDataContractAdapterType(type)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString("Type '{0}' cannot be added to list of known types since another type '{1}' with the same data contract name '{2}:{3}' is already present.", type, value.UnderlyingType, dataContract.StableName.Namespace, dataContract.StableName.Name))); } return; } nameToDataContractTable.Add(dataContract.StableName, dataContract); ImportKnownTypeAttributes(type, typesChecked, ref nameToDataContractTable); } private static bool IsOpenGenericType(Type t) { Type[] genericArguments = t.GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { if (!genericArguments[i].IsGenericParameter) { return false; } } return true; } public sealed override bool Equals(object other) { if (this == other) { return true; } return Equals(other, new Dictionary()); } internal virtual bool Equals(object other, Dictionary checkedContracts) { if (other is DataContract dataContract) { if (StableName.Name == dataContract.StableName.Name && StableName.Namespace == dataContract.StableName.Namespace) { return IsReference == dataContract.IsReference; } return false; } return false; } internal bool IsEqualOrChecked(object other, Dictionary checkedContracts) { if (this == other) { return true; } if (checkedContracts != null) { DataContractPairKey key = new DataContractPairKey(this, other); if (checkedContracts.ContainsKey(key)) { return true; } checkedContracts.Add(key, null); } return false; } public override int GetHashCode() { return base.GetHashCode(); } internal void ThrowInvalidDataContractException(string message) { ThrowInvalidDataContractException(message, UnderlyingType); } internal static bool IsTypeVisible(Type t) { return true; } } internal interface IGenericNameProvider { bool ParametersFromBuiltInNamespaces { get; } int GetParameterCount(); IList GetNestedParameterCounts(); string GetParameterName(int paramIndex); string GetNamespaces(); string GetGenericTypeName(); } internal class GenericNameProvider : IGenericNameProvider { private string genericTypeName; private object[] genericParams; private IList nestedParamCounts; public bool ParametersFromBuiltInNamespaces { get { bool flag = true; for (int i = 0; i < GetParameterCount(); i++) { if (!flag) { break; } flag = DataContract.IsBuiltInNamespace(GetStableName(i).Namespace); } return flag; } } internal GenericNameProvider(Type type) : this(DataContract.GetClrTypeFullName(type.GetGenericTypeDefinition()), type.GetGenericArguments()) { } internal GenericNameProvider(string genericTypeName, object[] genericParams) { this.genericTypeName = genericTypeName; this.genericParams = new object[genericParams.Length]; genericParams.CopyTo(this.genericParams, 0); DataContract.GetClrNameAndNamespace(genericTypeName, out var localName, out var _); nestedParamCounts = DataContract.GetDataContractNameForGenericName(localName, null); } public int GetParameterCount() { return genericParams.Length; } public IList GetNestedParameterCounts() { return nestedParamCounts; } public string GetParameterName(int paramIndex) { return GetStableName(paramIndex).Name; } public string GetNamespaces() { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < GetParameterCount(); i++) { stringBuilder.Append(" ").Append(GetStableName(i).Namespace); } return stringBuilder.ToString(); } public string GetGenericTypeName() { return genericTypeName; } private XmlQualifiedName GetStableName(int i) { object obj = genericParams[i]; XmlQualifiedName xmlQualifiedName = obj as XmlQualifiedName; if (xmlQualifiedName == null) { Type type = obj as Type; xmlQualifiedName = (XmlQualifiedName)((type != null) ? (genericParams[i] = DataContract.GetStableName(type)) : (genericParams[i] = ((DataContract)obj).StableName)); } return xmlQualifiedName; } } internal class GenericInfo : IGenericNameProvider { private string genericTypeName; private XmlQualifiedName stableName; private List paramGenericInfos; private List nestedParamCounts; internal XmlQualifiedName StableName => stableName; internal IList Parameters => paramGenericInfos; public bool ParametersFromBuiltInNamespaces { get { bool flag = true; for (int i = 0; i < paramGenericInfos.Count; i++) { if (!flag) { break; } flag = DataContract.IsBuiltInNamespace(paramGenericInfos[i].GetStableNamespace()); } return flag; } } internal GenericInfo(XmlQualifiedName stableName, string genericTypeName) { this.stableName = stableName; this.genericTypeName = genericTypeName; nestedParamCounts = new List(); nestedParamCounts.Add(0); } internal void Add(GenericInfo actualParamInfo) { if (paramGenericInfos == null) { paramGenericInfos = new List(); } paramGenericInfos.Add(actualParamInfo); } internal void AddToLevel(int level, int count) { if (level >= nestedParamCounts.Count) { do { nestedParamCounts.Add((level == nestedParamCounts.Count) ? count : 0); } while (level >= nestedParamCounts.Count); } else { nestedParamCounts[level] += count; } } internal XmlQualifiedName GetExpandedStableName() { if (paramGenericInfos == null) { return stableName; } return new XmlQualifiedName(DataContract.EncodeLocalName(DataContract.ExpandGenericParameters(XmlConvert.DecodeName(stableName.Name), this)), stableName.Namespace); } internal string GetStableNamespace() { return stableName.Namespace; } public int GetParameterCount() { return paramGenericInfos.Count; } public IList GetNestedParameterCounts() { return nestedParamCounts; } public string GetParameterName(int paramIndex) { return paramGenericInfos[paramIndex].GetExpandedStableName().Name; } public string GetNamespaces() { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < paramGenericInfos.Count; i++) { stringBuilder.Append(" ").Append(paramGenericInfos[i].GetStableNamespace()); } return stringBuilder.ToString(); } public string GetGenericTypeName() { return genericTypeName; } } internal class DataContractPairKey { private object object1; private object object2; public DataContractPairKey(object object1, object object2) { this.object1 = object1; this.object2 = object2; } public override bool Equals(object other) { if (!(other is DataContractPairKey dataContractPairKey)) { return false; } if (dataContractPairKey.object1 != object1 || dataContractPairKey.object2 != object2) { if (dataContractPairKey.object1 == object2) { return dataContractPairKey.object2 == object1; } return false; } return true; } public override int GetHashCode() { return object1.GetHashCode() ^ object2.GetHashCode(); } } internal class TypeHandleRefEqualityComparer : IEqualityComparer { public bool Equals(TypeHandleRef x, TypeHandleRef y) { return x.Value.Equals(y.Value); } public int GetHashCode(TypeHandleRef obj) { return obj.Value.GetHashCode(); } } internal class TypeHandleRef { private RuntimeTypeHandle value; public RuntimeTypeHandle Value { get { return value; } set { this.value = value; } } public TypeHandleRef() { } public TypeHandleRef(RuntimeTypeHandle value) { this.value = value; } } internal class IntRef { private int value; public int Value => value; public IntRef(int value) { this.value = value; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, Inherited = false, AllowMultiple = false)] public sealed class DataContractAttribute : Attribute { private string name; private string ns; private bool isNameSetExplicitly; private bool isNamespaceSetExplicitly; private bool isReference; private bool isReferenceSetExplicitly; public bool IsReference { get { return isReference; } set { isReference = value; isReferenceSetExplicitly = true; } } public bool IsReferenceSetExplicitly => isReferenceSetExplicitly; public string Namespace { get { return ns; } set { ns = value; isNamespaceSetExplicitly = true; } } public bool IsNamespaceSetExplicitly => isNamespaceSetExplicitly; public string Name { get { return name; } set { name = value; isNameSetExplicitly = true; } } public bool IsNameSetExplicitly => isNameSetExplicitly; } public abstract class DataContractResolver { public abstract bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace); public abstract Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver); } public sealed class DataContractSerializer : XmlObjectSerializer { private Type rootType; private DataContract rootContract; private bool needsContractNsAtRoot; private XmlDictionaryString rootName; private XmlDictionaryString rootNamespace; private int maxItemsInObjectGraph; private bool ignoreExtensionDataObject; private bool preserveObjectReferences; private IDataContractSurrogate dataContractSurrogate; private ReadOnlyCollection knownTypeCollection; internal IList knownTypeList; internal Dictionary knownDataContracts; private DataContractResolver dataContractResolver; private bool serializeReadOnlyTypes; public ReadOnlyCollection KnownTypes { get { if (knownTypeCollection == null) { if (knownTypeList != null) { knownTypeCollection = new ReadOnlyCollection(knownTypeList); } else { knownTypeCollection = new ReadOnlyCollection(Globals.EmptyTypeArray); } } return knownTypeCollection; } } internal override Dictionary KnownDataContracts { get { if (knownDataContracts == null && knownTypeList != null) { knownDataContracts = XmlObjectSerializerContext.GetDataContractsForKnownTypes(knownTypeList); } return knownDataContracts; } } public int MaxItemsInObjectGraph => maxItemsInObjectGraph; public IDataContractSurrogate DataContractSurrogate => dataContractSurrogate; public bool PreserveObjectReferences => preserveObjectReferences; public bool IgnoreExtensionDataObject => ignoreExtensionDataObject; public DataContractResolver DataContractResolver => dataContractResolver; public bool SerializeReadOnlyTypes => serializeReadOnlyTypes; private DataContract RootContract { get { if (rootContract == null) { rootContract = DataContract.GetDataContract((dataContractSurrogate == null) ? rootType : GetSurrogatedType(dataContractSurrogate, rootType)); needsContractNsAtRoot = CheckIfNeedsContractNsAtRoot(rootName, rootNamespace, rootContract); } return rootContract; } } public DataContractSerializer(Type type) : this(type, (IEnumerable)null) { } public DataContractSerializer(Type type, IEnumerable knownTypes) : this(type, knownTypes, int.MaxValue, ignoreExtensionDataObject: false, preserveObjectReferences: false, null) { } public DataContractSerializer(Type type, IEnumerable knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, IDataContractSurrogate dataContractSurrogate) : this(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractSurrogate, null) { } public DataContractSerializer(Type type, IEnumerable knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, IDataContractSurrogate dataContractSurrogate, DataContractResolver dataContractResolver) { Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractSurrogate, dataContractResolver, serializeReadOnlyTypes: false); } public DataContractSerializer(Type type, string rootName, string rootNamespace) : this(type, rootName, rootNamespace, null) { } public DataContractSerializer(Type type, string rootName, string rootNamespace, IEnumerable knownTypes) : this(type, rootName, rootNamespace, knownTypes, int.MaxValue, ignoreExtensionDataObject: false, preserveObjectReferences: false, null) { } public DataContractSerializer(Type type, string rootName, string rootNamespace, IEnumerable knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, IDataContractSurrogate dataContractSurrogate) : this(type, rootName, rootNamespace, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractSurrogate, null) { } public DataContractSerializer(Type type, string rootName, string rootNamespace, IEnumerable knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, IDataContractSurrogate dataContractSurrogate, DataContractResolver dataContractResolver) { XmlDictionary xmlDictionary = new XmlDictionary(2); Initialize(type, xmlDictionary.Add(rootName), xmlDictionary.Add(DataContract.GetNamespace(rootNamespace)), knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractSurrogate, dataContractResolver, serializeReadOnlyTypes: false); } public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace) : this(type, rootName, rootNamespace, null) { } public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable knownTypes) : this(type, rootName, rootNamespace, knownTypes, int.MaxValue, ignoreExtensionDataObject: false, preserveObjectReferences: false, null, null) { } public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, IDataContractSurrogate dataContractSurrogate) : this(type, rootName, rootNamespace, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractSurrogate, null) { } public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, IDataContractSurrogate dataContractSurrogate, DataContractResolver dataContractResolver) { Initialize(type, rootName, rootNamespace, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractSurrogate, dataContractResolver, serializeReadOnlyTypes: false); } public DataContractSerializer(Type type, DataContractSerializerSettings settings) { if (settings == null) { settings = new DataContractSerializerSettings(); } Initialize(type, settings.RootName, settings.RootNamespace, settings.KnownTypes, settings.MaxItemsInObjectGraph, settings.IgnoreExtensionDataObject, settings.PreserveObjectReferences, settings.DataContractSurrogate, settings.DataContractResolver, settings.SerializeReadOnlyTypes); } private void Initialize(Type type, IEnumerable knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, IDataContractSurrogate dataContractSurrogate, DataContractResolver dataContractResolver, bool serializeReadOnlyTypes) { XmlObjectSerializer.CheckNull(type, "type"); rootType = type; if (knownTypes != null) { knownTypeList = new List(); foreach (Type knownType in knownTypes) { knownTypeList.Add(knownType); } } if (maxItemsInObjectGraph < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxItemsInObjectGraph", SR.GetString("The value of this argument must be non-negative."))); } this.maxItemsInObjectGraph = maxItemsInObjectGraph; this.ignoreExtensionDataObject = ignoreExtensionDataObject; this.preserveObjectReferences = preserveObjectReferences; this.dataContractSurrogate = dataContractSurrogate; this.dataContractResolver = dataContractResolver; this.serializeReadOnlyTypes = serializeReadOnlyTypes; } private void Initialize(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, IDataContractSurrogate dataContractSurrogate, DataContractResolver dataContractResolver, bool serializeReadOnlyTypes) { Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractSurrogate, dataContractResolver, serializeReadOnlyTypes); this.rootName = rootName; this.rootNamespace = rootNamespace; } internal override void InternalWriteObject(XmlWriterDelegator writer, object graph) { InternalWriteObject(writer, graph, null); } internal override void InternalWriteObject(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver) { InternalWriteStartObject(writer, graph); InternalWriteObjectContent(writer, graph, dataContractResolver); InternalWriteEndObject(writer); } public override void WriteObject(XmlWriter writer, object graph) { WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteStartObject(XmlWriter writer, object graph) { WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteObjectContent(XmlWriter writer, object graph) { WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteEndObject(XmlWriter writer) { WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer)); } public override void WriteStartObject(XmlDictionaryWriter writer, object graph) { WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) { WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteEndObject(XmlDictionaryWriter writer) { WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer)); } public void WriteObject(XmlDictionaryWriter writer, object graph, DataContractResolver dataContractResolver) { WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph, dataContractResolver); } public override object ReadObject(XmlReader reader) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName: true); } public override object ReadObject(XmlReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName); } public override bool IsStartObject(XmlReader reader) { return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader)); } public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName); } public override bool IsStartObject(XmlDictionaryReader reader) { return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader)); } public object ReadObject(XmlDictionaryReader reader, bool verifyObjectName, DataContractResolver dataContractResolver) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName, dataContractResolver); } internal override void InternalWriteStartObject(XmlWriterDelegator writer, object graph) { WriteRootElement(writer, RootContract, rootName, rootNamespace, needsContractNsAtRoot); } internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph) { InternalWriteObjectContent(writer, graph, null); } internal void InternalWriteObjectContent(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver) { if (MaxItemsInObjectGraph == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Maximum number of items that can be serialized or deserialized in an object graph is '{0}'.", MaxItemsInObjectGraph))); } DataContract dataContract = RootContract; Type underlyingType = dataContract.UnderlyingType; Type objType = ((graph == null) ? underlyingType : graph.GetType()); if (dataContractSurrogate != null) { graph = SurrogateToDataContractType(dataContractSurrogate, graph, underlyingType, ref objType); } if (dataContractResolver == null) { dataContractResolver = DataContractResolver; } if (graph == null) { if (IsRootXmlAny(rootName, dataContract)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("A null value cannot be serialized at the top level for IXmlSerializable root type '{0}' since its IsAny setting is 'true'. This type must write all its contents including the root element. Verify that the IXmlSerializable implementation is correct.", underlyingType))); } XmlObjectSerializer.WriteNull(writer); return; } if (underlyingType == objType) { if (dataContract.CanContainReferences) { XmlObjectSerializerWriteContext xmlObjectSerializerWriteContext = XmlObjectSerializerWriteContext.CreateContext(this, dataContract, dataContractResolver); xmlObjectSerializerWriteContext.HandleGraphAtTopLevel(writer, graph, dataContract); xmlObjectSerializerWriteContext.SerializeWithoutXsiType(dataContract, writer, graph, underlyingType.TypeHandle); } else { dataContract.WriteXmlValue(writer, graph, null); } return; } XmlObjectSerializerWriteContext xmlObjectSerializerWriteContext2 = null; if (IsRootXmlAny(rootName, dataContract)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("An object of type '{0}' cannot be serialized at the top level for IXmlSerializable root type '{1}' since its IsAny setting is 'true'. This type must write all its contents including the root element. Verify that the IXmlSerializable implementation is correct.", objType, dataContract.UnderlyingType))); } dataContract = GetDataContract(dataContract, underlyingType, objType); xmlObjectSerializerWriteContext2 = XmlObjectSerializerWriteContext.CreateContext(this, RootContract, dataContractResolver); if (dataContract.CanContainReferences) { xmlObjectSerializerWriteContext2.HandleGraphAtTopLevel(writer, graph, dataContract); } xmlObjectSerializerWriteContext2.OnHandleIsReference(writer, dataContract, graph); xmlObjectSerializerWriteContext2.SerializeWithXsiTypeAtTopLevel(dataContract, writer, graph, underlyingType.TypeHandle, objType); } internal static DataContract GetDataContract(DataContract declaredTypeContract, Type declaredType, Type objectType) { if (declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType)) { return declaredTypeContract; } if (declaredType.IsArray) { return declaredTypeContract; } return DataContract.GetDataContract(objectType.TypeHandle, objectType, SerializationMode.SharedContract); } internal void SetDataContractSurrogate(IDataContractSurrogate adapter) { dataContractSurrogate = adapter; } internal override void InternalWriteEndObject(XmlWriterDelegator writer) { if (!IsRootXmlAny(rootName, RootContract)) { writer.WriteEndElement(); } } internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName) { return InternalReadObject(xmlReader, verifyObjectName, null); } internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName, DataContractResolver dataContractResolver) { if (MaxItemsInObjectGraph == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Maximum number of items that can be serialized or deserialized in an object graph is '{0}'.", MaxItemsInObjectGraph))); } if (dataContractResolver == null) { dataContractResolver = DataContractResolver; } if (verifyObjectName) { if (!InternalIsStartObject(xmlReader)) { XmlDictionaryString topLevelElementName; XmlDictionaryString topLevelElementNamespace; if (rootName == null) { topLevelElementName = RootContract.TopLevelElementName; topLevelElementNamespace = RootContract.TopLevelElementNamespace; } else { topLevelElementName = rootName; topLevelElementNamespace = rootNamespace; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.GetString("Expecting element '{1}' from namespace '{0}'.", topLevelElementNamespace, topLevelElementName), xmlReader)); } } else if (!IsStartElement(xmlReader)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.GetString("Expecting state '{0}' when ReadObject is called.", XmlNodeType.Element), xmlReader)); } DataContract dataContract = RootContract; if (dataContract.IsPrimitive && (object)dataContract.UnderlyingType == rootType) { return dataContract.ReadXmlValue(xmlReader, null); } if (IsRootXmlAny(rootName, dataContract)) { return XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, dataContract as XmlDataContract, isMemberType: false); } return XmlObjectSerializerReadContext.CreateContext(this, dataContract, dataContractResolver).InternalDeserialize(xmlReader, rootType, dataContract, null, null); } internal override bool InternalIsStartObject(XmlReaderDelegator reader) { return IsRootElement(reader, RootContract, rootName, rootNamespace); } internal override Type GetSerializeType(object graph) { if (graph != null) { return graph.GetType(); } return rootType; } internal override Type GetDeserializeType() { return rootType; } internal static object SurrogateToDataContractType(IDataContractSurrogate dataContractSurrogate, object oldObj, Type surrogatedDeclaredType, ref Type objType) { object objectToSerialize = DataContractSurrogateCaller.GetObjectToSerialize(dataContractSurrogate, oldObj, objType, surrogatedDeclaredType); if (objectToSerialize != oldObj) { if (objectToSerialize == null) { objType = Globals.TypeOfObject; } else { objType = objectToSerialize.GetType(); } } return objectToSerialize; } internal static Type GetSurrogatedType(IDataContractSurrogate dataContractSurrogate, Type type) { return DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, DataContract.UnwrapNullableType(type)); } } public class DataContractSerializerSettings { private int maxItemsInObjectGraph = int.MaxValue; public XmlDictionaryString RootName { get; set; } public XmlDictionaryString RootNamespace { get; set; } public IEnumerable KnownTypes { get; set; } public int MaxItemsInObjectGraph { get { return maxItemsInObjectGraph; } set { maxItemsInObjectGraph = value; } } public bool IgnoreExtensionDataObject { get; set; } public bool PreserveObjectReferences { get; set; } public IDataContractSurrogate DataContractSurrogate { get; set; } public DataContractResolver DataContractResolver { get; set; } public bool SerializeReadOnlyTypes { get; set; } } internal class DataContractSet { private Dictionary contracts; private Dictionary processedContracts; private IDataContractSurrogate dataContractSurrogate; private Hashtable surrogateDataTable; private Dictionary knownTypesForObject; private ICollection referencedTypes; private ICollection referencedCollectionTypes; private Dictionary referencedTypesDictionary; private Dictionary referencedCollectionTypesDictionary; private Dictionary Contracts { get { if (contracts == null) { contracts = new Dictionary(); } return contracts; } } private Dictionary ProcessedContracts { get { if (processedContracts == null) { processedContracts = new Dictionary(); } return processedContracts; } } private Hashtable SurrogateDataTable { get { if (surrogateDataTable == null) { surrogateDataTable = new Hashtable(); } return surrogateDataTable; } } internal Dictionary KnownTypesForObject { get { return knownTypesForObject; } set { knownTypesForObject = value; } } public DataContract this[XmlQualifiedName key] { get { DataContract value = DataContract.GetBuiltInDataContract(key.Name, key.Namespace); if (value == null) { Contracts.TryGetValue(key, out value); } return value; } } public IDataContractSurrogate DataContractSurrogate => dataContractSurrogate; internal DataContractSet(IDataContractSurrogate dataContractSurrogate) : this(dataContractSurrogate, null, null) { } internal DataContractSet(IDataContractSurrogate dataContractSurrogate, ICollection referencedTypes, ICollection referencedCollectionTypes) { this.dataContractSurrogate = dataContractSurrogate; this.referencedTypes = referencedTypes; this.referencedCollectionTypes = referencedCollectionTypes; } internal DataContractSet(DataContractSet dataContractSet) { if (dataContractSet == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("dataContractSet")); } dataContractSurrogate = dataContractSet.dataContractSurrogate; referencedTypes = dataContractSet.referencedTypes; referencedCollectionTypes = dataContractSet.referencedCollectionTypes; foreach (KeyValuePair item in dataContractSet) { Add(item.Key, item.Value); } if (dataContractSet.processedContracts == null) { return; } foreach (KeyValuePair processedContract in dataContractSet.processedContracts) { ProcessedContracts.Add(processedContract.Key, processedContract.Value); } } internal void Add(Type type) { DataContract dataContract = GetDataContract(type); EnsureTypeNotGeneric(dataContract.UnderlyingType); Add(dataContract); } internal static void EnsureTypeNotGeneric(Type type) { if (type.ContainsGenericParameters) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Generic type '{0}' is not exportable.", type))); } } private void Add(DataContract dataContract) { Add(dataContract.StableName, dataContract); } public void Add(XmlQualifiedName name, DataContract dataContract) { if (!dataContract.IsBuiltInDataContract) { InternalAdd(name, dataContract); } } internal void InternalAdd(XmlQualifiedName name, DataContract dataContract) { DataContract value = null; if (Contracts.TryGetValue(name, out value)) { if (!value.Equals(dataContract)) { if (dataContract.UnderlyingType == null || value.UnderlyingType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString("Duplicate contract in data contract set was found, for '{0}' in '{1}' namespace.", dataContract.StableName.Name, dataContract.StableName.Namespace))); } bool flag = DataContract.GetClrTypeFullName(dataContract.UnderlyingType) == DataContract.GetClrTypeFullName(value.UnderlyingType); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString("Duplicate type contract in data contract set. Type name '{0}', for data contract '{1}' in '{2}' namespace.", flag ? dataContract.UnderlyingType.AssemblyQualifiedName : DataContract.GetClrTypeFullName(dataContract.UnderlyingType), flag ? value.UnderlyingType.AssemblyQualifiedName : DataContract.GetClrTypeFullName(value.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace))); } } else { Contracts.Add(name, dataContract); if (dataContract is ClassDataContract) { AddClassDataContract((ClassDataContract)dataContract); } else if (dataContract is CollectionDataContract) { AddCollectionDataContract((CollectionDataContract)dataContract); } else if (dataContract is XmlDataContract) { AddXmlDataContract((XmlDataContract)dataContract); } } } private void AddClassDataContract(ClassDataContract classDataContract) { if (classDataContract.BaseContract != null) { Add(classDataContract.BaseContract.StableName, classDataContract.BaseContract); } if (!classDataContract.IsISerializable && classDataContract.Members != null) { for (int i = 0; i < classDataContract.Members.Count; i++) { DataMember dataMember = classDataContract.Members[i]; DataContract memberTypeDataContract = GetMemberTypeDataContract(dataMember); if (dataContractSurrogate != null && dataMember.MemberInfo != null) { object customDataToExport = DataContractSurrogateCaller.GetCustomDataToExport(dataContractSurrogate, dataMember.MemberInfo, memberTypeDataContract.UnderlyingType); if (customDataToExport != null) { SurrogateDataTable.Add(dataMember, customDataToExport); } } Add(memberTypeDataContract.StableName, memberTypeDataContract); } } AddKnownDataContracts(classDataContract.KnownDataContracts); } private void AddCollectionDataContract(CollectionDataContract collectionDataContract) { if (collectionDataContract.IsDictionary) { ClassDataContract classDataContract = collectionDataContract.ItemContract as ClassDataContract; AddClassDataContract(classDataContract); } else { DataContract itemTypeDataContract = GetItemTypeDataContract(collectionDataContract); if (itemTypeDataContract != null) { Add(itemTypeDataContract.StableName, itemTypeDataContract); } } AddKnownDataContracts(collectionDataContract.KnownDataContracts); } private void AddXmlDataContract(XmlDataContract xmlDataContract) { AddKnownDataContracts(xmlDataContract.KnownDataContracts); } private void AddKnownDataContracts(Dictionary knownDataContracts) { if (knownDataContracts == null) { return; } foreach (DataContract value in knownDataContracts.Values) { Add(value); } } internal XmlQualifiedName GetStableName(Type clrType) { if (dataContractSurrogate != null) { return DataContract.GetStableName(DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, clrType)); } return DataContract.GetStableName(clrType); } internal DataContract GetDataContract(Type clrType) { if (dataContractSurrogate == null) { return DataContract.GetDataContract(clrType); } DataContract builtInDataContract = DataContract.GetBuiltInDataContract(clrType); if (builtInDataContract != null) { return builtInDataContract; } Type dataContractType = DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, clrType); builtInDataContract = DataContract.GetDataContract(dataContractType); if (!SurrogateDataTable.Contains(builtInDataContract)) { object customDataToExport = DataContractSurrogateCaller.GetCustomDataToExport(dataContractSurrogate, clrType, dataContractType); if (customDataToExport != null) { SurrogateDataTable.Add(builtInDataContract, customDataToExport); } } return builtInDataContract; } internal DataContract GetMemberTypeDataContract(DataMember dataMember) { if (dataMember.MemberInfo != null) { Type memberType = dataMember.MemberType; if (dataMember.IsGetOnlyCollection) { if (dataContractSurrogate != null && DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, memberType) != memberType) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Surrogates with get-only collections are not supported. Type '{1}' contains '{2}' which is of '{0}' type.", DataContract.GetClrTypeFullName(memberType), DataContract.GetClrTypeFullName(dataMember.MemberInfo.DeclaringType), dataMember.MemberInfo.Name))); } return DataContract.GetGetOnlyCollectionDataContract(DataContract.GetId(memberType.TypeHandle), memberType.TypeHandle, memberType, SerializationMode.SharedContract); } return GetDataContract(memberType); } return dataMember.MemberTypeContract; } internal DataContract GetItemTypeDataContract(CollectionDataContract collectionContract) { if (collectionContract.ItemType != null) { return GetDataContract(collectionContract.ItemType); } return collectionContract.ItemContract; } internal object GetSurrogateData(object key) { return SurrogateDataTable[key]; } internal void SetSurrogateData(object key, object surrogateData) { SurrogateDataTable[key] = surrogateData; } public bool Remove(XmlQualifiedName key) { if (DataContract.GetBuiltInDataContract(key.Name, key.Namespace) != null) { return false; } return Contracts.Remove(key); } public IEnumerator> GetEnumerator() { return Contracts.GetEnumerator(); } internal bool IsContractProcessed(DataContract dataContract) { return ProcessedContracts.ContainsKey(dataContract); } internal void SetContractProcessed(DataContract dataContract) { ProcessedContracts.Add(dataContract, dataContract); } private Dictionary GetReferencedTypes() { if (referencedTypesDictionary == null) { referencedTypesDictionary = new Dictionary(); referencedTypesDictionary.Add(DataContract.GetStableName(Globals.TypeOfNullable), Globals.TypeOfNullable); if (referencedTypes != null) { foreach (Type referencedType in referencedTypes) { if (referencedType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString("Referenced types cannot contain null."))); } AddReferencedType(referencedTypesDictionary, referencedType); } } } return referencedTypesDictionary; } private Dictionary GetReferencedCollectionTypes() { if (referencedCollectionTypesDictionary == null) { referencedCollectionTypesDictionary = new Dictionary(); if (referencedCollectionTypes != null) { foreach (Type referencedCollectionType in referencedCollectionTypes) { if (referencedCollectionType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString("Referenced collection types cannot contain null."))); } AddReferencedType(referencedCollectionTypesDictionary, referencedCollectionType); } } XmlQualifiedName stableName = DataContract.GetStableName(Globals.TypeOfDictionaryGeneric); if (!referencedCollectionTypesDictionary.ContainsKey(stableName) && GetReferencedTypes().ContainsKey(stableName)) { AddReferencedType(referencedCollectionTypesDictionary, Globals.TypeOfDictionaryGeneric); } } return referencedCollectionTypesDictionary; } private void AddReferencedType(Dictionary referencedTypes, Type type) { if (!IsTypeReferenceable(type)) { return; } XmlQualifiedName stableName; try { stableName = GetStableName(type); } catch (InvalidDataContractException) { return; } catch (InvalidOperationException) { return; } if (referencedTypes.TryGetValue(stableName, out var value)) { Type type2 = value as Type; if (type2 != null) { if (type2 != type) { referencedTypes.Remove(stableName); List list = new List(); list.Add(type2); list.Add(type); referencedTypes.Add(stableName, list); } } else { List list2 = (List)value; if (!list2.Contains(type)) { list2.Add(type); } } } else { referencedTypes.Add(stableName, type); } } internal bool TryGetReferencedType(XmlQualifiedName stableName, DataContract dataContract, out Type type) { return TryGetReferencedType(stableName, dataContract, useReferencedCollectionTypes: false, out type); } internal bool TryGetReferencedCollectionType(XmlQualifiedName stableName, DataContract dataContract, out Type type) { return TryGetReferencedType(stableName, dataContract, useReferencedCollectionTypes: true, out type); } private bool TryGetReferencedType(XmlQualifiedName stableName, DataContract dataContract, bool useReferencedCollectionTypes, out Type type) { if ((useReferencedCollectionTypes ? GetReferencedCollectionTypes() : GetReferencedTypes()).TryGetValue(stableName, out var value)) { type = value as Type; if (type != null) { return true; } List list = (List)value; StringBuilder stringBuilder = new StringBuilder(); bool flag = false; for (int i = 0; i < list.Count; i++) { Type type2 = list[i]; if (!flag) { flag = type2.IsGenericTypeDefinition; } stringBuilder.AppendFormat("{0}\"{1}\" ", Environment.NewLine, type2.AssemblyQualifiedName); if (dataContract != null) { DataContract dataContract2 = GetDataContract(type2); stringBuilder.Append(SR.GetString((dataContract2 != null && dataContract2.Equals(dataContract)) ? "Reference type matches." : "Reference type does not match.")); } } if (flag) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(useReferencedCollectionTypes ? "Ambiguous collection types were referenced: {0}" : "Ambiguous types were referenced: {0}", stringBuilder.ToString()))); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(useReferencedCollectionTypes ? "In '{0}' element in '{1}' namespace, ambiguous collection types were referenced: {2}" : "In '{0}' element in '{1}' namespace, ambiguous types were referenced: {2}", XmlConvert.DecodeName(stableName.Name), stableName.Namespace, stringBuilder.ToString()))); } type = null; return false; } private static bool IsTypeReferenceable(Type type) { try { Type itemType; return type.IsSerializable || type.IsDefined(Globals.TypeOfDataContractAttribute, inherit: false) || (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type) && !type.IsGenericTypeDefinition) || CollectionDataContract.IsCollection(type, out itemType) || ClassDataContract.IsNonAttributedTypeValidForSerialization(type); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } } return false; } } internal class DataMember { private class CriticalHelper { private DataContract memberTypeContract; private string name; private int order; private bool isRequired; private bool emitDefaultValue; private bool isNullable; private bool isGetOnlyCollection; private MemberInfo memberInfo; private bool hasConflictingNameAndType; private DataMember conflictingMember; internal MemberInfo MemberInfo => memberInfo; internal string Name { get { return name; } set { name = value; } } internal int Order { get { return order; } set { order = value; } } internal bool IsRequired { get { return isRequired; } set { isRequired = value; } } internal bool EmitDefaultValue { get { return emitDefaultValue; } set { emitDefaultValue = value; } } internal bool IsNullable { get { return isNullable; } set { isNullable = value; } } internal bool IsGetOnlyCollection { get { return isGetOnlyCollection; } set { isGetOnlyCollection = value; } } internal Type MemberType { get { FieldInfo fieldInfo = MemberInfo as FieldInfo; if (fieldInfo != null) { return fieldInfo.FieldType; } return ((PropertyInfo)MemberInfo).PropertyType; } } internal DataContract MemberTypeContract { get { if (memberTypeContract == null && MemberInfo != null) { if (IsGetOnlyCollection) { memberTypeContract = DataContract.GetGetOnlyCollectionDataContract(DataContract.GetId(MemberType.TypeHandle), MemberType.TypeHandle, MemberType, SerializationMode.SharedContract); } else { memberTypeContract = DataContract.GetDataContract(MemberType); } } return memberTypeContract; } set { memberTypeContract = value; } } internal bool HasConflictingNameAndType { get { return hasConflictingNameAndType; } set { hasConflictingNameAndType = value; } } internal DataMember ConflictingMember { get { return conflictingMember; } set { conflictingMember = value; } } internal CriticalHelper() { emitDefaultValue = true; } internal CriticalHelper(MemberInfo memberInfo) { emitDefaultValue = true; this.memberInfo = memberInfo; } internal CriticalHelper(string name) { Name = name; } internal CriticalHelper(DataContract memberTypeContract, string name, bool isNullable, bool isRequired, bool emitDefaultValue, int order) { MemberTypeContract = memberTypeContract; Name = name; IsNullable = isNullable; IsRequired = isRequired; EmitDefaultValue = emitDefaultValue; Order = order; } } [SecurityCritical] private CriticalHelper helper; internal MemberInfo MemberInfo { [SecuritySafeCritical] get { return helper.MemberInfo; } } internal string Name { [SecuritySafeCritical] get { return helper.Name; } [SecurityCritical] set { helper.Name = value; } } internal int Order { [SecuritySafeCritical] get { return helper.Order; } [SecurityCritical] set { helper.Order = value; } } internal bool IsRequired { [SecuritySafeCritical] get { return helper.IsRequired; } [SecurityCritical] set { helper.IsRequired = value; } } internal bool EmitDefaultValue { [SecuritySafeCritical] get { return helper.EmitDefaultValue; } [SecurityCritical] set { helper.EmitDefaultValue = value; } } internal bool IsNullable { [SecuritySafeCritical] get { return helper.IsNullable; } [SecurityCritical] set { helper.IsNullable = value; } } internal bool IsGetOnlyCollection { [SecuritySafeCritical] get { return helper.IsGetOnlyCollection; } [SecurityCritical] set { helper.IsGetOnlyCollection = value; } } internal Type MemberType { [SecuritySafeCritical] get { return helper.MemberType; } } internal DataContract MemberTypeContract { [SecuritySafeCritical] get { return helper.MemberTypeContract; } [SecurityCritical] set { helper.MemberTypeContract = value; } } internal bool HasConflictingNameAndType { [SecuritySafeCritical] get { return helper.HasConflictingNameAndType; } [SecurityCritical] set { helper.HasConflictingNameAndType = value; } } internal DataMember ConflictingMember { [SecuritySafeCritical] get { return helper.ConflictingMember; } [SecurityCritical] set { helper.ConflictingMember = value; } } [SecuritySafeCritical] internal DataMember() { helper = new CriticalHelper(); } [SecuritySafeCritical] internal DataMember(MemberInfo memberInfo) { helper = new CriticalHelper(memberInfo); } [SecuritySafeCritical] internal DataMember(string name) { helper = new CriticalHelper(name); } [SecuritySafeCritical] internal DataMember(DataContract memberTypeContract, string name, bool isNullable, bool isRequired, bool emitDefaultValue, int order) { helper = new CriticalHelper(memberTypeContract, name, isNullable, isRequired, emitDefaultValue, order); } internal DataMember BindGenericParameters(DataContract[] paramContracts, Dictionary boundContracts) { DataContract dataContract = MemberTypeContract.BindGenericParameters(paramContracts, boundContracts); return new DataMember(dataContract, Name, !dataContract.IsValueType, IsRequired, EmitDefaultValue, Order); } internal bool Equals(object other, Dictionary checkedContracts) { if (this == other) { return true; } if (other is DataMember dataMember) { bool flag = MemberTypeContract != null && !MemberTypeContract.IsValueType; bool flag2 = dataMember.MemberTypeContract != null && !dataMember.MemberTypeContract.IsValueType; if (Name == dataMember.Name && (IsNullable || flag) == (dataMember.IsNullable || flag2) && IsRequired == dataMember.IsRequired && EmitDefaultValue == dataMember.EmitDefaultValue) { return MemberTypeContract.Equals(dataMember.MemberTypeContract, checkedContracts); } return false; } return false; } public override int GetHashCode() { return base.GetHashCode(); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, Inherited = false, AllowMultiple = false)] public sealed class DataMemberAttribute : Attribute { private string name; private bool isNameSetExplicitly; private int order = -1; private bool isRequired; private bool emitDefaultValue = true; public string Name { get { return name; } set { name = value; isNameSetExplicitly = true; } } public bool IsNameSetExplicitly => isNameSetExplicitly; public int Order { get { return order; } set { if (value < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Property 'Order' in DataMemberAttribute attribute cannot be a negative number."))); } order = value; } } public bool IsRequired { get { return isRequired; } set { isRequired = value; } } public bool EmitDefaultValue { get { return emitDefaultValue; } set { emitDefaultValue = value; } } } public class DateTimeFormat { private string formatString; private IFormatProvider formatProvider; private DateTimeStyles dateTimeStyles; public string FormatString => formatString; public IFormatProvider FormatProvider => formatProvider; public DateTimeStyles DateTimeStyles { get { return dateTimeStyles; } set { dateTimeStyles = value; } } public DateTimeFormat(string formatString) : this(formatString, DateTimeFormatInfo.CurrentInfo) { } public DateTimeFormat(string formatString, IFormatProvider formatProvider) { if (formatString == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("formatString"); } if (formatProvider == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("formatProvider"); } this.formatString = formatString; this.formatProvider = formatProvider; dateTimeStyles = DateTimeStyles.RoundtripKind; } } [DataContract(Name = "DateTimeOffset", Namespace = "http://schemas.datacontract.org/2004/07/System")] internal struct DateTimeOffsetAdapter { private DateTime utcDateTime; private short offsetMinutes; [DataMember(Name = "DateTime", IsRequired = true)] public DateTime UtcDateTime { get { return utcDateTime; } set { utcDateTime = value; } } [DataMember(Name = "OffsetMinutes", IsRequired = true)] public short OffsetMinutes { get { return offsetMinutes; } set { offsetMinutes = value; } } public DateTimeOffsetAdapter(DateTime dateTime, short offsetMinutes) { utcDateTime = dateTime; this.offsetMinutes = offsetMinutes; } public static DateTimeOffset GetDateTimeOffset(DateTimeOffsetAdapter value) { try { if (value.UtcDateTime.Kind == DateTimeKind.Unspecified) { return new DateTimeOffset(value.UtcDateTime, new TimeSpan(0, value.OffsetMinutes, 0)); } return new DateTimeOffset(value.UtcDateTime).ToOffset(new TimeSpan(0, value.OffsetMinutes, 0)); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value.ToString(CultureInfo.InvariantCulture), "DateTimeOffset", exception)); } } public static DateTimeOffsetAdapter GetDateTimeOffsetAdapter(DateTimeOffset value) { return new DateTimeOffsetAdapter(value.UtcDateTime, (short)value.Offset.TotalMinutes); } public string ToString(IFormatProvider provider) { return string.Concat("DateTime: ", UtcDateTime, ", Offset: ", OffsetMinutes); } } internal static class DictionaryGlobals { public static readonly XmlDictionaryString EmptyString; public static readonly XmlDictionaryString SchemaInstanceNamespace; public static readonly XmlDictionaryString SchemaNamespace; public static readonly XmlDictionaryString SerializationNamespace; public static readonly XmlDictionaryString XmlnsNamespace; public static readonly XmlDictionaryString XsiTypeLocalName; public static readonly XmlDictionaryString XsiNilLocalName; public static readonly XmlDictionaryString ClrTypeLocalName; public static readonly XmlDictionaryString ClrAssemblyLocalName; public static readonly XmlDictionaryString ArraySizeLocalName; public static readonly XmlDictionaryString IdLocalName; public static readonly XmlDictionaryString RefLocalName; public static readonly XmlDictionaryString ISerializableFactoryTypeLocalName; public static readonly XmlDictionaryString CharLocalName; public static readonly XmlDictionaryString BooleanLocalName; public static readonly XmlDictionaryString SignedByteLocalName; public static readonly XmlDictionaryString UnsignedByteLocalName; public static readonly XmlDictionaryString ShortLocalName; public static readonly XmlDictionaryString UnsignedShortLocalName; public static readonly XmlDictionaryString IntLocalName; public static readonly XmlDictionaryString UnsignedIntLocalName; public static readonly XmlDictionaryString LongLocalName; public static readonly XmlDictionaryString UnsignedLongLocalName; public static readonly XmlDictionaryString FloatLocalName; public static readonly XmlDictionaryString DoubleLocalName; public static readonly XmlDictionaryString DecimalLocalName; public static readonly XmlDictionaryString DateTimeLocalName; public static readonly XmlDictionaryString StringLocalName; public static readonly XmlDictionaryString ByteArrayLocalName; public static readonly XmlDictionaryString ObjectLocalName; public static readonly XmlDictionaryString TimeSpanLocalName; public static readonly XmlDictionaryString GuidLocalName; public static readonly XmlDictionaryString UriLocalName; public static readonly XmlDictionaryString QNameLocalName; public static readonly XmlDictionaryString Space; public static readonly XmlDictionaryString timeLocalName; public static readonly XmlDictionaryString dateLocalName; public static readonly XmlDictionaryString hexBinaryLocalName; public static readonly XmlDictionaryString gYearMonthLocalName; public static readonly XmlDictionaryString gYearLocalName; public static readonly XmlDictionaryString gMonthDayLocalName; public static readonly XmlDictionaryString gDayLocalName; public static readonly XmlDictionaryString gMonthLocalName; public static readonly XmlDictionaryString integerLocalName; public static readonly XmlDictionaryString positiveIntegerLocalName; public static readonly XmlDictionaryString negativeIntegerLocalName; public static readonly XmlDictionaryString nonPositiveIntegerLocalName; public static readonly XmlDictionaryString nonNegativeIntegerLocalName; public static readonly XmlDictionaryString normalizedStringLocalName; public static readonly XmlDictionaryString tokenLocalName; public static readonly XmlDictionaryString languageLocalName; public static readonly XmlDictionaryString NameLocalName; public static readonly XmlDictionaryString NCNameLocalName; public static readonly XmlDictionaryString XSDIDLocalName; public static readonly XmlDictionaryString IDREFLocalName; public static readonly XmlDictionaryString IDREFSLocalName; public static readonly XmlDictionaryString ENTITYLocalName; public static readonly XmlDictionaryString ENTITIESLocalName; public static readonly XmlDictionaryString NMTOKENLocalName; public static readonly XmlDictionaryString NMTOKENSLocalName; public static readonly XmlDictionaryString AsmxTypesNamespace; static DictionaryGlobals() { XmlDictionary xmlDictionary = new XmlDictionary(61); try { SchemaInstanceNamespace = xmlDictionary.Add("http://www.w3.org/2001/XMLSchema-instance"); SerializationNamespace = xmlDictionary.Add("http://schemas.microsoft.com/2003/10/Serialization/"); SchemaNamespace = xmlDictionary.Add("http://www.w3.org/2001/XMLSchema"); XsiTypeLocalName = xmlDictionary.Add("type"); XsiNilLocalName = xmlDictionary.Add("nil"); IdLocalName = xmlDictionary.Add("Id"); RefLocalName = xmlDictionary.Add("Ref"); ArraySizeLocalName = xmlDictionary.Add("Size"); EmptyString = xmlDictionary.Add(string.Empty); ISerializableFactoryTypeLocalName = xmlDictionary.Add("FactoryType"); XmlnsNamespace = xmlDictionary.Add("http://www.w3.org/2000/xmlns/"); CharLocalName = xmlDictionary.Add("char"); BooleanLocalName = xmlDictionary.Add("boolean"); SignedByteLocalName = xmlDictionary.Add("byte"); UnsignedByteLocalName = xmlDictionary.Add("unsignedByte"); ShortLocalName = xmlDictionary.Add("short"); UnsignedShortLocalName = xmlDictionary.Add("unsignedShort"); IntLocalName = xmlDictionary.Add("int"); UnsignedIntLocalName = xmlDictionary.Add("unsignedInt"); LongLocalName = xmlDictionary.Add("long"); UnsignedLongLocalName = xmlDictionary.Add("unsignedLong"); FloatLocalName = xmlDictionary.Add("float"); DoubleLocalName = xmlDictionary.Add("double"); DecimalLocalName = xmlDictionary.Add("decimal"); DateTimeLocalName = xmlDictionary.Add("dateTime"); StringLocalName = xmlDictionary.Add("string"); ByteArrayLocalName = xmlDictionary.Add("base64Binary"); ObjectLocalName = xmlDictionary.Add("anyType"); TimeSpanLocalName = xmlDictionary.Add("duration"); GuidLocalName = xmlDictionary.Add("guid"); UriLocalName = xmlDictionary.Add("anyURI"); QNameLocalName = xmlDictionary.Add("QName"); ClrTypeLocalName = xmlDictionary.Add("Type"); ClrAssemblyLocalName = xmlDictionary.Add("Assembly"); Space = xmlDictionary.Add(" "); timeLocalName = xmlDictionary.Add("time"); dateLocalName = xmlDictionary.Add("date"); hexBinaryLocalName = xmlDictionary.Add("hexBinary"); gYearMonthLocalName = xmlDictionary.Add("gYearMonth"); gYearLocalName = xmlDictionary.Add("gYear"); gMonthDayLocalName = xmlDictionary.Add("gMonthDay"); gDayLocalName = xmlDictionary.Add("gDay"); gMonthLocalName = xmlDictionary.Add("gMonth"); integerLocalName = xmlDictionary.Add("integer"); positiveIntegerLocalName = xmlDictionary.Add("positiveInteger"); negativeIntegerLocalName = xmlDictionary.Add("negativeInteger"); nonPositiveIntegerLocalName = xmlDictionary.Add("nonPositiveInteger"); nonNegativeIntegerLocalName = xmlDictionary.Add("nonNegativeInteger"); normalizedStringLocalName = xmlDictionary.Add("normalizedString"); tokenLocalName = xmlDictionary.Add("token"); languageLocalName = xmlDictionary.Add("language"); NameLocalName = xmlDictionary.Add("Name"); NCNameLocalName = xmlDictionary.Add("NCName"); XSDIDLocalName = xmlDictionary.Add("ID"); IDREFLocalName = xmlDictionary.Add("IDREF"); IDREFSLocalName = xmlDictionary.Add("IDREFS"); ENTITYLocalName = xmlDictionary.Add("ENTITY"); ENTITIESLocalName = xmlDictionary.Add("ENTITIES"); NMTOKENLocalName = xmlDictionary.Add("NMTOKEN"); NMTOKENSLocalName = xmlDictionary.Add("NMTOKENS"); AsmxTypesNamespace = xmlDictionary.Add("http://microsoft.com/wsdl/types/"); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } } } public enum EmitTypeInformation { AsNeeded, Always, Never } internal sealed class EnumDataContract : DataContract { private class EnumDataContractCriticalHelper : DataContractCriticalHelper { private static Dictionary typeToName; private static Dictionary nameToType; private XmlQualifiedName baseContractName; private List members; private List values; private bool isULong; private bool isFlags; private bool hasDataContract; private XmlDictionaryString[] childElementNames; internal XmlQualifiedName BaseContractName { get { return baseContractName; } set { baseContractName = value; Type baseType = GetBaseType(baseContractName); if (baseType == null) { ThrowInvalidDataContractException(SR.GetString("Invalid enum base type is specified for type '{0}' in '{1}' namespace, element name is '{2}' in '{3}' namespace.", value.Name, value.Namespace, base.StableName.Name, base.StableName.Namespace)); } ImportBaseType(baseType); } } internal List Members { get { return members; } set { members = value; } } internal List Values { get { return values; } set { values = value; } } internal bool IsFlags { get { return isFlags; } set { isFlags = value; } } internal bool IsULong => isULong; internal XmlDictionaryString[] ChildElementNames => childElementNames; static EnumDataContractCriticalHelper() { typeToName = new Dictionary(); nameToType = new Dictionary(); Add(typeof(sbyte), "byte"); Add(typeof(byte), "unsignedByte"); Add(typeof(short), "short"); Add(typeof(ushort), "unsignedShort"); Add(typeof(int), "int"); Add(typeof(uint), "unsignedInt"); Add(typeof(long), "long"); Add(typeof(ulong), "unsignedLong"); } internal static void Add(Type type, string localName) { XmlQualifiedName xmlQualifiedName = DataContract.CreateQualifiedName(localName, "http://www.w3.org/2001/XMLSchema"); typeToName.Add(type, xmlQualifiedName); nameToType.Add(xmlQualifiedName, type); } internal static XmlQualifiedName GetBaseContractName(Type type) { XmlQualifiedName value = null; typeToName.TryGetValue(type, out value); return value; } internal static Type GetBaseType(XmlQualifiedName baseContractName) { Type value = null; nameToType.TryGetValue(baseContractName, out value); return value; } internal EnumDataContractCriticalHelper() { base.IsValueType = true; } internal EnumDataContractCriticalHelper(Type type) : base(type) { base.StableName = DataContract.GetStableName(type, out hasDataContract); Type type2 = Enum.GetUnderlyingType(type); baseContractName = GetBaseContractName(type2); ImportBaseType(type2); IsFlags = type.IsDefined(Globals.TypeOfFlagsAttribute, inherit: false); ImportDataMembers(); XmlDictionary xmlDictionary = new XmlDictionary(2 + Members.Count); base.Name = xmlDictionary.Add(base.StableName.Name); base.Namespace = xmlDictionary.Add(base.StableName.Namespace); childElementNames = new XmlDictionaryString[Members.Count]; for (int i = 0; i < Members.Count; i++) { childElementNames[i] = xmlDictionary.Add(Members[i].Name); } if (DataContract.TryGetDCAttribute(type, out var dataContractAttribute) && dataContractAttribute.IsReference) { DataContract.ThrowInvalidDataContractException(SR.GetString("Enum type '{0}' cannot have the IsReference setting of '{1}'. Either change the setting to '{2}', or remove it completely.", DataContract.GetClrTypeFullName(type), dataContractAttribute.IsReference, false), type); } } private void ImportBaseType(Type baseType) { isULong = baseType == Globals.TypeOfULong; } private void ImportDataMembers() { Type type = base.UnderlyingType; FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public); Dictionary memberNamesTable = new Dictionary(); List list = new List(fields.Length); List list2 = new List(fields.Length); foreach (FieldInfo fieldInfo in fields) { bool flag = false; if (hasDataContract) { object[] customAttributes = fieldInfo.GetCustomAttributes(Globals.TypeOfEnumMemberAttribute, inherit: false); if (customAttributes != null && customAttributes.Length != 0) { if (customAttributes.Length > 1) { ThrowInvalidDataContractException(SR.GetString("Member '{0}.{1}' has more than one EnumMemberAttribute attribute.", DataContract.GetClrTypeFullName(fieldInfo.DeclaringType), fieldInfo.Name)); } EnumMemberAttribute enumMemberAttribute = (EnumMemberAttribute)customAttributes[0]; DataMember dataMember = new DataMember(fieldInfo); if (enumMemberAttribute.IsValueSetExplicitly) { if (enumMemberAttribute.Value == null || enumMemberAttribute.Value.Length == 0) { ThrowInvalidDataContractException(SR.GetString("'{0}' in type '{1}' cannot have EnumMemberAttribute attribute Value set to null or empty string.", fieldInfo.Name, DataContract.GetClrTypeFullName(type))); } dataMember.Name = enumMemberAttribute.Value; } else { dataMember.Name = fieldInfo.Name; } ClassDataContract.CheckAndAddMember(list, dataMember, memberNamesTable); flag = true; } object[] customAttributes2 = fieldInfo.GetCustomAttributes(Globals.TypeOfDataMemberAttribute, inherit: false); if (customAttributes2 != null && customAttributes2.Length != 0) { ThrowInvalidDataContractException(SR.GetString("Member '{0}.{1}' has DataMemberAttribute attribute. Use EnumMemberAttribute attribute instead.", DataContract.GetClrTypeFullName(fieldInfo.DeclaringType), fieldInfo.Name)); } } else if (!fieldInfo.IsNotSerialized) { DataMember dataMember2 = new DataMember(fieldInfo); dataMember2.Name = fieldInfo.Name; ClassDataContract.CheckAndAddMember(list, dataMember2, memberNamesTable); flag = true; } if (flag) { object value = fieldInfo.GetValue(null); if (isULong) { list2.Add((long)((IConvertible)value).ToUInt64(null)); } else { list2.Add(((IConvertible)value).ToInt64(null)); } } } Thread.MemoryBarrier(); members = list; values = list2; } } [SecurityCritical] private EnumDataContractCriticalHelper helper; internal XmlQualifiedName BaseContractName { [SecuritySafeCritical] get { return helper.BaseContractName; } [SecurityCritical] set { helper.BaseContractName = value; } } internal List Members { [SecuritySafeCritical] get { return helper.Members; } [SecurityCritical] set { helper.Members = value; } } internal List Values { [SecuritySafeCritical] get { return helper.Values; } [SecurityCritical] set { helper.Values = value; } } internal bool IsFlags { [SecuritySafeCritical] get { return helper.IsFlags; } [SecurityCritical] set { helper.IsFlags = value; } } internal bool IsULong { [SecuritySafeCritical] get { return helper.IsULong; } } private XmlDictionaryString[] ChildElementNames { [SecuritySafeCritical] get { return helper.ChildElementNames; } } internal override bool CanContainReferences => false; [SecuritySafeCritical] internal EnumDataContract() : base(new EnumDataContractCriticalHelper()) { helper = base.Helper as EnumDataContractCriticalHelper; } [SecuritySafeCritical] internal EnumDataContract(Type type) : base(new EnumDataContractCriticalHelper(type)) { helper = base.Helper as EnumDataContractCriticalHelper; } [SecuritySafeCritical] internal static XmlQualifiedName GetBaseContractName(Type type) { return EnumDataContractCriticalHelper.GetBaseContractName(type); } [SecuritySafeCritical] internal static Type GetBaseType(XmlQualifiedName baseContractName) { return EnumDataContractCriticalHelper.GetBaseType(baseContractName); } internal void WriteEnumValue(XmlWriterDelegator writer, object value) { long num = (IsULong ? ((long)((IConvertible)value).ToUInt64(null)) : ((IConvertible)value).ToInt64(null)); for (int i = 0; i < Values.Count; i++) { if (num == Values[i]) { writer.WriteString(ChildElementNames[i].Value); return; } } if (IsFlags) { int num2 = -1; bool flag = true; for (int j = 0; j < Values.Count; j++) { long num3 = Values[j]; if (num3 == 0L) { num2 = j; continue; } if (num == 0L) { break; } if ((num3 & num) == num3) { if (flag) { flag = false; } else { writer.WriteString(DictionaryGlobals.Space.Value); } writer.WriteString(ChildElementNames[j].Value); num &= ~num3; } } if (num != 0L) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Enum value '{0}' is invalid for type '{1}' and cannot be serialized. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attribute.", value, DataContract.GetClrTypeFullName(base.UnderlyingType)))); } if (flag && num2 >= 0) { writer.WriteString(ChildElementNames[num2].Value); } return; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Enum value '{0}' is invalid for type '{1}' and cannot be serialized. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attribute.", value, DataContract.GetClrTypeFullName(base.UnderlyingType)))); } internal object ReadEnumValue(XmlReaderDelegator reader) { string text = reader.ReadElementContentAsString(); long num = 0L; int i = 0; if (IsFlags) { for (; i < text.Length && text[i] == ' '; i++) { } int num2 = i; int num3 = 0; for (; i < text.Length; i++) { if (text[i] == ' ') { num3 = i - num2; if (num3 > 0) { num |= ReadEnumValue(text, num2, num3); } for (i++; i < text.Length && text[i] == ' '; i++) { } num2 = i; if (i == text.Length) { break; } } } num3 = i - num2; if (num3 > 0) { num |= ReadEnumValue(text, num2, num3); } } else { if (text.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Invalid enum value '{0}' cannot be deserialized into type '{1}'. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attribute.", text, DataContract.GetClrTypeFullName(base.UnderlyingType)))); } num = ReadEnumValue(text, 0, text.Length); } if (IsULong) { return Enum.ToObject(base.UnderlyingType, (ulong)num); } return Enum.ToObject(base.UnderlyingType, num); } private long ReadEnumValue(string value, int index, int count) { for (int i = 0; i < Members.Count; i++) { string text = Members[i].Name; if (text.Length == count && string.CompareOrdinal(value, index, text, 0, count) == 0) { return Values[i]; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Invalid enum value '{0}' cannot be deserialized into type '{1}'. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attribute.", value.Substring(index, count), DataContract.GetClrTypeFullName(base.UnderlyingType)))); } internal string GetStringFromEnumValue(long value) { if (IsULong) { return XmlConvert.ToString((ulong)value); } return XmlConvert.ToString(value); } internal long GetEnumValueFromString(string value) { if (IsULong) { return (long)XmlConverter.ToUInt64(value); } return XmlConverter.ToInt64(value); } internal override bool Equals(object other, Dictionary checkedContracts) { if (IsEqualOrChecked(other, checkedContracts)) { return true; } if (base.Equals(other, null) && other is EnumDataContract enumDataContract) { if (Members.Count != enumDataContract.Members.Count || Values.Count != enumDataContract.Values.Count) { return false; } string[] array = new string[Members.Count]; string[] array2 = new string[Members.Count]; for (int i = 0; i < Members.Count; i++) { array[i] = Members[i].Name; array2[i] = enumDataContract.Members[i].Name; } Array.Sort(array); Array.Sort(array2); for (int j = 0; j < Members.Count; j++) { if (array[j] != array2[j]) { return false; } } return IsFlags == enumDataContract.IsFlags; } return false; } public override int GetHashCode() { return base.GetHashCode(); } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { WriteEnumValue(xmlWriter, obj); } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { object obj = ReadEnumValue(xmlReader); context?.AddNewObject(obj); return obj; } } [AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = false)] public sealed class EnumMemberAttribute : Attribute { private string value; private bool isValueSetExplicitly; public string Value { get { return value; } set { this.value = value; isValueSetExplicitly = true; } } public bool IsValueSetExplicitly => isValueSetExplicitly; } public class ExportOptions { private Collection knownTypes; private IDataContractSurrogate dataContractSurrogate; public IDataContractSurrogate DataContractSurrogate { get { return dataContractSurrogate; } set { dataContractSurrogate = value; } } public Collection KnownTypes { get { if (knownTypes == null) { knownTypes = new Collection(); } return knownTypes; } } internal IDataContractSurrogate GetSurrogate() { return dataContractSurrogate; } } public sealed class ExtensionDataObject { private IList members; internal IList Members { get { return members; } set { members = value; } } internal ExtensionDataObject() { } } internal class ExtensionDataMember { private string name; private string ns; private IDataNode value; private int memberIndex; public string Name { get { return name; } set { name = value; } } public string Namespace { get { return ns; } set { ns = value; } } public IDataNode Value { get { return value; } set { this.value = value; } } public int MemberIndex { get { return memberIndex; } set { memberIndex = value; } } } internal interface IDataNode { Type DataType { get; } object Value { get; set; } string DataContractName { get; set; } string DataContractNamespace { get; set; } string ClrTypeName { get; set; } string ClrAssemblyName { get; set; } string Id { get; set; } bool PreservesReferences { get; } bool IsFinalValue { get; set; } void GetData(ElementData element); void Clear(); } internal class DataNode : IDataNode { protected Type dataType; private T value; private string dataContractName; private string dataContractNamespace; private string clrTypeName; private string clrAssemblyName; private string id = Globals.NewObjectId; private bool isFinalValue; public Type DataType => dataType; public object Value { get { return value; } set { this.value = (T)value; } } bool IDataNode.IsFinalValue { get { return isFinalValue; } set { isFinalValue = value; } } public string DataContractName { get { return dataContractName; } set { dataContractName = value; } } public string DataContractNamespace { get { return dataContractNamespace; } set { dataContractNamespace = value; } } public string ClrTypeName { get { return clrTypeName; } set { clrTypeName = value; } } public string ClrAssemblyName { get { return clrAssemblyName; } set { clrAssemblyName = value; } } public bool PreservesReferences => Id != Globals.NewObjectId; public string Id { get { return id; } set { id = value; } } internal DataNode() { dataType = typeof(T); isFinalValue = true; } internal DataNode(T value) : this() { this.value = value; } public T GetValue() { return value; } public virtual void GetData(ElementData element) { element.dataNode = this; element.attributeCount = 0; element.childElementIndex = 0; if (DataContractName != null) { AddQualifiedNameAttribute(element, "i", "type", "http://www.w3.org/2001/XMLSchema-instance", DataContractName, DataContractNamespace); } if (ClrTypeName != null) { element.AddAttribute("z", "http://schemas.microsoft.com/2003/10/Serialization/", "Type", ClrTypeName); } if (ClrAssemblyName != null) { element.AddAttribute("z", "http://schemas.microsoft.com/2003/10/Serialization/", "Assembly", ClrAssemblyName); } } public virtual void Clear() { clrTypeName = (clrAssemblyName = null); } internal void AddQualifiedNameAttribute(ElementData element, string elementPrefix, string elementName, string elementNs, string valueName, string valueNs) { string prefix = ExtensionDataReader.GetPrefix(valueNs); element.AddAttribute(elementPrefix, elementNs, elementName, string.Format(CultureInfo.InvariantCulture, "{0}:{1}", prefix, valueName)); bool flag = false; if (element.attributes != null) { for (int i = 0; i < element.attributes.Length; i++) { AttributeData attributeData = element.attributes[i]; if (attributeData != null && attributeData.prefix == "xmlns" && attributeData.localName == prefix) { flag = true; break; } } } if (!flag) { element.AddAttribute("xmlns", "http://www.w3.org/2000/xmlns/", prefix, valueNs); } } } internal class ClassDataNode : DataNode { private IList members; internal IList Members { get { return members; } set { members = value; } } internal ClassDataNode() { dataType = Globals.TypeOfClassDataNode; } public override void Clear() { base.Clear(); members = null; } } internal class CollectionDataNode : DataNode { private IList items; private string itemName; private string itemNamespace; private int size = -1; internal IList Items { get { return items; } set { items = value; } } internal string ItemName { get { return itemName; } set { itemName = value; } } internal string ItemNamespace { get { return itemNamespace; } set { itemNamespace = value; } } internal int Size { get { return size; } set { size = value; } } internal CollectionDataNode() { dataType = Globals.TypeOfCollectionDataNode; } public override void GetData(ElementData element) { base.GetData(element); element.AddAttribute("z", "http://schemas.microsoft.com/2003/10/Serialization/", "Size", Size.ToString(NumberFormatInfo.InvariantInfo)); } public override void Clear() { base.Clear(); items = null; size = -1; } } internal class XmlDataNode : DataNode { private IList xmlAttributes; private IList xmlChildNodes; private XmlDocument ownerDocument; internal IList XmlAttributes { get { return xmlAttributes; } set { xmlAttributes = value; } } internal IList XmlChildNodes { get { return xmlChildNodes; } set { xmlChildNodes = value; } } internal XmlDocument OwnerDocument { get { return ownerDocument; } set { ownerDocument = value; } } internal XmlDataNode() { dataType = Globals.TypeOfXmlDataNode; } public override void Clear() { base.Clear(); xmlAttributes = null; xmlChildNodes = null; ownerDocument = null; } } internal class ISerializableDataNode : DataNode { private string factoryTypeName; private string factoryTypeNamespace; private IList members; internal string FactoryTypeName { get { return factoryTypeName; } set { factoryTypeName = value; } } internal string FactoryTypeNamespace { get { return factoryTypeNamespace; } set { factoryTypeNamespace = value; } } internal IList Members { get { return members; } set { members = value; } } internal ISerializableDataNode() { dataType = Globals.TypeOfISerializableDataNode; } public override void GetData(ElementData element) { base.GetData(element); if (FactoryTypeName != null) { AddQualifiedNameAttribute(element, "z", "FactoryType", "http://schemas.microsoft.com/2003/10/Serialization/", FactoryTypeName, FactoryTypeNamespace); } } public override void Clear() { base.Clear(); members = null; factoryTypeName = (factoryTypeNamespace = null); } } internal class ISerializableDataMember { private string name; private IDataNode value; internal string Name { get { return name; } set { name = value; } } internal IDataNode Value { get { return value; } set { this.value = value; } } } internal class ExtensionDataReader : XmlReader { private enum ExtensionDataNodeType { None, Element, EndElement, Text, Xml, ReferencedElement, NullElement } private Hashtable cache = new Hashtable(); private ElementData[] elements; private ElementData element; private ElementData nextElement; private ReadState readState; private ExtensionDataNodeType internalNodeType; private XmlNodeType nodeType; private int depth; private string localName; private string ns; private string prefix; private string value; private int attributeCount; private int attributeIndex; private XmlNodeReader xmlNodeReader; private Queue deserializedDataNodes; private XmlObjectSerializerReadContext context; [SecurityCritical] private static Dictionary nsToPrefixTable; [SecurityCritical] private static Dictionary prefixToNsTable; private bool IsXmlDataNode => internalNodeType == ExtensionDataNodeType.Xml; public override XmlNodeType NodeType { get { if (!IsXmlDataNode) { return nodeType; } return xmlNodeReader.NodeType; } } public override string LocalName { get { if (!IsXmlDataNode) { return localName; } return xmlNodeReader.LocalName; } } public override string NamespaceURI { get { if (!IsXmlDataNode) { return ns; } return xmlNodeReader.NamespaceURI; } } public override string Prefix { get { if (!IsXmlDataNode) { return prefix; } return xmlNodeReader.Prefix; } } public override string Value { get { if (!IsXmlDataNode) { return value; } return xmlNodeReader.Value; } } public override int Depth { get { if (!IsXmlDataNode) { return depth; } return xmlNodeReader.Depth; } } public override int AttributeCount { get { if (!IsXmlDataNode) { return attributeCount; } return xmlNodeReader.AttributeCount; } } public override bool EOF { get { if (!IsXmlDataNode) { return readState == ReadState.EndOfFile; } return xmlNodeReader.EOF; } } public override ReadState ReadState { get { if (!IsXmlDataNode) { return readState; } return xmlNodeReader.ReadState; } } public override bool IsEmptyElement { get { if (!IsXmlDataNode) { return false; } return xmlNodeReader.IsEmptyElement; } } public override bool IsDefault { get { if (!IsXmlDataNode) { return base.IsDefault; } return xmlNodeReader.IsDefault; } } public override char QuoteChar { get { if (!IsXmlDataNode) { return base.QuoteChar; } return xmlNodeReader.QuoteChar; } } public override XmlSpace XmlSpace { get { if (!IsXmlDataNode) { return base.XmlSpace; } return xmlNodeReader.XmlSpace; } } public override string XmlLang { get { if (!IsXmlDataNode) { return base.XmlLang; } return xmlNodeReader.XmlLang; } } public override string this[int i] { get { if (!IsXmlDataNode) { return GetAttribute(i); } return xmlNodeReader[i]; } } public override string this[string name] { get { if (!IsXmlDataNode) { return GetAttribute(name); } return xmlNodeReader[name]; } } public override string this[string name, string namespaceURI] { get { if (!IsXmlDataNode) { return GetAttribute(name, namespaceURI); } return xmlNodeReader[name, namespaceURI]; } } public override string Name { get { if (IsXmlDataNode) { return xmlNodeReader.Name; } return string.Empty; } } public override bool HasValue { get { if (IsXmlDataNode) { return xmlNodeReader.HasValue; } return false; } } public override string BaseURI { get { if (IsXmlDataNode) { return xmlNodeReader.BaseURI; } return string.Empty; } } public override XmlNameTable NameTable { get { if (IsXmlDataNode) { return xmlNodeReader.NameTable; } return null; } } [SecuritySafeCritical] static ExtensionDataReader() { nsToPrefixTable = new Dictionary(); prefixToNsTable = new Dictionary(); AddPrefix("i", "http://www.w3.org/2001/XMLSchema-instance"); AddPrefix("z", "http://schemas.microsoft.com/2003/10/Serialization/"); AddPrefix(string.Empty, string.Empty); } internal ExtensionDataReader(XmlObjectSerializerReadContext context) { attributeIndex = -1; this.context = context; } internal void SetDeserializedValue(object obj) { IDataNode dataNode = ((deserializedDataNodes == null || deserializedDataNodes.Count == 0) ? null : deserializedDataNodes.Dequeue()); if (dataNode != null && !(obj is IDataNode)) { dataNode.Value = obj; dataNode.IsFinalValue = true; } } internal IDataNode GetCurrentNode() { IDataNode dataNode = element.dataNode; Skip(); return dataNode; } internal void SetDataNode(IDataNode dataNode, string name, string ns) { SetNextElement(dataNode, name, ns, null); element = nextElement; nextElement = null; SetElement(); } internal void Reset() { localName = null; ns = null; prefix = null; value = null; attributeCount = 0; attributeIndex = -1; depth = 0; element = null; nextElement = null; elements = null; deserializedDataNodes = null; } public override bool MoveToFirstAttribute() { if (IsXmlDataNode) { return xmlNodeReader.MoveToFirstAttribute(); } if (attributeCount == 0) { return false; } MoveToAttribute(0); return true; } public override bool MoveToNextAttribute() { if (IsXmlDataNode) { return xmlNodeReader.MoveToNextAttribute(); } if (attributeIndex + 1 >= attributeCount) { return false; } MoveToAttribute(attributeIndex + 1); return true; } public override void MoveToAttribute(int index) { if (IsXmlDataNode) { xmlNodeReader.MoveToAttribute(index); return; } if (index < 0 || index >= attributeCount) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Invalid XML while deserializing extension data."))); } nodeType = XmlNodeType.Attribute; AttributeData attributeData = element.attributes[index]; localName = attributeData.localName; ns = attributeData.ns; prefix = attributeData.prefix; value = attributeData.value; attributeIndex = index; } public override string GetAttribute(string name, string namespaceURI) { if (IsXmlDataNode) { return xmlNodeReader.GetAttribute(name, namespaceURI); } for (int i = 0; i < element.attributeCount; i++) { AttributeData attributeData = element.attributes[i]; if (attributeData.localName == name && attributeData.ns == namespaceURI) { return attributeData.value; } } return null; } public override bool MoveToAttribute(string name, string namespaceURI) { if (IsXmlDataNode) { return xmlNodeReader.MoveToAttribute(name, ns); } for (int i = 0; i < element.attributeCount; i++) { AttributeData attributeData = element.attributes[i]; if (attributeData.localName == name && attributeData.ns == namespaceURI) { MoveToAttribute(i); return true; } } return false; } public override bool MoveToElement() { if (IsXmlDataNode) { return xmlNodeReader.MoveToElement(); } if (nodeType != XmlNodeType.Attribute) { return false; } SetElement(); return true; } private void SetElement() { nodeType = XmlNodeType.Element; localName = element.localName; ns = element.ns; prefix = element.prefix; value = string.Empty; attributeCount = element.attributeCount; attributeIndex = -1; } [SecuritySafeCritical] public override string LookupNamespace(string prefix) { if (IsXmlDataNode) { return xmlNodeReader.LookupNamespace(prefix); } if (!prefixToNsTable.TryGetValue(prefix, out var result)) { return null; } return result; } public override void Skip() { if (IsXmlDataNode) { xmlNodeReader.Skip(); } else { if (ReadState != ReadState.Interactive) { return; } MoveToElement(); if (IsElementNode(internalNodeType)) { int num = 1; while (num != 0) { if (!Read()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Invalid XML while deserializing extension data."))); } if (IsElementNode(internalNodeType)) { num++; } else if (internalNodeType == ExtensionDataNodeType.EndElement) { ReadEndElement(); num--; } } } else { Read(); } } } private bool IsElementNode(ExtensionDataNodeType nodeType) { if (nodeType != ExtensionDataNodeType.Element && nodeType != ExtensionDataNodeType.ReferencedElement) { return nodeType == ExtensionDataNodeType.NullElement; } return true; } public override void Close() { if (IsXmlDataNode) { xmlNodeReader.Close(); return; } Reset(); readState = ReadState.Closed; } public override bool Read() { if (nodeType == XmlNodeType.Attribute && MoveToNextAttribute()) { return true; } MoveNext(element.dataNode); switch (internalNodeType) { case ExtensionDataNodeType.Element: case ExtensionDataNodeType.ReferencedElement: case ExtensionDataNodeType.NullElement: PushElement(); SetElement(); break; case ExtensionDataNodeType.Text: nodeType = XmlNodeType.Text; prefix = string.Empty; ns = string.Empty; localName = string.Empty; attributeCount = 0; attributeIndex = -1; break; case ExtensionDataNodeType.EndElement: nodeType = XmlNodeType.EndElement; prefix = string.Empty; ns = string.Empty; localName = string.Empty; value = string.Empty; attributeCount = 0; attributeIndex = -1; PopElement(); break; case ExtensionDataNodeType.None: if (depth != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Invalid XML while deserializing extension data."))); } nodeType = XmlNodeType.None; prefix = string.Empty; ns = string.Empty; localName = string.Empty; value = string.Empty; attributeCount = 0; readState = ReadState.EndOfFile; return false; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString("Invalid state in extension data reader."))); case ExtensionDataNodeType.Xml: break; } readState = ReadState.Interactive; return true; } public override string GetAttribute(string name) { if (IsXmlDataNode) { return xmlNodeReader.GetAttribute(name); } return null; } public override string GetAttribute(int i) { if (IsXmlDataNode) { return xmlNodeReader.GetAttribute(i); } return null; } public override bool MoveToAttribute(string name) { if (IsXmlDataNode) { return xmlNodeReader.MoveToAttribute(name); } return false; } public override void ResolveEntity() { if (IsXmlDataNode) { xmlNodeReader.ResolveEntity(); } } public override bool ReadAttributeValue() { if (IsXmlDataNode) { return xmlNodeReader.ReadAttributeValue(); } return false; } private void MoveNext(IDataNode dataNode) { ExtensionDataNodeType extensionDataNodeType = internalNodeType; if (extensionDataNodeType == ExtensionDataNodeType.Text || (uint)(extensionDataNodeType - 5) <= 1u) { internalNodeType = ExtensionDataNodeType.EndElement; return; } Type dataType = dataNode.DataType; if (dataType == Globals.TypeOfClassDataNode) { MoveNextInClass((ClassDataNode)dataNode); return; } if (dataType == Globals.TypeOfCollectionDataNode) { MoveNextInCollection((CollectionDataNode)dataNode); return; } if (dataType == Globals.TypeOfISerializableDataNode) { MoveNextInISerializable((ISerializableDataNode)dataNode); return; } if (dataType == Globals.TypeOfXmlDataNode) { MoveNextInXml((XmlDataNode)dataNode); return; } if (dataNode.Value != null) { MoveToDeserializedObject(dataNode); return; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString("Invalid state in extension data reader."))); } private void SetNextElement(IDataNode node, string name, string ns, string prefix) { internalNodeType = ExtensionDataNodeType.Element; nextElement = GetNextElement(); nextElement.localName = name; nextElement.ns = ns; nextElement.prefix = prefix; if (node == null) { nextElement.attributeCount = 0; nextElement.AddAttribute("i", "http://www.w3.org/2001/XMLSchema-instance", "nil", "true"); internalNodeType = ExtensionDataNodeType.NullElement; } else if (!CheckIfNodeHandled(node)) { AddDeserializedDataNode(node); node.GetData(nextElement); if (node is XmlDataNode) { MoveNextInXml((XmlDataNode)node); } } } private void AddDeserializedDataNode(IDataNode node) { if (node.Id != Globals.NewObjectId && (node.Value == null || !node.IsFinalValue)) { if (deserializedDataNodes == null) { deserializedDataNodes = new Queue(); } deserializedDataNodes.Enqueue(node); } } private bool CheckIfNodeHandled(IDataNode node) { bool flag = false; if (node.Id != Globals.NewObjectId) { flag = cache[node] != null; if (flag) { if (nextElement == null) { nextElement = GetNextElement(); } nextElement.attributeCount = 0; nextElement.AddAttribute("z", "http://schemas.microsoft.com/2003/10/Serialization/", "Ref", node.Id.ToString(NumberFormatInfo.InvariantInfo)); nextElement.AddAttribute("i", "http://www.w3.org/2001/XMLSchema-instance", "nil", "true"); internalNodeType = ExtensionDataNodeType.ReferencedElement; } else { cache.Add(node, node); } } return flag; } private void MoveNextInClass(ClassDataNode dataNode) { if (dataNode.Members != null && element.childElementIndex < dataNode.Members.Count) { if (element.childElementIndex == 0) { context.IncrementItemCount(-dataNode.Members.Count); } ExtensionDataMember extensionDataMember = dataNode.Members[element.childElementIndex++]; SetNextElement(extensionDataMember.Value, extensionDataMember.Name, extensionDataMember.Namespace, GetPrefix(extensionDataMember.Namespace)); } else { internalNodeType = ExtensionDataNodeType.EndElement; element.childElementIndex = 0; } } private void MoveNextInCollection(CollectionDataNode dataNode) { if (dataNode.Items != null && element.childElementIndex < dataNode.Items.Count) { if (element.childElementIndex == 0) { context.IncrementItemCount(-dataNode.Items.Count); } IDataNode node = dataNode.Items[element.childElementIndex++]; SetNextElement(node, dataNode.ItemName, dataNode.ItemNamespace, GetPrefix(dataNode.ItemNamespace)); } else { internalNodeType = ExtensionDataNodeType.EndElement; element.childElementIndex = 0; } } private void MoveNextInISerializable(ISerializableDataNode dataNode) { if (dataNode.Members != null && element.childElementIndex < dataNode.Members.Count) { if (element.childElementIndex == 0) { context.IncrementItemCount(-dataNode.Members.Count); } ISerializableDataMember serializableDataMember = dataNode.Members[element.childElementIndex++]; SetNextElement(serializableDataMember.Value, serializableDataMember.Name, string.Empty, string.Empty); } else { internalNodeType = ExtensionDataNodeType.EndElement; element.childElementIndex = 0; } } private void MoveNextInXml(XmlDataNode dataNode) { if (IsXmlDataNode) { xmlNodeReader.Read(); if (xmlNodeReader.Depth == 0) { internalNodeType = ExtensionDataNodeType.EndElement; xmlNodeReader = null; } return; } internalNodeType = ExtensionDataNodeType.Xml; if (element == null) { element = nextElement; } else { PushElement(); } XmlNode xmlNode = XmlObjectSerializerReadContext.CreateWrapperXmlElement(dataNode.OwnerDocument, dataNode.XmlAttributes, dataNode.XmlChildNodes, element.prefix, element.localName, element.ns); for (int i = 0; i < element.attributeCount; i++) { AttributeData attributeData = element.attributes[i]; XmlAttribute xmlAttribute = dataNode.OwnerDocument.CreateAttribute(attributeData.prefix, attributeData.localName, attributeData.ns); xmlAttribute.Value = attributeData.value; xmlNode.Attributes.Append(xmlAttribute); } xmlNodeReader = new XmlNodeReader(xmlNode); xmlNodeReader.Read(); } private void MoveToDeserializedObject(IDataNode dataNode) { Type type = dataNode.DataType; bool isTypedNode = true; if (type == Globals.TypeOfObject) { type = dataNode.Value.GetType(); if (type == Globals.TypeOfObject) { internalNodeType = ExtensionDataNodeType.EndElement; return; } isTypedNode = false; } if (!MoveToText(type, dataNode, isTypedNode)) { if (!dataNode.IsFinalValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Invalid data node for '{0}' type.", DataContract.GetClrTypeFullName(type)))); } internalNodeType = ExtensionDataNodeType.EndElement; } } private bool MoveToText(Type type, IDataNode dataNode, bool isTypedNode) { bool flag = true; switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: value = XmlConvert.ToString(isTypedNode ? ((DataNode)dataNode).GetValue() : ((bool)dataNode.Value)); break; case TypeCode.Char: value = XmlConvert.ToString((int)(isTypedNode ? ((DataNode)dataNode).GetValue() : ((char)dataNode.Value))); break; case TypeCode.Byte: value = XmlConvert.ToString(isTypedNode ? ((DataNode)dataNode).GetValue() : ((byte)dataNode.Value)); break; case TypeCode.Int16: value = XmlConvert.ToString(isTypedNode ? ((DataNode)dataNode).GetValue() : ((short)dataNode.Value)); break; case TypeCode.Int32: value = XmlConvert.ToString(isTypedNode ? ((DataNode)dataNode).GetValue() : ((int)dataNode.Value)); break; case TypeCode.Int64: value = XmlConvert.ToString(isTypedNode ? ((DataNode)dataNode).GetValue() : ((long)dataNode.Value)); break; case TypeCode.Single: value = XmlConvert.ToString(isTypedNode ? ((DataNode)dataNode).GetValue() : ((float)dataNode.Value)); break; case TypeCode.Double: value = XmlConvert.ToString(isTypedNode ? ((DataNode)dataNode).GetValue() : ((double)dataNode.Value)); break; case TypeCode.Decimal: value = XmlConvert.ToString(isTypedNode ? ((DataNode)dataNode).GetValue() : ((decimal)dataNode.Value)); break; case TypeCode.DateTime: value = (isTypedNode ? ((DataNode)dataNode).GetValue() : ((DateTime)dataNode.Value)).ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", DateTimeFormatInfo.InvariantInfo); break; case TypeCode.String: value = (isTypedNode ? ((DataNode)dataNode).GetValue() : ((string)dataNode.Value)); break; case TypeCode.SByte: value = XmlConvert.ToString(isTypedNode ? ((DataNode)dataNode).GetValue() : ((sbyte)dataNode.Value)); break; case TypeCode.UInt16: value = XmlConvert.ToString(isTypedNode ? ((DataNode)dataNode).GetValue() : ((ushort)dataNode.Value)); break; case TypeCode.UInt32: value = XmlConvert.ToString(isTypedNode ? ((DataNode)dataNode).GetValue() : ((uint)dataNode.Value)); break; case TypeCode.UInt64: value = XmlConvert.ToString(isTypedNode ? ((DataNode)dataNode).GetValue() : ((ulong)dataNode.Value)); break; default: if (type == Globals.TypeOfByteArray) { byte[] array = (isTypedNode ? ((DataNode)dataNode).GetValue() : ((byte[])dataNode.Value)); value = ((array == null) ? string.Empty : Convert.ToBase64String(array)); } else if (type == Globals.TypeOfTimeSpan) { value = XmlConvert.ToString(isTypedNode ? ((DataNode)dataNode).GetValue() : ((TimeSpan)dataNode.Value)); } else if (type == Globals.TypeOfGuid) { value = (isTypedNode ? ((DataNode)dataNode).GetValue() : ((Guid)dataNode.Value)).ToString(); } else if (type == Globals.TypeOfUri) { Uri uri = (isTypedNode ? ((DataNode)dataNode).GetValue() : ((Uri)dataNode.Value)); value = uri.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped); } else { flag = false; } break; } if (flag) { internalNodeType = ExtensionDataNodeType.Text; } return flag; } private void PushElement() { GrowElementsIfNeeded(); elements[depth++] = element; if (nextElement == null) { element = GetNextElement(); return; } element = nextElement; nextElement = null; } private void PopElement() { prefix = element.prefix; localName = element.localName; ns = element.ns; if (depth != 0) { depth--; if (elements != null) { element = elements[depth]; } } } private void GrowElementsIfNeeded() { if (elements == null) { elements = new ElementData[8]; } else if (elements.Length == depth) { ElementData[] destinationArray = new ElementData[elements.Length * 2]; Array.Copy(elements, 0, destinationArray, 0, elements.Length); elements = destinationArray; } } private ElementData GetNextElement() { int num = depth + 1; if (elements != null && elements.Length > num && elements[num] != null) { return elements[num]; } return new ElementData(); } [SecuritySafeCritical] internal static string GetPrefix(string ns) { ns = ns ?? string.Empty; if (!nsToPrefixTable.TryGetValue(ns, out var result)) { lock (nsToPrefixTable) { if (!nsToPrefixTable.TryGetValue(ns, out result)) { result = ((ns == null || ns.Length == 0) ? string.Empty : ("p" + nsToPrefixTable.Count)); AddPrefix(result, ns); } } } return result; } [SecuritySafeCritical] private static void AddPrefix(string prefix, string ns) { nsToPrefixTable.Add(ns, prefix); prefixToNsTable.Add(prefix, ns); } } internal class AttributeData { public string prefix; public string ns; public string localName; public string value; } internal class ElementData { public string localName; public string ns; public string prefix; public int attributeCount; public AttributeData[] attributes; public IDataNode dataNode; public int childElementIndex; public void AddAttribute(string prefix, string ns, string name, string value) { GrowAttributesIfNeeded(); AttributeData attributeData = attributes[attributeCount]; if (attributeData == null) { attributeData = (attributes[attributeCount] = new AttributeData()); } attributeData.prefix = prefix; attributeData.ns = ns; attributeData.localName = name; attributeData.value = value; attributeCount++; } private void GrowAttributesIfNeeded() { if (attributes == null) { attributes = new AttributeData[4]; } else if (attributes.Length == attributeCount) { AttributeData[] destinationArray = new AttributeData[attributes.Length * 2]; Array.Copy(attributes, 0, destinationArray, 0, attributes.Length); attributes = destinationArray; } } } internal sealed class GenericParameterDataContract : DataContract { private class GenericParameterDataContractCriticalHelper : DataContractCriticalHelper { private int parameterPosition; internal int ParameterPosition => parameterPosition; internal GenericParameterDataContractCriticalHelper(Type type) : base(type) { SetDataContractName(DataContract.GetStableName(type)); parameterPosition = type.GenericParameterPosition; } } [SecurityCritical] private GenericParameterDataContractCriticalHelper helper; internal int ParameterPosition { [SecuritySafeCritical] get { return helper.ParameterPosition; } } internal override bool IsBuiltInDataContract => true; [SecuritySafeCritical] internal GenericParameterDataContract(Type type) : base(new GenericParameterDataContractCriticalHelper(type)) { helper = base.Helper as GenericParameterDataContractCriticalHelper; } internal override DataContract BindGenericParameters(DataContract[] paramContracts, Dictionary boundContracts) { return paramContracts[ParameterPosition]; } } internal static class Globals { internal const BindingFlags ScanAllMembers = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; [SecurityCritical] private static XmlQualifiedName idQualifiedName; [SecurityCritical] private static XmlQualifiedName refQualifiedName; [SecurityCritical] private static Type typeOfObject; [SecurityCritical] private static Type typeOfValueType; [SecurityCritical] private static Type typeOfArray; [SecurityCritical] private static Type typeOfString; [SecurityCritical] private static Type typeOfInt; [SecurityCritical] private static Type typeOfULong; [SecurityCritical] private static Type typeOfVoid; [SecurityCritical] private static Type typeOfByteArray; [SecurityCritical] private static Type typeOfTimeSpan; [SecurityCritical] private static Type typeOfGuid; [SecurityCritical] private static Type typeOfDateTimeOffset; [SecurityCritical] private static Type typeOfDateTimeOffsetAdapter; [SecurityCritical] private static Type typeOfUri; [SecurityCritical] private static Type typeOfTypeEnumerable; [SecurityCritical] private static Type typeOfStreamingContext; [SecurityCritical] private static Type typeOfISerializable; [SecurityCritical] private static Type typeOfIDeserializationCallback; [SecurityCritical] private static Type typeOfIObjectReference; [SecurityCritical] private static Type typeOfXmlFormatClassWriterDelegate; [SecurityCritical] private static Type typeOfXmlFormatCollectionWriterDelegate; [SecurityCritical] private static Type typeOfXmlFormatClassReaderDelegate; [SecurityCritical] private static Type typeOfXmlFormatCollectionReaderDelegate; [SecurityCritical] private static Type typeOfXmlFormatGetOnlyCollectionReaderDelegate; [SecurityCritical] private static Type typeOfKnownTypeAttribute; [SecurityCritical] private static Type typeOfDataContractAttribute; [SecurityCritical] private static Type typeOfContractNamespaceAttribute; [SecurityCritical] private static Type typeOfDataMemberAttribute; [SecurityCritical] private static Type typeOfEnumMemberAttribute; [SecurityCritical] private static Type typeOfCollectionDataContractAttribute; [SecurityCritical] private static Type typeOfOptionalFieldAttribute; [SecurityCritical] private static Type typeOfObjectArray; [SecurityCritical] private static Type typeOfOnSerializingAttribute; [SecurityCritical] private static Type typeOfOnSerializedAttribute; [SecurityCritical] private static Type typeOfOnDeserializingAttribute; [SecurityCritical] private static Type typeOfOnDeserializedAttribute; [SecurityCritical] private static Type typeOfFlagsAttribute; [SecurityCritical] private static Type typeOfSerializableAttribute; [SecurityCritical] private static Type typeOfNonSerializedAttribute; [SecurityCritical] private static Type typeOfSerializationInfo; [SecurityCritical] private static Type typeOfSerializationInfoEnumerator; [SecurityCritical] private static Type typeOfSerializationEntry; [SecurityCritical] private static Type typeOfIXmlSerializable; [SecurityCritical] private static Type typeOfXmlSchemaProviderAttribute; [SecurityCritical] private static Type typeOfXmlRootAttribute; [SecurityCritical] private static Type typeOfXmlQualifiedName; [SecurityCritical] private static Type typeOfXmlSchemaType; [SecurityCritical] private static Type typeOfXmlSerializableServices; [SecurityCritical] private static Type typeOfXmlNodeArray; [SecurityCritical] private static Type typeOfXmlSchemaSet; [SecurityCritical] private static object[] emptyObjectArray; [SecurityCritical] private static Type[] emptyTypeArray; [SecurityCritical] private static Type typeOfIPropertyChange; [SecurityCritical] private static Type typeOfIExtensibleDataObject; [SecurityCritical] private static Type typeOfExtensionDataObject; [SecurityCritical] private static Type typeOfISerializableDataNode; [SecurityCritical] private static Type typeOfClassDataNode; [SecurityCritical] private static Type typeOfCollectionDataNode; [SecurityCritical] private static Type typeOfXmlDataNode; [SecurityCritical] private static Type typeOfNullable; [SecurityCritical] private static Type typeOfReflectionPointer; [SecurityCritical] private static Type typeOfIDictionaryGeneric; [SecurityCritical] private static Type typeOfIDictionary; [SecurityCritical] private static Type typeOfIListGeneric; [SecurityCritical] private static Type typeOfIList; [SecurityCritical] private static Type typeOfICollectionGeneric; [SecurityCritical] private static Type typeOfICollection; [SecurityCritical] private static Type typeOfIEnumerableGeneric; [SecurityCritical] private static Type typeOfIEnumerable; [SecurityCritical] private static Type typeOfIEnumeratorGeneric; [SecurityCritical] private static Type typeOfIEnumerator; [SecurityCritical] private static Type typeOfKeyValuePair; [SecurityCritical] private static Type typeOfKeyValue; [SecurityCritical] private static Type typeOfIDictionaryEnumerator; [SecurityCritical] private static Type typeOfDictionaryEnumerator; [SecurityCritical] private static Type typeOfGenericDictionaryEnumerator; [SecurityCritical] private static Type typeOfDictionaryGeneric; [SecurityCritical] private static Type typeOfHashtable; [SecurityCritical] private static Type typeOfListGeneric; [SecurityCritical] private static Type typeOfXmlElement; [SecurityCritical] private static Type typeOfDBNull; [SecurityCritical] private static Uri dataContractXsdBaseNamespaceUri; public const bool DefaultIsRequired = false; public const bool DefaultEmitDefaultValue = true; public const int DefaultOrder = 0; public const bool DefaultIsReference = false; public static readonly string NewObjectId = string.Empty; public const string SimpleSRSInternalsVisiblePattern = "^[\\s]*System\\.Runtime\\.Serialization[\\s]*$"; public const string FullSRSInternalsVisiblePattern = "^[\\s]*System\\.Runtime\\.Serialization[\\s]*,[\\s]*PublicKey[\\s]*=[\\s]*(?i:00000000000000000400000000000000)[\\s]*$"; public const string NullObjectId = null; public const string Space = " "; public const string OpenBracket = "["; public const string CloseBracket = "]"; public const string Comma = ","; public const string XsiPrefix = "i"; public const string XsdPrefix = "x"; public const string SerPrefix = "z"; public const string SerPrefixForSchema = "ser"; public const string ElementPrefix = "q"; public const string DataContractXsdBaseNamespace = "http://schemas.datacontract.org/2004/07/"; public const string DataContractXmlNamespace = "http://schemas.datacontract.org/2004/07/System.Xml"; public const string SchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance"; public const string SchemaNamespace = "http://www.w3.org/2001/XMLSchema"; public const string XsiNilLocalName = "nil"; public const string XsiTypeLocalName = "type"; public const string TnsPrefix = "tns"; public const string OccursUnbounded = "unbounded"; public const string AnyTypeLocalName = "anyType"; public const string StringLocalName = "string"; public const string IntLocalName = "int"; public const string True = "true"; public const string False = "false"; public const string ArrayPrefix = "ArrayOf"; public const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/"; public const string XmlnsPrefix = "xmlns"; public const string SchemaLocalName = "schema"; public const string CollectionsNamespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays"; public const string DefaultClrNamespace = "GeneratedNamespace"; public const string DefaultTypeName = "GeneratedType"; public const string DefaultGeneratedMember = "GeneratedMember"; public const string DefaultFieldSuffix = "Field"; public const string DefaultPropertySuffix = "Property"; public const string DefaultMemberSuffix = "Member"; public const string NameProperty = "Name"; public const string NamespaceProperty = "Namespace"; public const string OrderProperty = "Order"; public const string IsReferenceProperty = "IsReference"; public const string IsRequiredProperty = "IsRequired"; public const string EmitDefaultValueProperty = "EmitDefaultValue"; public const string ClrNamespaceProperty = "ClrNamespace"; public const string ItemNameProperty = "ItemName"; public const string KeyNameProperty = "KeyName"; public const string ValueNameProperty = "ValueName"; public const string SerializationInfoPropertyName = "SerializationInfo"; public const string SerializationInfoFieldName = "info"; public const string NodeArrayPropertyName = "Nodes"; public const string NodeArrayFieldName = "nodesField"; public const string ExportSchemaMethod = "ExportSchema"; public const string IsAnyProperty = "IsAny"; public const string ContextFieldName = "context"; public const string GetObjectDataMethodName = "GetObjectData"; public const string GetEnumeratorMethodName = "GetEnumerator"; public const string MoveNextMethodName = "MoveNext"; public const string AddValueMethodName = "AddValue"; public const string CurrentPropertyName = "Current"; public const string ValueProperty = "Value"; public const string EnumeratorFieldName = "enumerator"; public const string SerializationEntryFieldName = "entry"; public const string ExtensionDataSetMethod = "set_ExtensionData"; public const string ExtensionDataSetExplicitMethod = "System.Runtime.Serialization.IExtensibleDataObject.set_ExtensionData"; public const string ExtensionDataObjectPropertyName = "ExtensionData"; public const string ExtensionDataObjectFieldName = "extensionDataField"; public const string AddMethodName = "Add"; public const string ParseMethodName = "Parse"; public const string GetCurrentMethodName = "get_Current"; public const string SerializationNamespace = "http://schemas.microsoft.com/2003/10/Serialization/"; public const string ClrTypeLocalName = "Type"; public const string ClrAssemblyLocalName = "Assembly"; public const string IsValueTypeLocalName = "IsValueType"; public const string EnumerationValueLocalName = "EnumerationValue"; public const string SurrogateDataLocalName = "Surrogate"; public const string GenericTypeLocalName = "GenericType"; public const string GenericParameterLocalName = "GenericParameter"; public const string GenericNameAttribute = "Name"; public const string GenericNamespaceAttribute = "Namespace"; public const string GenericParameterNestedLevelAttribute = "NestedLevel"; public const string IsDictionaryLocalName = "IsDictionary"; public const string ActualTypeLocalName = "ActualType"; public const string ActualTypeNameAttribute = "Name"; public const string ActualTypeNamespaceAttribute = "Namespace"; public const string DefaultValueLocalName = "DefaultValue"; public const string EmitDefaultValueAttribute = "EmitDefaultValue"; public const string ISerializableFactoryTypeLocalName = "FactoryType"; public const string IdLocalName = "Id"; public const string RefLocalName = "Ref"; public const string ArraySizeLocalName = "Size"; public const string KeyLocalName = "Key"; public const string ValueLocalName = "Value"; public const string MscorlibAssemblyName = "0"; public const string MscorlibAssemblySimpleName = "mscorlib"; public const string MscorlibFileName = "mscorlib.dll"; public const string SerializationSchema = "\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n"; internal static XmlQualifiedName IdQualifiedName { [SecuritySafeCritical] get { if (idQualifiedName == null) { idQualifiedName = new XmlQualifiedName("Id", "http://schemas.microsoft.com/2003/10/Serialization/"); } return idQualifiedName; } } internal static XmlQualifiedName RefQualifiedName { [SecuritySafeCritical] get { if (refQualifiedName == null) { refQualifiedName = new XmlQualifiedName("Ref", "http://schemas.microsoft.com/2003/10/Serialization/"); } return refQualifiedName; } } internal static Type TypeOfObject { [SecuritySafeCritical] get { if (typeOfObject == null) { typeOfObject = typeof(object); } return typeOfObject; } } internal static Type TypeOfValueType { [SecuritySafeCritical] get { if (typeOfValueType == null) { typeOfValueType = typeof(ValueType); } return typeOfValueType; } } internal static Type TypeOfArray { [SecuritySafeCritical] get { if (typeOfArray == null) { typeOfArray = typeof(Array); } return typeOfArray; } } internal static Type TypeOfString { [SecuritySafeCritical] get { if (typeOfString == null) { typeOfString = typeof(string); } return typeOfString; } } internal static Type TypeOfInt { [SecuritySafeCritical] get { if (typeOfInt == null) { typeOfInt = typeof(int); } return typeOfInt; } } internal static Type TypeOfULong { [SecuritySafeCritical] get { if (typeOfULong == null) { typeOfULong = typeof(ulong); } return typeOfULong; } } internal static Type TypeOfVoid { [SecuritySafeCritical] get { if (typeOfVoid == null) { typeOfVoid = typeof(void); } return typeOfVoid; } } internal static Type TypeOfByteArray { [SecuritySafeCritical] get { if (typeOfByteArray == null) { typeOfByteArray = typeof(byte[]); } return typeOfByteArray; } } internal static Type TypeOfTimeSpan { [SecuritySafeCritical] get { if (typeOfTimeSpan == null) { typeOfTimeSpan = typeof(TimeSpan); } return typeOfTimeSpan; } } internal static Type TypeOfGuid { [SecuritySafeCritical] get { if (typeOfGuid == null) { typeOfGuid = typeof(Guid); } return typeOfGuid; } } internal static Type TypeOfDateTimeOffset { [SecuritySafeCritical] get { if (typeOfDateTimeOffset == null) { typeOfDateTimeOffset = typeof(DateTimeOffset); } return typeOfDateTimeOffset; } } internal static Type TypeOfDateTimeOffsetAdapter { [SecuritySafeCritical] get { if (typeOfDateTimeOffsetAdapter == null) { typeOfDateTimeOffsetAdapter = typeof(DateTimeOffsetAdapter); } return typeOfDateTimeOffsetAdapter; } } internal static Type TypeOfUri { [SecuritySafeCritical] get { if (typeOfUri == null) { typeOfUri = typeof(Uri); } return typeOfUri; } } internal static Type TypeOfTypeEnumerable { [SecuritySafeCritical] get { if (typeOfTypeEnumerable == null) { typeOfTypeEnumerable = typeof(IEnumerable); } return typeOfTypeEnumerable; } } internal static Type TypeOfStreamingContext { [SecuritySafeCritical] get { if (typeOfStreamingContext == null) { typeOfStreamingContext = typeof(StreamingContext); } return typeOfStreamingContext; } } internal static Type TypeOfISerializable { [SecuritySafeCritical] get { if (typeOfISerializable == null) { typeOfISerializable = typeof(ISerializable); } return typeOfISerializable; } } internal static Type TypeOfIDeserializationCallback { [SecuritySafeCritical] get { if (typeOfIDeserializationCallback == null) { typeOfIDeserializationCallback = typeof(IDeserializationCallback); } return typeOfIDeserializationCallback; } } internal static Type TypeOfIObjectReference { [SecuritySafeCritical] get { if (typeOfIObjectReference == null) { typeOfIObjectReference = typeof(IObjectReference); } return typeOfIObjectReference; } } internal static Type TypeOfXmlFormatClassWriterDelegate { [SecuritySafeCritical] get { if (typeOfXmlFormatClassWriterDelegate == null) { typeOfXmlFormatClassWriterDelegate = typeof(XmlFormatClassWriterDelegate); } return typeOfXmlFormatClassWriterDelegate; } } internal static Type TypeOfXmlFormatCollectionWriterDelegate { [SecuritySafeCritical] get { if (typeOfXmlFormatCollectionWriterDelegate == null) { typeOfXmlFormatCollectionWriterDelegate = typeof(XmlFormatCollectionWriterDelegate); } return typeOfXmlFormatCollectionWriterDelegate; } } internal static Type TypeOfXmlFormatClassReaderDelegate { [SecuritySafeCritical] get { if (typeOfXmlFormatClassReaderDelegate == null) { typeOfXmlFormatClassReaderDelegate = typeof(XmlFormatClassReaderDelegate); } return typeOfXmlFormatClassReaderDelegate; } } internal static Type TypeOfXmlFormatCollectionReaderDelegate { [SecuritySafeCritical] get { if (typeOfXmlFormatCollectionReaderDelegate == null) { typeOfXmlFormatCollectionReaderDelegate = typeof(XmlFormatCollectionReaderDelegate); } return typeOfXmlFormatCollectionReaderDelegate; } } internal static Type TypeOfXmlFormatGetOnlyCollectionReaderDelegate { [SecuritySafeCritical] get { if (typeOfXmlFormatGetOnlyCollectionReaderDelegate == null) { typeOfXmlFormatGetOnlyCollectionReaderDelegate = typeof(XmlFormatGetOnlyCollectionReaderDelegate); } return typeOfXmlFormatGetOnlyCollectionReaderDelegate; } } internal static Type TypeOfKnownTypeAttribute { [SecuritySafeCritical] get { if (typeOfKnownTypeAttribute == null) { typeOfKnownTypeAttribute = typeof(KnownTypeAttribute); } return typeOfKnownTypeAttribute; } } internal static Type TypeOfDataContractAttribute { [SecuritySafeCritical] get { if (typeOfDataContractAttribute == null) { typeOfDataContractAttribute = typeof(DataContractAttribute); } return typeOfDataContractAttribute; } } internal static Type TypeOfContractNamespaceAttribute { [SecuritySafeCritical] get { if (typeOfContractNamespaceAttribute == null) { typeOfContractNamespaceAttribute = typeof(ContractNamespaceAttribute); } return typeOfContractNamespaceAttribute; } } internal static Type TypeOfDataMemberAttribute { [SecuritySafeCritical] get { if (typeOfDataMemberAttribute == null) { typeOfDataMemberAttribute = typeof(DataMemberAttribute); } return typeOfDataMemberAttribute; } } internal static Type TypeOfEnumMemberAttribute { [SecuritySafeCritical] get { if (typeOfEnumMemberAttribute == null) { typeOfEnumMemberAttribute = typeof(EnumMemberAttribute); } return typeOfEnumMemberAttribute; } } internal static Type TypeOfCollectionDataContractAttribute { [SecuritySafeCritical] get { if (typeOfCollectionDataContractAttribute == null) { typeOfCollectionDataContractAttribute = typeof(CollectionDataContractAttribute); } return typeOfCollectionDataContractAttribute; } } internal static Type TypeOfOptionalFieldAttribute { [SecuritySafeCritical] get { if (typeOfOptionalFieldAttribute == null) { typeOfOptionalFieldAttribute = typeof(OptionalFieldAttribute); } return typeOfOptionalFieldAttribute; } } internal static Type TypeOfObjectArray { [SecuritySafeCritical] get { if (typeOfObjectArray == null) { typeOfObjectArray = typeof(object[]); } return typeOfObjectArray; } } internal static Type TypeOfOnSerializingAttribute { [SecuritySafeCritical] get { if (typeOfOnSerializingAttribute == null) { typeOfOnSerializingAttribute = typeof(OnSerializingAttribute); } return typeOfOnSerializingAttribute; } } internal static Type TypeOfOnSerializedAttribute { [SecuritySafeCritical] get { if (typeOfOnSerializedAttribute == null) { typeOfOnSerializedAttribute = typeof(OnSerializedAttribute); } return typeOfOnSerializedAttribute; } } internal static Type TypeOfOnDeserializingAttribute { [SecuritySafeCritical] get { if (typeOfOnDeserializingAttribute == null) { typeOfOnDeserializingAttribute = typeof(OnDeserializingAttribute); } return typeOfOnDeserializingAttribute; } } internal static Type TypeOfOnDeserializedAttribute { [SecuritySafeCritical] get { if (typeOfOnDeserializedAttribute == null) { typeOfOnDeserializedAttribute = typeof(OnDeserializedAttribute); } return typeOfOnDeserializedAttribute; } } internal static Type TypeOfFlagsAttribute { [SecuritySafeCritical] get { if (typeOfFlagsAttribute == null) { typeOfFlagsAttribute = typeof(FlagsAttribute); } return typeOfFlagsAttribute; } } internal static Type TypeOfSerializableAttribute { [SecuritySafeCritical] get { if (typeOfSerializableAttribute == null) { typeOfSerializableAttribute = typeof(SerializableAttribute); } return typeOfSerializableAttribute; } } internal static Type TypeOfNonSerializedAttribute { [SecuritySafeCritical] get { if (typeOfNonSerializedAttribute == null) { typeOfNonSerializedAttribute = typeof(NonSerializedAttribute); } return typeOfNonSerializedAttribute; } } internal static Type TypeOfSerializationInfo { [SecuritySafeCritical] get { if (typeOfSerializationInfo == null) { typeOfSerializationInfo = typeof(SerializationInfo); } return typeOfSerializationInfo; } } internal static Type TypeOfSerializationInfoEnumerator { [SecuritySafeCritical] get { if (typeOfSerializationInfoEnumerator == null) { typeOfSerializationInfoEnumerator = typeof(SerializationInfoEnumerator); } return typeOfSerializationInfoEnumerator; } } internal static Type TypeOfSerializationEntry { [SecuritySafeCritical] get { if (typeOfSerializationEntry == null) { typeOfSerializationEntry = typeof(SerializationEntry); } return typeOfSerializationEntry; } } internal static Type TypeOfIXmlSerializable { [SecuritySafeCritical] get { if (typeOfIXmlSerializable == null) { typeOfIXmlSerializable = typeof(IXmlSerializable); } return typeOfIXmlSerializable; } } internal static Type TypeOfXmlSchemaProviderAttribute { [SecuritySafeCritical] get { if (typeOfXmlSchemaProviderAttribute == null) { typeOfXmlSchemaProviderAttribute = typeof(XmlSchemaProviderAttribute); } return typeOfXmlSchemaProviderAttribute; } } internal static Type TypeOfXmlRootAttribute { [SecuritySafeCritical] get { if (typeOfXmlRootAttribute == null) { typeOfXmlRootAttribute = typeof(XmlRootAttribute); } return typeOfXmlRootAttribute; } } internal static Type TypeOfXmlQualifiedName { [SecuritySafeCritical] get { if (typeOfXmlQualifiedName == null) { typeOfXmlQualifiedName = typeof(XmlQualifiedName); } return typeOfXmlQualifiedName; } } internal static Type TypeOfXmlSchemaType { [SecuritySafeCritical] get { if (typeOfXmlSchemaType == null) { typeOfXmlSchemaType = typeof(XmlSchemaType); } return typeOfXmlSchemaType; } } internal static Type TypeOfXmlSerializableServices { [SecuritySafeCritical] get { if (typeOfXmlSerializableServices == null) { typeOfXmlSerializableServices = typeof(XmlSerializableServices); } return typeOfXmlSerializableServices; } } internal static Type TypeOfXmlNodeArray { [SecuritySafeCritical] get { if (typeOfXmlNodeArray == null) { typeOfXmlNodeArray = typeof(XmlNode[]); } return typeOfXmlNodeArray; } } internal static Type TypeOfXmlSchemaSet { [SecuritySafeCritical] get { if (typeOfXmlSchemaSet == null) { typeOfXmlSchemaSet = typeof(XmlSchemaSet); } return typeOfXmlSchemaSet; } } internal static object[] EmptyObjectArray { [SecuritySafeCritical] get { if (emptyObjectArray == null) { emptyObjectArray = new object[0]; } return emptyObjectArray; } } internal static Type[] EmptyTypeArray { [SecuritySafeCritical] get { if (emptyTypeArray == null) { emptyTypeArray = new Type[0]; } return emptyTypeArray; } } internal static Type TypeOfIPropertyChange { [SecuritySafeCritical] get { if (typeOfIPropertyChange == null) { typeOfIPropertyChange = typeof(INotifyPropertyChanged); } return typeOfIPropertyChange; } } internal static Type TypeOfIExtensibleDataObject { [SecuritySafeCritical] get { if (typeOfIExtensibleDataObject == null) { typeOfIExtensibleDataObject = typeof(IExtensibleDataObject); } return typeOfIExtensibleDataObject; } } internal static Type TypeOfExtensionDataObject { [SecuritySafeCritical] get { if (typeOfExtensionDataObject == null) { typeOfExtensionDataObject = typeof(ExtensionDataObject); } return typeOfExtensionDataObject; } } internal static Type TypeOfISerializableDataNode { [SecuritySafeCritical] get { if (typeOfISerializableDataNode == null) { typeOfISerializableDataNode = typeof(ISerializableDataNode); } return typeOfISerializableDataNode; } } internal static Type TypeOfClassDataNode { [SecuritySafeCritical] get { if (typeOfClassDataNode == null) { typeOfClassDataNode = typeof(ClassDataNode); } return typeOfClassDataNode; } } internal static Type TypeOfCollectionDataNode { [SecuritySafeCritical] get { if (typeOfCollectionDataNode == null) { typeOfCollectionDataNode = typeof(CollectionDataNode); } return typeOfCollectionDataNode; } } internal static Type TypeOfXmlDataNode { [SecuritySafeCritical] get { if (typeOfXmlDataNode == null) { typeOfXmlDataNode = typeof(XmlDataNode); } return typeOfXmlDataNode; } } internal static Type TypeOfNullable { [SecuritySafeCritical] get { if (typeOfNullable == null) { typeOfNullable = typeof(Nullable<>); } return typeOfNullable; } } internal static Type TypeOfReflectionPointer { [SecuritySafeCritical] get { if (typeOfReflectionPointer == null) { typeOfReflectionPointer = typeof(Pointer); } return typeOfReflectionPointer; } } internal static Type TypeOfIDictionaryGeneric { [SecuritySafeCritical] get { if (typeOfIDictionaryGeneric == null) { typeOfIDictionaryGeneric = typeof(IDictionary<, >); } return typeOfIDictionaryGeneric; } } internal static Type TypeOfIDictionary { [SecuritySafeCritical] get { if (typeOfIDictionary == null) { typeOfIDictionary = typeof(IDictionary); } return typeOfIDictionary; } } internal static Type TypeOfIListGeneric { [SecuritySafeCritical] get { if (typeOfIListGeneric == null) { typeOfIListGeneric = typeof(IList<>); } return typeOfIListGeneric; } } internal static Type TypeOfIList { [SecuritySafeCritical] get { if (typeOfIList == null) { typeOfIList = typeof(IList); } return typeOfIList; } } internal static Type TypeOfICollectionGeneric { [SecuritySafeCritical] get { if (typeOfICollectionGeneric == null) { typeOfICollectionGeneric = typeof(ICollection<>); } return typeOfICollectionGeneric; } } internal static Type TypeOfICollection { [SecuritySafeCritical] get { if (typeOfICollection == null) { typeOfICollection = typeof(ICollection); } return typeOfICollection; } } internal static Type TypeOfIEnumerableGeneric { [SecuritySafeCritical] get { if (typeOfIEnumerableGeneric == null) { typeOfIEnumerableGeneric = typeof(IEnumerable<>); } return typeOfIEnumerableGeneric; } } internal static Type TypeOfIEnumerable { [SecuritySafeCritical] get { if (typeOfIEnumerable == null) { typeOfIEnumerable = typeof(IEnumerable); } return typeOfIEnumerable; } } internal static Type TypeOfIEnumeratorGeneric { [SecuritySafeCritical] get { if (typeOfIEnumeratorGeneric == null) { typeOfIEnumeratorGeneric = typeof(IEnumerator<>); } return typeOfIEnumeratorGeneric; } } internal static Type TypeOfIEnumerator { [SecuritySafeCritical] get { if (typeOfIEnumerator == null) { typeOfIEnumerator = typeof(IEnumerator); } return typeOfIEnumerator; } } internal static Type TypeOfKeyValuePair { [SecuritySafeCritical] get { if (typeOfKeyValuePair == null) { typeOfKeyValuePair = typeof(KeyValuePair<, >); } return typeOfKeyValuePair; } } internal static Type TypeOfKeyValue { [SecuritySafeCritical] get { if (typeOfKeyValue == null) { typeOfKeyValue = typeof(KeyValue<, >); } return typeOfKeyValue; } } internal static Type TypeOfIDictionaryEnumerator { [SecuritySafeCritical] get { if (typeOfIDictionaryEnumerator == null) { typeOfIDictionaryEnumerator = typeof(IDictionaryEnumerator); } return typeOfIDictionaryEnumerator; } } internal static Type TypeOfDictionaryEnumerator { [SecuritySafeCritical] get { if (typeOfDictionaryEnumerator == null) { typeOfDictionaryEnumerator = typeof(CollectionDataContract.DictionaryEnumerator); } return typeOfDictionaryEnumerator; } } internal static Type TypeOfGenericDictionaryEnumerator { [SecuritySafeCritical] get { if (typeOfGenericDictionaryEnumerator == null) { typeOfGenericDictionaryEnumerator = typeof(CollectionDataContract.GenericDictionaryEnumerator<, >); } return typeOfGenericDictionaryEnumerator; } } internal static Type TypeOfDictionaryGeneric { [SecuritySafeCritical] get { if (typeOfDictionaryGeneric == null) { typeOfDictionaryGeneric = typeof(Dictionary<, >); } return typeOfDictionaryGeneric; } } internal static Type TypeOfHashtable { [SecuritySafeCritical] get { if (typeOfHashtable == null) { typeOfHashtable = typeof(Hashtable); } return typeOfHashtable; } } internal static Type TypeOfListGeneric { [SecuritySafeCritical] get { if (typeOfListGeneric == null) { typeOfListGeneric = typeof(List<>); } return typeOfListGeneric; } } internal static Type TypeOfXmlElement { [SecuritySafeCritical] get { if (typeOfXmlElement == null) { typeOfXmlElement = typeof(XmlElement); } return typeOfXmlElement; } } internal static Type TypeOfDBNull { [SecuritySafeCritical] get { if (typeOfDBNull == null) { typeOfDBNull = typeof(DBNull); } return typeOfDBNull; } } internal static Uri DataContractXsdBaseNamespaceUri { [SecuritySafeCritical] get { if (dataContractXsdBaseNamespaceUri == null) { dataContractXsdBaseNamespaceUri = new Uri("http://schemas.datacontract.org/2004/07/"); } return dataContractXsdBaseNamespaceUri; } } } internal class HybridObjectCache { private Dictionary objectDictionary; private Dictionary referencedObjectDictionary; internal HybridObjectCache() { } internal void Add(string id, object obj) { if (objectDictionary == null) { objectDictionary = new Dictionary(); } if (objectDictionary.TryGetValue(id, out var _)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Invalid XML encountered. The same Id value '{0}' is defined more than once. Multiple objects cannot be deserialized using the same Id.", id))); } objectDictionary.Add(id, obj); } internal void Remove(string id) { if (objectDictionary != null) { objectDictionary.Remove(id); } } internal object GetObject(string id) { if (referencedObjectDictionary == null) { referencedObjectDictionary = new Dictionary(); referencedObjectDictionary.Add(id, null); } else if (!referencedObjectDictionary.ContainsKey(id)) { referencedObjectDictionary.Add(id, null); } if (objectDictionary != null) { objectDictionary.TryGetValue(id, out var value); return value; } return null; } internal bool IsObjectReferenced(string id) { if (referencedObjectDictionary != null) { return referencedObjectDictionary.ContainsKey(id); } return false; } } public interface IDataContractSurrogate { Type GetDataContractType(Type type); object GetObjectToSerialize(object obj, Type targetType); object GetDeserializedObject(object obj, Type targetType); object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType); object GetCustomDataToExport(Type clrType, Type dataContractType); void GetKnownCustomDataTypes(Collection customDataTypes); Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData); CodeTypeDeclaration ProcessImportedType(CodeTypeDeclaration typeDeclaration, CodeCompileUnit compileUnit); } internal static class DataContractSurrogateCaller { internal static Type GetDataContractType(IDataContractSurrogate surrogate, Type type) { if (DataContract.GetBuiltInDataContract(type) != null) { return type; } Type dataContractType = surrogate.GetDataContractType(type); if (dataContractType == null) { return type; } return dataContractType; } internal static object GetObjectToSerialize(IDataContractSurrogate surrogate, object obj, Type objType, Type membertype) { if (obj == null) { return null; } if (DataContract.GetBuiltInDataContract(objType) != null) { return obj; } return surrogate.GetObjectToSerialize(obj, membertype); } internal static object GetDeserializedObject(IDataContractSurrogate surrogate, object obj, Type objType, Type memberType) { if (obj == null) { return null; } if (DataContract.GetBuiltInDataContract(objType) != null) { return obj; } return surrogate.GetDeserializedObject(obj, memberType); } internal static object GetCustomDataToExport(IDataContractSurrogate surrogate, MemberInfo memberInfo, Type dataContractType) { return surrogate.GetCustomDataToExport(memberInfo, dataContractType); } internal static object GetCustomDataToExport(IDataContractSurrogate surrogate, Type clrType, Type dataContractType) { if (DataContract.GetBuiltInDataContract(clrType) != null) { return null; } return surrogate.GetCustomDataToExport(clrType, dataContractType); } internal static void GetKnownCustomDataTypes(IDataContractSurrogate surrogate, Collection customDataTypes) { surrogate.GetKnownCustomDataTypes(customDataTypes); } internal static Type GetReferencedTypeOnImport(IDataContractSurrogate surrogate, string typeName, string typeNamespace, object customData) { if (DataContract.GetBuiltInDataContract(typeName, typeNamespace) != null) { return null; } return surrogate.GetReferencedTypeOnImport(typeName, typeNamespace, customData); } internal static CodeTypeDeclaration ProcessImportedType(IDataContractSurrogate surrogate, CodeTypeDeclaration typeDeclaration, CodeCompileUnit compileUnit) { return surrogate.ProcessImportedType(typeDeclaration, compileUnit); } } public interface IExtensibleDataObject { ExtensionDataObject ExtensionData { get; set; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, Inherited = false, AllowMultiple = false)] public sealed class IgnoreDataMemberAttribute : Attribute { } [Serializable] public class InvalidDataContractException : Exception { public InvalidDataContractException() { } public InvalidDataContractException(string message) : base(message) { } public InvalidDataContractException(string message, Exception innerException) : base(message, innerException) { } protected InvalidDataContractException(SerializationInfo info, StreamingContext context) : base(info, context) { } } internal static class JsonFormatGeneratorStatics { [SecurityCritical] private static MethodInfo boxPointer; [SecurityCritical] private static PropertyInfo collectionItemNameProperty; [SecurityCritical] private static ConstructorInfo extensionDataObjectCtor; [SecurityCritical] private static PropertyInfo extensionDataProperty; [SecurityCritical] private static MethodInfo getItemContractMethod; [SecurityCritical] private static MethodInfo getJsonDataContractMethod; [SecurityCritical] private static MethodInfo getJsonMemberIndexMethod; [SecurityCritical] private static MethodInfo getRevisedItemContractMethod; [SecurityCritical] private static MethodInfo getUninitializedObjectMethod; [SecurityCritical] private static MethodInfo ienumeratorGetCurrentMethod; [SecurityCritical] private static MethodInfo ienumeratorMoveNextMethod; [SecurityCritical] private static MethodInfo isStartElementMethod0; [SecurityCritical] private static MethodInfo isStartElementMethod2; [SecurityCritical] private static PropertyInfo localNameProperty; [SecurityCritical] private static PropertyInfo namespaceProperty; [SecurityCritical] private static MethodInfo moveToContentMethod; [SecurityCritical] private static PropertyInfo nodeTypeProperty; [SecurityCritical] private static MethodInfo onDeserializationMethod; [SecurityCritical] private static MethodInfo readJsonValueMethod; [SecurityCritical] private static ConstructorInfo serializationExceptionCtor; [SecurityCritical] private static Type[] serInfoCtorArgs; [SecurityCritical] private static MethodInfo throwDuplicateMemberExceptionMethod; [SecurityCritical] private static MethodInfo throwMissingRequiredMembersMethod; [SecurityCritical] private static PropertyInfo typeHandleProperty; [SecurityCritical] private static MethodInfo unboxPointer; [SecurityCritical] private static PropertyInfo useSimpleDictionaryFormatReadProperty; [SecurityCritical] private static PropertyInfo useSimpleDictionaryFormatWriteProperty; [SecurityCritical] private static MethodInfo writeAttributeStringMethod; [SecurityCritical] private static MethodInfo writeEndElementMethod; [SecurityCritical] private static MethodInfo writeJsonISerializableMethod; [SecurityCritical] private static MethodInfo writeJsonNameWithMappingMethod; [SecurityCritical] private static MethodInfo writeJsonValueMethod; [SecurityCritical] private static MethodInfo writeStartElementMethod; [SecurityCritical] private static MethodInfo writeStartElementStringMethod; [SecurityCritical] private static MethodInfo parseEnumMethod; [SecurityCritical] private static MethodInfo getJsonMemberNameMethod; public static MethodInfo BoxPointer { [SecuritySafeCritical] get { if (boxPointer == null) { boxPointer = typeof(Pointer).GetMethod("Box"); } return boxPointer; } } public static PropertyInfo CollectionItemNameProperty { [SecuritySafeCritical] get { if (collectionItemNameProperty == null) { collectionItemNameProperty = typeof(XmlObjectSerializerWriteContextComplexJson).GetProperty("CollectionItemName", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return collectionItemNameProperty; } } public static ConstructorInfo ExtensionDataObjectCtor { [SecuritySafeCritical] get { if (extensionDataObjectCtor == null) { extensionDataObjectCtor = typeof(ExtensionDataObject).GetConstructor(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null); } return extensionDataObjectCtor; } } public static PropertyInfo ExtensionDataProperty { [SecuritySafeCritical] get { if (extensionDataProperty == null) { extensionDataProperty = typeof(IExtensibleDataObject).GetProperty("ExtensionData"); } return extensionDataProperty; } } public static MethodInfo GetCurrentMethod { [SecuritySafeCritical] get { if (ienumeratorGetCurrentMethod == null) { ienumeratorGetCurrentMethod = typeof(IEnumerator).GetProperty("Current").GetGetMethod(); } return ienumeratorGetCurrentMethod; } } public static MethodInfo GetItemContractMethod { [SecuritySafeCritical] get { if (getItemContractMethod == null) { getItemContractMethod = typeof(CollectionDataContract).GetProperty("ItemContract", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetGetMethod(nonPublic: true); } return getItemContractMethod; } } public static MethodInfo GetJsonDataContractMethod { [SecuritySafeCritical] get { if (getJsonDataContractMethod == null) { getJsonDataContractMethod = typeof(JsonDataContract).GetMethod("GetJsonDataContract", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return getJsonDataContractMethod; } } public static MethodInfo GetJsonMemberIndexMethod { [SecuritySafeCritical] get { if (getJsonMemberIndexMethod == null) { getJsonMemberIndexMethod = typeof(XmlObjectSerializerReadContextComplexJson).GetMethod("GetJsonMemberIndex", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return getJsonMemberIndexMethod; } } public static MethodInfo GetRevisedItemContractMethod { [SecuritySafeCritical] get { if (getRevisedItemContractMethod == null) { getRevisedItemContractMethod = typeof(XmlObjectSerializerWriteContextComplexJson).GetMethod("GetRevisedItemContract", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return getRevisedItemContractMethod; } } public static MethodInfo GetUninitializedObjectMethod { [SecuritySafeCritical] get { if (getUninitializedObjectMethod == null) { getUninitializedObjectMethod = typeof(XmlFormatReaderGenerator).GetMethod("UnsafeGetUninitializedObject", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(int) }, null); } return getUninitializedObjectMethod; } } public static MethodInfo IsStartElementMethod0 { [SecuritySafeCritical] get { if (isStartElementMethod0 == null) { isStartElementMethod0 = typeof(XmlReaderDelegator).GetMethod("IsStartElement", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null); } return isStartElementMethod0; } } public static MethodInfo IsStartElementMethod2 { [SecuritySafeCritical] get { if (isStartElementMethod2 == null) { isStartElementMethod2 = typeof(XmlReaderDelegator).GetMethod("IsStartElement", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2] { typeof(XmlDictionaryString), typeof(XmlDictionaryString) }, null); } return isStartElementMethod2; } } public static PropertyInfo LocalNameProperty { [SecuritySafeCritical] get { if (localNameProperty == null) { localNameProperty = typeof(XmlReaderDelegator).GetProperty("LocalName", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return localNameProperty; } } public static PropertyInfo NamespaceProperty { [SecuritySafeCritical] get { if (namespaceProperty == null) { namespaceProperty = typeof(XmlReaderDelegator).GetProperty("NamespaceProperty", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return namespaceProperty; } } public static MethodInfo MoveNextMethod { [SecuritySafeCritical] get { if (ienumeratorMoveNextMethod == null) { ienumeratorMoveNextMethod = typeof(IEnumerator).GetMethod("MoveNext"); } return ienumeratorMoveNextMethod; } } public static MethodInfo MoveToContentMethod { [SecuritySafeCritical] get { if (moveToContentMethod == null) { moveToContentMethod = typeof(XmlReaderDelegator).GetMethod("MoveToContent", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return moveToContentMethod; } } public static PropertyInfo NodeTypeProperty { [SecuritySafeCritical] get { if (nodeTypeProperty == null) { nodeTypeProperty = typeof(XmlReaderDelegator).GetProperty("NodeType", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return nodeTypeProperty; } } public static MethodInfo OnDeserializationMethod { [SecuritySafeCritical] get { if (onDeserializationMethod == null) { onDeserializationMethod = typeof(IDeserializationCallback).GetMethod("OnDeserialization"); } return onDeserializationMethod; } } public static MethodInfo ReadJsonValueMethod { [SecuritySafeCritical] get { if (readJsonValueMethod == null) { readJsonValueMethod = typeof(DataContractJsonSerializer).GetMethod("ReadJsonValue", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return readJsonValueMethod; } } public static ConstructorInfo SerializationExceptionCtor { [SecuritySafeCritical] get { if (serializationExceptionCtor == null) { serializationExceptionCtor = typeof(SerializationException).GetConstructor(new Type[1] { typeof(string) }); } return serializationExceptionCtor; } } public static Type[] SerInfoCtorArgs { [SecuritySafeCritical] get { if (serInfoCtorArgs == null) { serInfoCtorArgs = new Type[2] { typeof(SerializationInfo), typeof(StreamingContext) }; } return serInfoCtorArgs; } } public static MethodInfo ThrowDuplicateMemberExceptionMethod { [SecuritySafeCritical] get { if (throwDuplicateMemberExceptionMethod == null) { throwDuplicateMemberExceptionMethod = typeof(XmlObjectSerializerReadContextComplexJson).GetMethod("ThrowDuplicateMemberException", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return throwDuplicateMemberExceptionMethod; } } public static MethodInfo ThrowMissingRequiredMembersMethod { [SecuritySafeCritical] get { if (throwMissingRequiredMembersMethod == null) { throwMissingRequiredMembersMethod = typeof(XmlObjectSerializerReadContextComplexJson).GetMethod("ThrowMissingRequiredMembers", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return throwMissingRequiredMembersMethod; } } public static PropertyInfo TypeHandleProperty { [SecuritySafeCritical] get { if (typeHandleProperty == null) { typeHandleProperty = typeof(Type).GetProperty("TypeHandle"); } return typeHandleProperty; } } public static MethodInfo UnboxPointer { [SecuritySafeCritical] get { if (unboxPointer == null) { unboxPointer = typeof(Pointer).GetMethod("Unbox"); } return unboxPointer; } } public static PropertyInfo UseSimpleDictionaryFormatReadProperty { [SecuritySafeCritical] get { if (useSimpleDictionaryFormatReadProperty == null) { useSimpleDictionaryFormatReadProperty = typeof(XmlObjectSerializerReadContextComplexJson).GetProperty("UseSimpleDictionaryFormat", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return useSimpleDictionaryFormatReadProperty; } } public static PropertyInfo UseSimpleDictionaryFormatWriteProperty { [SecuritySafeCritical] get { if (useSimpleDictionaryFormatWriteProperty == null) { useSimpleDictionaryFormatWriteProperty = typeof(XmlObjectSerializerWriteContextComplexJson).GetProperty("UseSimpleDictionaryFormat", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return useSimpleDictionaryFormatWriteProperty; } } public static MethodInfo WriteAttributeStringMethod { [SecuritySafeCritical] get { if (writeAttributeStringMethod == null) { writeAttributeStringMethod = typeof(XmlWriterDelegator).GetMethod("WriteAttributeString", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[4] { typeof(string), typeof(string), typeof(string), typeof(string) }, null); } return writeAttributeStringMethod; } } public static MethodInfo WriteEndElementMethod { [SecuritySafeCritical] get { if (writeEndElementMethod == null) { writeEndElementMethod = typeof(XmlWriterDelegator).GetMethod("WriteEndElement", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null); } return writeEndElementMethod; } } public static MethodInfo WriteJsonISerializableMethod { [SecuritySafeCritical] get { if (writeJsonISerializableMethod == null) { writeJsonISerializableMethod = typeof(XmlObjectSerializerWriteContextComplexJson).GetMethod("WriteJsonISerializable", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return writeJsonISerializableMethod; } } public static MethodInfo WriteJsonNameWithMappingMethod { [SecuritySafeCritical] get { if (writeJsonNameWithMappingMethod == null) { writeJsonNameWithMappingMethod = typeof(XmlObjectSerializerWriteContextComplexJson).GetMethod("WriteJsonNameWithMapping", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return writeJsonNameWithMappingMethod; } } public static MethodInfo WriteJsonValueMethod { [SecuritySafeCritical] get { if (writeJsonValueMethod == null) { writeJsonValueMethod = typeof(DataContractJsonSerializer).GetMethod("WriteJsonValue", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return writeJsonValueMethod; } } public static MethodInfo WriteStartElementMethod { [SecuritySafeCritical] get { if (writeStartElementMethod == null) { writeStartElementMethod = typeof(XmlWriterDelegator).GetMethod("WriteStartElement", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2] { typeof(XmlDictionaryString), typeof(XmlDictionaryString) }, null); } return writeStartElementMethod; } } public static MethodInfo WriteStartElementStringMethod { [SecuritySafeCritical] get { if (writeStartElementStringMethod == null) { writeStartElementStringMethod = typeof(XmlWriterDelegator).GetMethod("WriteStartElement", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2] { typeof(string), typeof(string) }, null); } return writeStartElementStringMethod; } } public static MethodInfo ParseEnumMethod { [SecuritySafeCritical] get { if (parseEnumMethod == null) { parseEnumMethod = typeof(Enum).GetMethod("Parse", BindingFlags.Static | BindingFlags.Public, null, new Type[2] { typeof(Type), typeof(string) }, null); } return parseEnumMethod; } } public static MethodInfo GetJsonMemberNameMethod { [SecuritySafeCritical] get { if (getJsonMemberNameMethod == null) { getJsonMemberNameMethod = typeof(XmlObjectSerializerReadContextComplexJson).GetMethod("GetJsonMemberName", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(XmlReaderDelegator) }, null); } return getJsonMemberNameMethod; } } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = true, AllowMultiple = true)] public sealed class KnownTypeAttribute : Attribute { private string methodName; private Type type; public string MethodName => methodName; public Type Type => type; private KnownTypeAttribute() { } public KnownTypeAttribute(Type type) { this.type = type; } public KnownTypeAttribute(string methodName) { this.methodName = methodName; } } internal sealed class KnownTypeDataContractResolver : DataContractResolver { private XmlObjectSerializerContext context; internal KnownTypeDataContractResolver(XmlObjectSerializerContext context) { this.context = context; } public override bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { if (type == null) { typeName = null; typeNamespace = null; return false; } if (declaredType != null && declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType)) { typeName = null; typeNamespace = null; return true; } DataContract dataContract = DataContract.GetDataContract(type); if (context.IsKnownType(dataContract, dataContract.KnownDataContracts, declaredType)) { typeName = dataContract.Name; typeNamespace = dataContract.Namespace; return true; } typeName = null; typeNamespace = null; return false; } public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver) { if (typeName == null || typeNamespace == null) { return null; } return context.ResolveNameFromKnownTypes(new XmlQualifiedName(typeName, typeNamespace)); } } public sealed class NetDataContractSerializer : XmlObjectSerializer, IFormatter { private XmlDictionaryString rootName; private XmlDictionaryString rootNamespace; private StreamingContext context; private SerializationBinder binder; private ISurrogateSelector surrogateSelector; private int maxItemsInObjectGraph; private bool ignoreExtensionDataObject; private FormatterAssemblyStyle assemblyFormat; private DataContract cachedDataContract; private static Hashtable typeNameCache = new Hashtable(); private static bool? unsafeTypeForwardingEnabled; internal static bool UnsafeTypeForwardingEnabled { [SecuritySafeCritical] get { if (!unsafeTypeForwardingEnabled.HasValue) { unsafeTypeForwardingEnabled = false; } return unsafeTypeForwardingEnabled.Value; } } public StreamingContext Context { get { return context; } set { context = value; } } public SerializationBinder Binder { get { return binder; } set { binder = value; } } public ISurrogateSelector SurrogateSelector { get { return surrogateSelector; } set { surrogateSelector = value; } } public FormatterAssemblyStyle AssemblyFormat { get { return assemblyFormat; } set { if (value != FormatterAssemblyStyle.Full && value != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString("'{0}': invalid assembly format.", value))); } assemblyFormat = value; } } public int MaxItemsInObjectGraph => maxItemsInObjectGraph; public bool IgnoreExtensionDataObject => ignoreExtensionDataObject; public NetDataContractSerializer() : this(new StreamingContext(StreamingContextStates.All)) { } public NetDataContractSerializer(StreamingContext context) : this(context, int.MaxValue, ignoreExtensionDataObject: false, FormatterAssemblyStyle.Full, null) { } public NetDataContractSerializer(StreamingContext context, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, FormatterAssemblyStyle assemblyFormat, ISurrogateSelector surrogateSelector) { Initialize(context, maxItemsInObjectGraph, ignoreExtensionDataObject, assemblyFormat, surrogateSelector); } public NetDataContractSerializer(string rootName, string rootNamespace) : this(rootName, rootNamespace, new StreamingContext(StreamingContextStates.All), int.MaxValue, ignoreExtensionDataObject: false, FormatterAssemblyStyle.Full, null) { } public NetDataContractSerializer(string rootName, string rootNamespace, StreamingContext context, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, FormatterAssemblyStyle assemblyFormat, ISurrogateSelector surrogateSelector) { XmlDictionary xmlDictionary = new XmlDictionary(2); Initialize(xmlDictionary.Add(rootName), xmlDictionary.Add(DataContract.GetNamespace(rootNamespace)), context, maxItemsInObjectGraph, ignoreExtensionDataObject, assemblyFormat, surrogateSelector); } public NetDataContractSerializer(XmlDictionaryString rootName, XmlDictionaryString rootNamespace) : this(rootName, rootNamespace, new StreamingContext(StreamingContextStates.All), int.MaxValue, ignoreExtensionDataObject: false, FormatterAssemblyStyle.Full, null) { } public NetDataContractSerializer(XmlDictionaryString rootName, XmlDictionaryString rootNamespace, StreamingContext context, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, FormatterAssemblyStyle assemblyFormat, ISurrogateSelector surrogateSelector) { Initialize(rootName, rootNamespace, context, maxItemsInObjectGraph, ignoreExtensionDataObject, assemblyFormat, surrogateSelector); } private void Initialize(StreamingContext context, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, FormatterAssemblyStyle assemblyFormat, ISurrogateSelector surrogateSelector) { this.context = context; if (maxItemsInObjectGraph < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxItemsInObjectGraph", SR.GetString("The value of this argument must be non-negative."))); } this.maxItemsInObjectGraph = maxItemsInObjectGraph; this.ignoreExtensionDataObject = ignoreExtensionDataObject; this.surrogateSelector = surrogateSelector; AssemblyFormat = assemblyFormat; } private void Initialize(XmlDictionaryString rootName, XmlDictionaryString rootNamespace, StreamingContext context, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, FormatterAssemblyStyle assemblyFormat, ISurrogateSelector surrogateSelector) { Initialize(context, maxItemsInObjectGraph, ignoreExtensionDataObject, assemblyFormat, surrogateSelector); this.rootName = rootName; this.rootNamespace = rootNamespace; } public void Serialize(Stream stream, object graph) { base.WriteObject(stream, graph); } public object Deserialize(Stream stream) { return base.ReadObject(stream); } internal override void InternalWriteObject(XmlWriterDelegator writer, object graph) { Hashtable surrogateDataContracts = null; DataContract dataContract = GetDataContract(graph, ref surrogateDataContracts); InternalWriteStartObject(writer, graph, dataContract); InternalWriteObjectContent(writer, graph, dataContract, surrogateDataContracts); InternalWriteEndObject(writer); } public override void WriteObject(XmlWriter writer, object graph) { WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteStartObject(XmlWriter writer, object graph) { WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteObjectContent(XmlWriter writer, object graph) { WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph); } public override void WriteEndObject(XmlWriter writer) { WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer)); } public override void WriteStartObject(XmlDictionaryWriter writer, object graph) { WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } internal override void InternalWriteStartObject(XmlWriterDelegator writer, object graph) { Hashtable surrogateDataContracts = null; DataContract dataContract = GetDataContract(graph, ref surrogateDataContracts); InternalWriteStartObject(writer, graph, dataContract); } private void InternalWriteStartObject(XmlWriterDelegator writer, object graph, DataContract contract) { WriteRootElement(writer, contract, rootName, rootNamespace, CheckIfNeedsContractNsAtRoot(rootName, rootNamespace, contract)); } public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) { WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph); } internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph) { Hashtable surrogateDataContracts = null; DataContract dataContract = GetDataContract(graph, ref surrogateDataContracts); InternalWriteObjectContent(writer, graph, dataContract, surrogateDataContracts); } private void InternalWriteObjectContent(XmlWriterDelegator writer, object graph, DataContract contract, Hashtable surrogateDataContracts) { if (MaxItemsInObjectGraph == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Maximum number of items that can be serialized or deserialized in an object graph is '{0}'.", MaxItemsInObjectGraph))); } if (IsRootXmlAny(rootName, contract)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("For type '{0}', IsAny is not supported by NetDataContractSerializer.", contract.UnderlyingType))); } if (graph == null) { XmlObjectSerializer.WriteNull(writer); return; } Type type = graph.GetType(); if (contract.UnderlyingType != type) { contract = GetDataContract(graph, ref surrogateDataContracts); } XmlObjectSerializerWriteContext xmlObjectSerializerWriteContext = null; if (contract.CanContainReferences) { xmlObjectSerializerWriteContext = XmlObjectSerializerWriteContext.CreateContext(this, surrogateDataContracts); xmlObjectSerializerWriteContext.HandleGraphAtTopLevel(writer, graph, contract); } WriteClrTypeInfo(writer, contract, binder); contract.WriteXmlValue(writer, graph, xmlObjectSerializerWriteContext); } internal static void WriteClrTypeInfo(XmlWriterDelegator writer, DataContract dataContract, SerializationBinder binder) { if (dataContract.IsISerializable || dataContract is SurrogateDataContract) { return; } TypeInformation typeInformation = null; Type originalUnderlyingType = dataContract.OriginalUnderlyingType; string typeName = null; string assemblyName = null; binder?.BindToName(originalUnderlyingType, out assemblyName, out typeName); if (typeName == null) { typeInformation = GetTypeInformation(originalUnderlyingType); typeName = typeInformation.FullTypeName; } if (assemblyName == null) { assemblyName = ((typeInformation == null) ? GetTypeInformation(originalUnderlyingType).AssemblyString : typeInformation.AssemblyString); if (!UnsafeTypeForwardingEnabled && !originalUnderlyingType.Assembly.IsFullyTrusted && !IsAssemblyNameForwardingSafe(originalUnderlyingType.Assembly.FullName, assemblyName)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Type '{0}' in assembly '{1}' cannot be forwarded from assembly '{2}'.", DataContract.GetClrTypeFullName(originalUnderlyingType), originalUnderlyingType.Assembly.FullName, assemblyName))); } } WriteClrTypeInfo(writer, typeName, assemblyName); } internal static void WriteClrTypeInfo(XmlWriterDelegator writer, Type dataContractType, SerializationBinder binder, string defaultClrTypeName, string defaultClrAssemblyName) { string typeName = null; string assemblyName = null; binder?.BindToName(dataContractType, out assemblyName, out typeName); if (typeName == null) { typeName = defaultClrTypeName; } if (assemblyName == null) { assemblyName = defaultClrAssemblyName; } WriteClrTypeInfo(writer, typeName, assemblyName); } internal static void WriteClrTypeInfo(XmlWriterDelegator writer, Type dataContractType, SerializationBinder binder, SerializationInfo serInfo) { TypeInformation typeInformation = null; string typeName = null; string assemblyName = null; binder?.BindToName(dataContractType, out assemblyName, out typeName); if (typeName == null) { if (serInfo.IsFullTypeNameSetExplicit) { typeName = serInfo.FullTypeName; } else { typeInformation = GetTypeInformation(serInfo.ObjectType); typeName = typeInformation.FullTypeName; } } if (assemblyName == null) { assemblyName = ((!serInfo.IsAssemblyNameSetExplicit) ? ((typeInformation == null) ? GetTypeInformation(serInfo.ObjectType).AssemblyString : typeInformation.AssemblyString) : serInfo.AssemblyName); } WriteClrTypeInfo(writer, typeName, assemblyName); } private static void WriteClrTypeInfo(XmlWriterDelegator writer, string clrTypeName, string clrAssemblyName) { if (clrTypeName != null) { writer.WriteAttributeString("z", DictionaryGlobals.ClrTypeLocalName, DictionaryGlobals.SerializationNamespace, DataContract.GetClrTypeString(clrTypeName)); } if (clrAssemblyName != null) { writer.WriteAttributeString("z", DictionaryGlobals.ClrAssemblyLocalName, DictionaryGlobals.SerializationNamespace, DataContract.GetClrTypeString(clrAssemblyName)); } } public override void WriteEndObject(XmlDictionaryWriter writer) { WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer)); } internal override void InternalWriteEndObject(XmlWriterDelegator writer) { writer.WriteEndElement(); } public override object ReadObject(XmlReader reader) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName: true); } public override object ReadObject(XmlReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName); } public override bool IsStartObject(XmlReader reader) { return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader)); } public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName); } public override bool IsStartObject(XmlDictionaryReader reader) { return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader)); } internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName) { if (MaxItemsInObjectGraph == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Maximum number of items that can be serialized or deserialized in an object graph is '{0}'.", MaxItemsInObjectGraph))); } if (!IsStartElement(xmlReader)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.GetString("Expecting state '{0}' when ReadObject is called.", XmlNodeType.Element), xmlReader)); } return XmlObjectSerializerReadContext.CreateContext(this).InternalDeserialize(xmlReader, null, null, null); } internal override bool InternalIsStartObject(XmlReaderDelegator reader) { return IsStartElement(reader); } internal DataContract GetDataContract(object obj, ref Hashtable surrogateDataContracts) { return GetDataContract((obj == null) ? Globals.TypeOfObject : obj.GetType(), ref surrogateDataContracts); } internal DataContract GetDataContract(Type type, ref Hashtable surrogateDataContracts) { return GetDataContract(type.TypeHandle, type, ref surrogateDataContracts); } internal DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type, ref Hashtable surrogateDataContracts) { DataContract dataContractFromSurrogateSelector = GetDataContractFromSurrogateSelector(surrogateSelector, Context, typeHandle, type, ref surrogateDataContracts); if (dataContractFromSurrogateSelector != null) { return dataContractFromSurrogateSelector; } if (cachedDataContract == null) { return cachedDataContract = DataContract.GetDataContract(typeHandle, type, SerializationMode.SharedType); } DataContract dataContract = cachedDataContract; if (dataContract.UnderlyingType.TypeHandle.Equals(typeHandle)) { return dataContract; } return DataContract.GetDataContract(typeHandle, type, SerializationMode.SharedType); } [MethodImpl(MethodImplOptions.NoInlining)] [SecuritySafeCritical] [PermissionSet(SecurityAction.Demand, Unrestricted = true)] private static ISerializationSurrogate GetSurrogate(Type type, ISurrogateSelector surrogateSelector, StreamingContext context) { ISurrogateSelector selector; return surrogateSelector.GetSurrogate(type, context, out selector); } internal static DataContract GetDataContractFromSurrogateSelector(ISurrogateSelector surrogateSelector, StreamingContext context, RuntimeTypeHandle typeHandle, Type type, ref Hashtable surrogateDataContracts) { if (surrogateSelector == null) { return null; } if (type == null) { type = Type.GetTypeFromHandle(typeHandle); } DataContract builtInDataContract = DataContract.GetBuiltInDataContract(type); if (builtInDataContract != null) { return builtInDataContract; } if (surrogateDataContracts != null) { DataContract dataContract = (DataContract)surrogateDataContracts[type]; if (dataContract != null) { return dataContract; } } DataContract dataContract2 = null; ISerializationSurrogate surrogate = GetSurrogate(type, surrogateSelector, context); if (surrogate != null) { dataContract2 = new SurrogateDataContract(type, surrogate); } else if (type.IsArray) { Type elementType = type.GetElementType(); DataContract dataContract3 = GetDataContractFromSurrogateSelector(surrogateSelector, context, elementType.TypeHandle, elementType, ref surrogateDataContracts); if (dataContract3 == null) { dataContract3 = DataContract.GetDataContract(elementType.TypeHandle, elementType, SerializationMode.SharedType); } dataContract2 = new CollectionDataContract(type, dataContract3); } if (dataContract2 != null) { if (surrogateDataContracts == null) { surrogateDataContracts = new Hashtable(); } surrogateDataContracts.Add(type, dataContract2); return dataContract2; } return null; } internal static TypeInformation GetTypeInformation(Type type) { TypeInformation typeInformation = null; object obj = typeNameCache[type]; if (obj == null) { bool hasTypeForwardedFrom; string clrAssemblyName = DataContract.GetClrAssemblyName(type, out hasTypeForwardedFrom); typeInformation = new TypeInformation(DataContract.GetClrTypeFullNameUsingTypeForwardedFromAttribute(type), clrAssemblyName, hasTypeForwardedFrom); lock (typeNameCache) { typeNameCache[type] = typeInformation; } } else { typeInformation = (TypeInformation)obj; } return typeInformation; } private static bool IsAssemblyNameForwardingSafe(string originalAssemblyName, string newAssemblyName) { if (originalAssemblyName == newAssemblyName) { return true; } AssemblyName assemblyName = new AssemblyName(originalAssemblyName); AssemblyName assemblyName2 = new AssemblyName(newAssemblyName); if (string.Equals(assemblyName2.Name, "mscorlib", StringComparison.OrdinalIgnoreCase) || string.Equals(assemblyName2.Name, "mscorlib.dll", StringComparison.OrdinalIgnoreCase)) { return false; } return IsPublicKeyTokenForwardingSafe(assemblyName.GetPublicKeyToken(), assemblyName2.GetPublicKeyToken()); } private static bool IsPublicKeyTokenForwardingSafe(byte[] sourceToken, byte[] destinationToken) { if (sourceToken == null || destinationToken == null || sourceToken.Length == 0 || destinationToken.Length == 0 || sourceToken.Length != destinationToken.Length) { return false; } for (int i = 0; i < sourceToken.Length; i++) { if (sourceToken[i] != destinationToken[i]) { return false; } } return true; } } internal struct ObjectReferenceStack { private const int MaximumArraySize = 16; private const int InitialArraySize = 4; private int count; private object[] objectArray; private bool[] isReferenceArray; private Dictionary objectDictionary; internal int Count => count; internal void Push(object obj) { if (objectArray == null) { objectArray = new object[4]; objectArray[count++] = obj; return; } if (count < 16) { if (count == objectArray.Length) { Array.Resize(ref objectArray, objectArray.Length * 2); } objectArray[count++] = obj; return; } if (objectDictionary == null) { objectDictionary = new Dictionary(); } objectDictionary.Add(obj, null); count++; } internal void EnsureSetAsIsReference(object obj) { if (count == 0) { return; } if (count > 16) { _ = objectDictionary; objectDictionary.Remove(obj); } else if (objectArray != null && objectArray[count - 1] == obj) { if (isReferenceArray == null) { isReferenceArray = new bool[4]; } else if (count == isReferenceArray.Length) { Array.Resize(ref isReferenceArray, isReferenceArray.Length * 2); } isReferenceArray[count - 1] = true; } } internal void Pop(object obj) { if (count > 16) { _ = objectDictionary; objectDictionary.Remove(obj); } count--; } internal bool Contains(object obj) { int num = count; if (num > 16) { if (objectDictionary != null && objectDictionary.ContainsKey(obj)) { return true; } num = 16; } for (int num2 = num - 1; num2 >= 0; num2--) { if (obj == objectArray[num2] && isReferenceArray != null && !isReferenceArray[num2]) { return true; } } return false; } } internal class ObjectToIdCache { internal int m_currentCount; internal int[] m_ids; internal object[] m_objs; private bool[] m_isWrapped; internal static readonly int[] primes = new int[20] { 3, 7, 17, 37, 89, 197, 431, 919, 1931, 4049, 8419, 17519, 36353, 75431, 156437, 324449, 672827, 1395263, 2893249, 5999471 }; public ObjectToIdCache() { m_currentCount = 1; m_ids = new int[GetPrime(1)]; m_objs = new object[m_ids.Length]; m_isWrapped = new bool[m_ids.Length]; } public int GetId(object obj, ref bool newId) { bool isEmpty; bool isWrapped; int num = FindElement(obj, out isEmpty, out isWrapped); if (!isEmpty) { newId = false; return m_ids[num]; } if (!newId) { return -1; } int num2 = m_currentCount++; m_objs[num] = obj; m_ids[num] = num2; m_isWrapped[num] = isWrapped; if (m_currentCount >= m_objs.Length - 1) { Rehash(); } return num2; } public int ReassignId(int oldObjId, object oldObj, object newObj) { int num = FindElement(oldObj, out var isEmpty, out var isWrapped); if (isEmpty) { return 0; } int num2 = m_ids[num]; if (oldObjId > 0) { m_ids[num] = oldObjId; } else { RemoveAt(num); } num = FindElement(newObj, out isEmpty, out isWrapped); int result = 0; if (!isEmpty) { result = m_ids[num]; } m_objs[num] = newObj; m_ids[num] = num2; m_isWrapped[num] = isWrapped; return result; } private int FindElement(object obj, out bool isEmpty, out bool isWrapped) { isWrapped = false; int num = ComputeStartPosition(obj); for (int i = num; i != num - 1; i++) { if (m_objs[i] == null) { isEmpty = true; return i; } if (m_objs[i] == obj) { isEmpty = false; return i; } if (i == m_objs.Length - 1) { isWrapped = true; i = -1; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("An internal error has occurred. Object table overflow. This could be caused by serializing or deserializing extremely large object graphs."))); } private void RemoveAt(int position) { int num = m_objs.Length; int num2 = position; for (int i = ((position != num - 1) ? (position + 1) : 0); i != position; i++) { if (m_objs[i] == null) { m_objs[num2] = null; m_ids[num2] = 0; m_isWrapped[num2] = false; return; } int num3 = ComputeStartPosition(m_objs[i]); bool flag = i < position && !m_isWrapped[i]; bool flag2 = num2 < position; if ((num3 <= num2 && (!flag || flag2)) || (flag2 && !flag)) { m_objs[num2] = m_objs[i]; m_ids[num2] = m_ids[i]; m_isWrapped[num2] = m_isWrapped[i] && i > num2; num2 = i; } if (i == num - 1) { i = -1; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("An internal error has occurred. Object table overflow. This could be caused by serializing or deserializing extremely large object graphs."))); } private int ComputeStartPosition(object o) { return (RuntimeHelpers.GetHashCode(o) & 0x7FFFFFFF) % m_objs.Length; } private void Rehash() { int prime = GetPrime(m_objs.Length * 2); int[] ids = m_ids; object[] objs = m_objs; m_ids = new int[prime]; m_objs = new object[prime]; m_isWrapped = new bool[prime]; for (int i = 0; i < objs.Length; i++) { object obj = objs[i]; if (obj != null) { bool isEmpty; bool isWrapped; int num = FindElement(obj, out isEmpty, out isWrapped); m_objs[num] = obj; m_ids[num] = ids[i]; m_isWrapped[num] = isWrapped; } } } private static int GetPrime(int min) { for (int i = 0; i < primes.Length; i++) { int num = primes[i]; if (num >= min) { return num; } } for (int j = min | 1; j < int.MaxValue; j += 2) { if (IsPrime(j)) { return j; } } return min; } private static bool IsPrime(int candidate) { if (((uint)candidate & (true ? 1u : 0u)) != 0) { int num = (int)Math.Sqrt(candidate); for (int i = 3; i <= num; i += 2) { if (candidate % i == 0) { return false; } } return true; } return candidate == 2; } } internal abstract class PrimitiveDataContract : DataContract { private class PrimitiveDataContractCriticalHelper : DataContractCriticalHelper { private MethodInfo xmlFormatWriterMethod; private MethodInfo xmlFormatContentWriterMethod; private MethodInfo xmlFormatReaderMethod; internal MethodInfo XmlFormatWriterMethod { get { return xmlFormatWriterMethod; } set { xmlFormatWriterMethod = value; } } internal MethodInfo XmlFormatContentWriterMethod { get { return xmlFormatContentWriterMethod; } set { xmlFormatContentWriterMethod = value; } } internal MethodInfo XmlFormatReaderMethod { get { return xmlFormatReaderMethod; } set { xmlFormatReaderMethod = value; } } internal PrimitiveDataContractCriticalHelper(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(type) { SetDataContractName(name, ns); } } [SecurityCritical] private PrimitiveDataContractCriticalHelper helper; internal abstract string WriteMethodName { get; } internal abstract string ReadMethodName { get; } internal override XmlDictionaryString TopLevelElementNamespace { get { return DictionaryGlobals.SerializationNamespace; } set { } } internal override bool CanContainReferences => false; internal override bool IsPrimitive => true; internal override bool IsBuiltInDataContract => true; internal MethodInfo XmlFormatWriterMethod { [SecuritySafeCritical] get { if (helper.XmlFormatWriterMethod == null) { if (base.UnderlyingType.IsValueType) { helper.XmlFormatWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[3] { base.UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) }, null); } else { helper.XmlFormatWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[4] { typeof(XmlWriterDelegator), base.UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) }, null); } } return helper.XmlFormatWriterMethod; } } internal MethodInfo XmlFormatContentWriterMethod { [SecuritySafeCritical] get { if (helper.XmlFormatContentWriterMethod == null) { if (base.UnderlyingType.IsValueType) { helper.XmlFormatContentWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { base.UnderlyingType }, null); } else { helper.XmlFormatContentWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2] { typeof(XmlWriterDelegator), base.UnderlyingType }, null); } } return helper.XmlFormatContentWriterMethod; } } internal MethodInfo XmlFormatReaderMethod { [SecuritySafeCritical] get { if (helper.XmlFormatReaderMethod == null) { helper.XmlFormatReaderMethod = typeof(XmlReaderDelegator).GetMethod(ReadMethodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return helper.XmlFormatReaderMethod; } } [SecuritySafeCritical] protected PrimitiveDataContract(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(new PrimitiveDataContractCriticalHelper(type, name, ns)) { helper = base.Helper as PrimitiveDataContractCriticalHelper; } internal static PrimitiveDataContract GetPrimitiveDataContract(Type type) { return DataContract.GetBuiltInDataContract(type) as PrimitiveDataContract; } internal static PrimitiveDataContract GetPrimitiveDataContract(string name, string ns) { return DataContract.GetBuiltInDataContract(name, ns) as PrimitiveDataContract; } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { xmlWriter.WriteAnyType(obj); } protected object HandleReadValue(object obj, XmlObjectSerializerReadContext context) { context.AddNewObject(obj); return obj; } protected bool TryReadNullAtTopLevel(XmlReaderDelegator reader) { Attributes attributes = new Attributes(); attributes.Read(reader); if (attributes.Ref != Globals.NewObjectId) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Cannot deserialize since root element references unrecognized object with id '{0}'.", attributes.Ref))); } if (attributes.XsiNil) { reader.Skip(); return true; } return false; } internal override bool Equals(object other, Dictionary checkedContracts) { if (other is PrimitiveDataContract) { Type type = GetType(); Type type2 = other.GetType(); if (!type.Equals(type2) && !type.IsSubclassOf(type2)) { return type2.IsSubclassOf(type); } return true; } return false; } } internal class CharDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteChar"; internal override string ReadMethodName => "ReadElementContentAsChar"; internal CharDataContract() : this(DictionaryGlobals.CharLocalName, DictionaryGlobals.SerializationNamespace) { } internal CharDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(char), name, ns) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteChar((char)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context != null) { return HandleReadValue(reader.ReadElementContentAsChar(), context); } return reader.ReadElementContentAsChar(); } } internal class AsmxCharDataContract : CharDataContract { internal AsmxCharDataContract() : base(DictionaryGlobals.CharLocalName, DictionaryGlobals.AsmxTypesNamespace) { } } internal class BooleanDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteBoolean"; internal override string ReadMethodName => "ReadElementContentAsBoolean"; internal BooleanDataContract() : base(typeof(bool), DictionaryGlobals.BooleanLocalName, DictionaryGlobals.SchemaNamespace) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteBoolean((bool)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context != null) { return HandleReadValue(reader.ReadElementContentAsBoolean(), context); } return reader.ReadElementContentAsBoolean(); } } internal class SignedByteDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteSignedByte"; internal override string ReadMethodName => "ReadElementContentAsSignedByte"; internal SignedByteDataContract() : base(typeof(sbyte), DictionaryGlobals.SignedByteLocalName, DictionaryGlobals.SchemaNamespace) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteSignedByte((sbyte)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context != null) { return HandleReadValue(reader.ReadElementContentAsSignedByte(), context); } return reader.ReadElementContentAsSignedByte(); } } internal class UnsignedByteDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteUnsignedByte"; internal override string ReadMethodName => "ReadElementContentAsUnsignedByte"; internal UnsignedByteDataContract() : base(typeof(byte), DictionaryGlobals.UnsignedByteLocalName, DictionaryGlobals.SchemaNamespace) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteUnsignedByte((byte)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context != null) { return HandleReadValue(reader.ReadElementContentAsUnsignedByte(), context); } return reader.ReadElementContentAsUnsignedByte(); } } internal class ShortDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteShort"; internal override string ReadMethodName => "ReadElementContentAsShort"; internal ShortDataContract() : base(typeof(short), DictionaryGlobals.ShortLocalName, DictionaryGlobals.SchemaNamespace) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteShort((short)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context != null) { return HandleReadValue(reader.ReadElementContentAsShort(), context); } return reader.ReadElementContentAsShort(); } } internal class UnsignedShortDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteUnsignedShort"; internal override string ReadMethodName => "ReadElementContentAsUnsignedShort"; internal UnsignedShortDataContract() : base(typeof(ushort), DictionaryGlobals.UnsignedShortLocalName, DictionaryGlobals.SchemaNamespace) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteUnsignedShort((ushort)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context != null) { return HandleReadValue(reader.ReadElementContentAsUnsignedShort(), context); } return reader.ReadElementContentAsUnsignedShort(); } } internal class IntDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteInt"; internal override string ReadMethodName => "ReadElementContentAsInt"; internal IntDataContract() : base(typeof(int), DictionaryGlobals.IntLocalName, DictionaryGlobals.SchemaNamespace) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteInt((int)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context != null) { return HandleReadValue(reader.ReadElementContentAsInt(), context); } return reader.ReadElementContentAsInt(); } } internal class UnsignedIntDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteUnsignedInt"; internal override string ReadMethodName => "ReadElementContentAsUnsignedInt"; internal UnsignedIntDataContract() : base(typeof(uint), DictionaryGlobals.UnsignedIntLocalName, DictionaryGlobals.SchemaNamespace) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteUnsignedInt((uint)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context != null) { return HandleReadValue(reader.ReadElementContentAsUnsignedInt(), context); } return reader.ReadElementContentAsUnsignedInt(); } } internal class LongDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteLong"; internal override string ReadMethodName => "ReadElementContentAsLong"; internal LongDataContract() : this(DictionaryGlobals.LongLocalName, DictionaryGlobals.SchemaNamespace) { } internal LongDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(long), name, ns) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteLong((long)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context != null) { return HandleReadValue(reader.ReadElementContentAsLong(), context); } return reader.ReadElementContentAsLong(); } } internal class IntegerDataContract : LongDataContract { internal IntegerDataContract() : base(DictionaryGlobals.integerLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class PositiveIntegerDataContract : LongDataContract { internal PositiveIntegerDataContract() : base(DictionaryGlobals.positiveIntegerLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class NegativeIntegerDataContract : LongDataContract { internal NegativeIntegerDataContract() : base(DictionaryGlobals.negativeIntegerLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class NonPositiveIntegerDataContract : LongDataContract { internal NonPositiveIntegerDataContract() : base(DictionaryGlobals.nonPositiveIntegerLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class NonNegativeIntegerDataContract : LongDataContract { internal NonNegativeIntegerDataContract() : base(DictionaryGlobals.nonNegativeIntegerLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class UnsignedLongDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteUnsignedLong"; internal override string ReadMethodName => "ReadElementContentAsUnsignedLong"; internal UnsignedLongDataContract() : base(typeof(ulong), DictionaryGlobals.UnsignedLongLocalName, DictionaryGlobals.SchemaNamespace) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteUnsignedLong((ulong)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context != null) { return HandleReadValue(reader.ReadElementContentAsUnsignedLong(), context); } return reader.ReadElementContentAsUnsignedLong(); } } internal class FloatDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteFloat"; internal override string ReadMethodName => "ReadElementContentAsFloat"; internal FloatDataContract() : base(typeof(float), DictionaryGlobals.FloatLocalName, DictionaryGlobals.SchemaNamespace) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteFloat((float)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context != null) { return HandleReadValue(reader.ReadElementContentAsFloat(), context); } return reader.ReadElementContentAsFloat(); } } internal class DoubleDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteDouble"; internal override string ReadMethodName => "ReadElementContentAsDouble"; internal DoubleDataContract() : base(typeof(double), DictionaryGlobals.DoubleLocalName, DictionaryGlobals.SchemaNamespace) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteDouble((double)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context != null) { return HandleReadValue(reader.ReadElementContentAsDouble(), context); } return reader.ReadElementContentAsDouble(); } } internal class DecimalDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteDecimal"; internal override string ReadMethodName => "ReadElementContentAsDecimal"; internal DecimalDataContract() : base(typeof(decimal), DictionaryGlobals.DecimalLocalName, DictionaryGlobals.SchemaNamespace) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteDecimal((decimal)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context != null) { return HandleReadValue(reader.ReadElementContentAsDecimal(), context); } return reader.ReadElementContentAsDecimal(); } } internal class DateTimeDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteDateTime"; internal override string ReadMethodName => "ReadElementContentAsDateTime"; internal DateTimeDataContract() : base(typeof(DateTime), DictionaryGlobals.DateTimeLocalName, DictionaryGlobals.SchemaNamespace) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteDateTime((DateTime)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context != null) { return HandleReadValue(reader.ReadElementContentAsDateTime(), context); } return reader.ReadElementContentAsDateTime(); } } internal class StringDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteString"; internal override string ReadMethodName => "ReadElementContentAsString"; internal StringDataContract() : this(DictionaryGlobals.StringLocalName, DictionaryGlobals.SchemaNamespace) { } internal StringDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(string), name, ns) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteString((string)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context == null) { if (!TryReadNullAtTopLevel(reader)) { return reader.ReadElementContentAsString(); } return null; } return HandleReadValue(reader.ReadElementContentAsString(), context); } } internal class TimeDataContract : StringDataContract { internal TimeDataContract() : base(DictionaryGlobals.timeLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class DateDataContract : StringDataContract { internal DateDataContract() : base(DictionaryGlobals.dateLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class HexBinaryDataContract : StringDataContract { internal HexBinaryDataContract() : base(DictionaryGlobals.hexBinaryLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class GYearMonthDataContract : StringDataContract { internal GYearMonthDataContract() : base(DictionaryGlobals.gYearMonthLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class GYearDataContract : StringDataContract { internal GYearDataContract() : base(DictionaryGlobals.gYearLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class GMonthDayDataContract : StringDataContract { internal GMonthDayDataContract() : base(DictionaryGlobals.gMonthDayLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class GDayDataContract : StringDataContract { internal GDayDataContract() : base(DictionaryGlobals.gDayLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class GMonthDataContract : StringDataContract { internal GMonthDataContract() : base(DictionaryGlobals.gMonthLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class NormalizedStringDataContract : StringDataContract { internal NormalizedStringDataContract() : base(DictionaryGlobals.normalizedStringLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class TokenDataContract : StringDataContract { internal TokenDataContract() : base(DictionaryGlobals.tokenLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class LanguageDataContract : StringDataContract { internal LanguageDataContract() : base(DictionaryGlobals.languageLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class NameDataContract : StringDataContract { internal NameDataContract() : base(DictionaryGlobals.NameLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class NCNameDataContract : StringDataContract { internal NCNameDataContract() : base(DictionaryGlobals.NCNameLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class IDDataContract : StringDataContract { internal IDDataContract() : base(DictionaryGlobals.XSDIDLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class IDREFDataContract : StringDataContract { internal IDREFDataContract() : base(DictionaryGlobals.IDREFLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class IDREFSDataContract : StringDataContract { internal IDREFSDataContract() : base(DictionaryGlobals.IDREFSLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class ENTITYDataContract : StringDataContract { internal ENTITYDataContract() : base(DictionaryGlobals.ENTITYLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class ENTITIESDataContract : StringDataContract { internal ENTITIESDataContract() : base(DictionaryGlobals.ENTITIESLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class NMTOKENDataContract : StringDataContract { internal NMTOKENDataContract() : base(DictionaryGlobals.NMTOKENLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class NMTOKENSDataContract : StringDataContract { internal NMTOKENSDataContract() : base(DictionaryGlobals.NMTOKENSLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class ByteArrayDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteBase64"; internal override string ReadMethodName => "ReadElementContentAsBase64"; internal ByteArrayDataContract() : base(typeof(byte[]), DictionaryGlobals.ByteArrayLocalName, DictionaryGlobals.SchemaNamespace) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteBase64((byte[])obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context == null) { if (!TryReadNullAtTopLevel(reader)) { return reader.ReadElementContentAsBase64(); } return null; } return HandleReadValue(reader.ReadElementContentAsBase64(), context); } } internal class ObjectDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteAnyType"; internal override string ReadMethodName => "ReadElementContentAsAnyType"; internal override bool CanContainReferences => true; internal override bool IsPrimitive => false; internal ObjectDataContract() : base(typeof(object), DictionaryGlobals.ObjectLocalName, DictionaryGlobals.SchemaNamespace) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { object obj; if (reader.IsEmptyElement) { reader.Skip(); obj = new object(); } else { string localName = reader.LocalName; string namespaceURI = reader.NamespaceURI; reader.Read(); try { reader.ReadEndElement(); obj = new object(); } catch (XmlException innerException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Element {0} from namespace {1} cannot have child contents to be deserialized as an object. Please use XElement to deserialize this pattern of XML.", localName, namespaceURI), innerException)); } } if (context != null) { return HandleReadValue(obj, context); } return obj; } } internal class TimeSpanDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteTimeSpan"; internal override string ReadMethodName => "ReadElementContentAsTimeSpan"; internal TimeSpanDataContract() : this(DictionaryGlobals.TimeSpanLocalName, DictionaryGlobals.SerializationNamespace) { } internal TimeSpanDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(TimeSpan), name, ns) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteTimeSpan((TimeSpan)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context != null) { return HandleReadValue(reader.ReadElementContentAsTimeSpan(), context); } return reader.ReadElementContentAsTimeSpan(); } } internal class XsDurationDataContract : TimeSpanDataContract { internal XsDurationDataContract() : base(DictionaryGlobals.TimeSpanLocalName, DictionaryGlobals.SchemaNamespace) { } } internal class GuidDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteGuid"; internal override string ReadMethodName => "ReadElementContentAsGuid"; internal GuidDataContract() : this(DictionaryGlobals.GuidLocalName, DictionaryGlobals.SerializationNamespace) { } internal GuidDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(Guid), name, ns) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteGuid((Guid)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context != null) { return HandleReadValue(reader.ReadElementContentAsGuid(), context); } return reader.ReadElementContentAsGuid(); } } internal class AsmxGuidDataContract : GuidDataContract { internal AsmxGuidDataContract() : base(DictionaryGlobals.GuidLocalName, DictionaryGlobals.AsmxTypesNamespace) { } } internal class UriDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteUri"; internal override string ReadMethodName => "ReadElementContentAsUri"; internal UriDataContract() : base(typeof(Uri), DictionaryGlobals.UriLocalName, DictionaryGlobals.SchemaNamespace) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteUri((Uri)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context == null) { if (!TryReadNullAtTopLevel(reader)) { return reader.ReadElementContentAsUri(); } return null; } return HandleReadValue(reader.ReadElementContentAsUri(), context); } } internal class QNameDataContract : PrimitiveDataContract { internal override string WriteMethodName => "WriteQName"; internal override string ReadMethodName => "ReadElementContentAsQName"; internal override bool IsPrimitive => false; internal QNameDataContract() : base(typeof(XmlQualifiedName), DictionaryGlobals.QNameLocalName, DictionaryGlobals.SchemaNamespace) { } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteQName((XmlQualifiedName)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context == null) { if (!TryReadNullAtTopLevel(reader)) { return reader.ReadElementContentAsQName(); } return null; } return HandleReadValue(reader.ReadElementContentAsQName(), context); } internal override void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString ns) { if (ns == DictionaryGlobals.SerializationNamespace) { writer.WriteStartElement("z", name, ns); } else if (ns != null && ns.Value != null && ns.Value.Length > 0) { writer.WriteStartElement("q", name, ns); } else { writer.WriteStartElement(name, ns); } } } internal struct ScopedKnownTypes { internal Dictionary[] dataContractDictionaries; private int count; internal void Push(Dictionary dataContractDictionary) { if (dataContractDictionaries == null) { dataContractDictionaries = new Dictionary[4]; } else if (count == dataContractDictionaries.Length) { Array.Resize(ref dataContractDictionaries, dataContractDictionaries.Length * 2); } dataContractDictionaries[count++] = dataContractDictionary; } internal void Pop() { count--; } internal DataContract GetDataContract(XmlQualifiedName qname) { for (int num = count - 1; num >= 0; num--) { if (dataContractDictionaries[num].TryGetValue(qname, out var value)) { return value; } } return null; } } internal enum SerializationMode { SharedContract, SharedType } internal static class SerializationTrace { [SecurityCritical] private static TraceSource codeGen; internal static SourceSwitch CodeGenerationSwitch => CodeGenerationTraceSource.Switch; private static TraceSource CodeGenerationTraceSource { [SecuritySafeCritical] get { if (codeGen == null) { codeGen = new TraceSource("System.Runtime.Serialization.CodeGeneration"); } return codeGen; } } internal static void WriteInstruction(int lineNumber, string instruction) { } internal static void TraceInstruction(string instruction) { } } internal sealed class SpecialTypeDataContract : DataContract { private class SpecialTypeDataContractCriticalHelper : DataContractCriticalHelper { internal SpecialTypeDataContractCriticalHelper(Type type) : base(type) { } internal SpecialTypeDataContractCriticalHelper(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(type) { SetDataContractName(name, ns); } } [SecurityCritical] private SpecialTypeDataContractCriticalHelper helper; internal override bool IsBuiltInDataContract => true; [SecuritySafeCritical] public SpecialTypeDataContract(Type type) : base(new SpecialTypeDataContractCriticalHelper(type)) { helper = base.Helper as SpecialTypeDataContractCriticalHelper; } [SecuritySafeCritical] public SpecialTypeDataContract(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(new SpecialTypeDataContractCriticalHelper(type, name, ns)) { helper = base.Helper as SpecialTypeDataContractCriticalHelper; } } internal sealed class SurrogateDataContract : DataContract { private class SurrogateDataContractCriticalHelper : DataContractCriticalHelper { private ISerializationSurrogate serializationSurrogate; internal ISerializationSurrogate SerializationSurrogate => serializationSurrogate; internal SurrogateDataContractCriticalHelper(Type type, ISerializationSurrogate serializationSurrogate) : base(type) { this.serializationSurrogate = serializationSurrogate; DataContract.GetDefaultStableName(DataContract.GetClrTypeFullName(type), out var localName, out var text); SetDataContractName(DataContract.CreateQualifiedName(localName, text)); } } [SecurityCritical] private SurrogateDataContractCriticalHelper helper; internal ISerializationSurrogate SerializationSurrogate { [SecuritySafeCritical] get { return helper.SerializationSurrogate; } } [SecuritySafeCritical] internal SurrogateDataContract(Type type, ISerializationSurrogate serializationSurrogate) : base(new SurrogateDataContractCriticalHelper(type, serializationSurrogate)) { helper = base.Helper as SurrogateDataContractCriticalHelper; } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { SerializationInfo serInfo = new SerializationInfo(base.UnderlyingType, XmlObjectSerializer.FormatterConverter, !context.UnsafeTypeForwardingEnabled); SerializationSurrogateGetObjectData(obj, serInfo, context.GetStreamingContext()); context.WriteSerializationInfo(xmlWriter, base.UnderlyingType, serInfo); } [MethodImpl(MethodImplOptions.NoInlining)] [SecuritySafeCritical] [PermissionSet(SecurityAction.Demand, Unrestricted = true)] private object SerializationSurrogateSetObjectData(object obj, SerializationInfo serInfo, StreamingContext context) { return SerializationSurrogate.SetObjectData(obj, serInfo, context, null); } [MethodImpl(MethodImplOptions.NoInlining)] [SecuritySafeCritical] [PermissionSet(SecurityAction.Demand, Unrestricted = true)] internal static object GetRealObject(IObjectReference obj, StreamingContext context) { return obj.GetRealObject(context); } [MethodImpl(MethodImplOptions.NoInlining)] [SecuritySafeCritical] [PermissionSet(SecurityAction.Demand, Unrestricted = true)] private object GetUninitializedObject(Type objType) { return FormatterServices.GetUninitializedObject(objType); } [MethodImpl(MethodImplOptions.NoInlining)] [SecuritySafeCritical] [PermissionSet(SecurityAction.Demand, Unrestricted = true)] private void SerializationSurrogateGetObjectData(object obj, SerializationInfo serInfo, StreamingContext context) { SerializationSurrogate.GetObjectData(obj, serInfo, context); } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { xmlReader.Read(); Type underlyingType = base.UnderlyingType; object obj = (underlyingType.IsArray ? Array.CreateInstance(underlyingType.GetElementType(), 0) : GetUninitializedObject(underlyingType)); context.AddNewObject(obj); string objectId = context.GetObjectId(); SerializationInfo serInfo = context.ReadSerializationInfo(xmlReader, underlyingType); object obj2 = SerializationSurrogateSetObjectData(obj, serInfo, context.GetStreamingContext()); if (obj2 == null) { obj2 = obj; } if (obj2 is IDeserializationCallback) { ((IDeserializationCallback)obj2).OnDeserialization(null); } if (obj2 is IObjectReference) { obj2 = GetRealObject((IObjectReference)obj2, context.GetStreamingContext()); } context.ReplaceDeserializedObject(objectId, obj, obj2); xmlReader.ReadEndElement(); return obj2; } } internal sealed class TypeInformation { private string fullTypeName; private string assemblyString; private bool hasTypeForwardedFrom; internal string FullTypeName => fullTypeName; internal string AssemblyString => assemblyString; internal bool HasTypeForwardedFrom => hasTypeForwardedFrom; internal TypeInformation(string fullTypeName, string assemblyString, bool hasTypeForwardedFrom) { this.fullTypeName = fullTypeName; this.assemblyString = assemblyString; this.hasTypeForwardedFrom = hasTypeForwardedFrom; } } public static class XPathQueryGenerator { private class ExportContext { private XmlNamespaceManager namespaces; private int nextPrefix; private StringBuilder xPathBuilder; public XmlNamespaceManager Namespaces => namespaces; public string XPath => xPathBuilder.ToString(); public ExportContext(DataContract rootContract) { namespaces = new XmlNamespaceManager(new NameTable()); string text = SetNamespace(rootContract.TopLevelElementNamespace.Value); xPathBuilder = new StringBuilder("/" + text + ":" + rootContract.TopLevelElementName.Value); } public ExportContext(StringBuilder rootContractXPath) { namespaces = new XmlNamespaceManager(new NameTable()); xPathBuilder = rootContractXPath; } public void WriteChildToContext(DataMember contextMember, string prefix) { xPathBuilder.Append("/" + prefix + ":" + contextMember.Name); } public string SetNamespace(string ns) { string text = namespaces.LookupPrefix(ns); if (text == null || text.Length == 0) { text = "xg" + nextPrefix++.ToString(NumberFormatInfo.InvariantInfo); Namespaces.AddNamespace(text, ns); } return text; } } private const string XPathSeparator = "/"; private const string NsSeparator = ":"; public static string CreateFromDataContractSerializer(Type type, MemberInfo[] pathToMember, out XmlNamespaceManager namespaces) { return CreateFromDataContractSerializer(type, pathToMember, null, out namespaces); } public static string CreateFromDataContractSerializer(Type type, MemberInfo[] pathToMember, StringBuilder rootElementXpath, out XmlNamespaceManager namespaces) { if (type == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("type")); } if (pathToMember == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("pathToMember")); } DataContract dataContract = DataContract.GetDataContract(type); ExportContext exportContext = ((rootElementXpath != null) ? new ExportContext(rootElementXpath) : new ExportContext(dataContract)); for (int i = 0; i < pathToMember.Length; i++) { dataContract = ProcessDataContract(dataContract, exportContext, pathToMember[i]); } namespaces = exportContext.Namespaces; return exportContext.XPath; } private static DataContract ProcessDataContract(DataContract contract, ExportContext context, MemberInfo memberNode) { if (contract is ClassDataContract) { return ProcessClassDataContract((ClassDataContract)contract, context, memberNode); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("The path to member was not found for XPath query generator."))); } private static DataContract ProcessClassDataContract(ClassDataContract contract, ExportContext context, MemberInfo memberNode) { string prefix = context.SetNamespace(contract.Namespace.Value); foreach (DataMember dataMember in GetDataMembers(contract)) { if (dataMember.MemberInfo.Name == memberNode.Name && dataMember.MemberInfo.DeclaringType.IsAssignableFrom(memberNode.DeclaringType)) { context.WriteChildToContext(dataMember, prefix); return dataMember.MemberTypeContract; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("The path to member was not found for XPath query generator."))); } private static IEnumerable GetDataMembers(ClassDataContract contract) { if (contract.BaseContract != null) { foreach (DataMember dataMember in GetDataMembers(contract.BaseContract)) { yield return dataMember; } } if (contract.Members == null) { yield break; } foreach (DataMember member in contract.Members) { yield return member; } } } internal delegate IXmlSerializable CreateXmlSerializableDelegate(); internal sealed class XmlDataContract : DataContract { private class XmlDataContractCriticalHelper : DataContractCriticalHelper { private Dictionary knownDataContracts; private bool isKnownTypeAttributeChecked; private XmlDictionaryString topLevelElementName; private XmlDictionaryString topLevelElementNamespace; private bool isTopLevelElementNullable; private bool isTypeDefinedOnImport; private XmlSchemaType xsdType; private bool hasRoot; private CreateXmlSerializableDelegate createXmlSerializable; internal override Dictionary KnownDataContracts { get { if (!isKnownTypeAttributeChecked && base.UnderlyingType != null) { lock (this) { if (!isKnownTypeAttributeChecked) { knownDataContracts = DataContract.ImportKnownTypeAttributes(base.UnderlyingType); Thread.MemoryBarrier(); isKnownTypeAttributeChecked = true; } } } return knownDataContracts; } set { knownDataContracts = value; } } internal XmlSchemaType XsdType { get { return xsdType; } set { xsdType = value; } } internal bool IsAnonymous => xsdType != null; internal override bool HasRoot { get { return hasRoot; } set { hasRoot = value; } } internal override XmlDictionaryString TopLevelElementName { get { return topLevelElementName; } set { topLevelElementName = value; } } internal override XmlDictionaryString TopLevelElementNamespace { get { return topLevelElementNamespace; } set { topLevelElementNamespace = value; } } internal bool IsTopLevelElementNullable { get { return isTopLevelElementNullable; } set { isTopLevelElementNullable = value; } } internal bool IsTypeDefinedOnImport { get { return isTypeDefinedOnImport; } set { isTypeDefinedOnImport = value; } } internal CreateXmlSerializableDelegate CreateXmlSerializableDelegate { get { return createXmlSerializable; } set { createXmlSerializable = value; } } internal XmlDataContractCriticalHelper() { } internal XmlDataContractCriticalHelper(Type type) : base(type) { if (type.IsDefined(Globals.TypeOfDataContractAttribute, inherit: false)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Type '{0}' cannot be IXmlSerializable and have DataContractAttribute attribute.", DataContract.GetClrTypeFullName(type)))); } if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, inherit: false)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Type '{0}' cannot be IXmlSerializable and have CollectionDataContractAttribute attribute.", DataContract.GetClrTypeFullName(type)))); } SchemaExporter.GetXmlTypeInfo(type, out var xmlQualifiedName, out var xmlSchemaType, out var flag); base.StableName = xmlQualifiedName; XsdType = xmlSchemaType; HasRoot = flag; XmlDictionary xmlDictionary = new XmlDictionary(); base.Name = xmlDictionary.Add(base.StableName.Name); base.Namespace = xmlDictionary.Add(base.StableName.Namespace); object[] array = ((base.UnderlyingType == null) ? null : base.UnderlyingType.GetCustomAttributes(Globals.TypeOfXmlRootAttribute, inherit: false)); if (array == null || array.Length == 0) { if (flag) { topLevelElementName = base.Name; topLevelElementNamespace = ((base.StableName.Namespace == "http://www.w3.org/2001/XMLSchema") ? DictionaryGlobals.EmptyString : base.Namespace); isTopLevelElementNullable = true; } return; } if (flag) { XmlRootAttribute xmlRootAttribute = (XmlRootAttribute)array[0]; isTopLevelElementNullable = xmlRootAttribute.IsNullable; string elementName = xmlRootAttribute.ElementName; topLevelElementName = ((elementName == null || elementName.Length == 0) ? base.Name : xmlDictionary.Add(DataContract.EncodeLocalName(elementName))); string @namespace = xmlRootAttribute.Namespace; topLevelElementNamespace = ((@namespace == null || @namespace.Length == 0) ? DictionaryGlobals.EmptyString : xmlDictionary.Add(@namespace)); return; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Type '{0}' cannot specify an XmlRootAttribute attribute because its IsAny setting is 'true'. This type must write all its contents including the root element. Verify that the IXmlSerializable implementation is correct.", DataContract.GetClrTypeFullName(base.UnderlyingType)))); } } [SecurityCritical] private XmlDataContractCriticalHelper helper; internal override Dictionary KnownDataContracts { [SecuritySafeCritical] get { return helper.KnownDataContracts; } [SecurityCritical] set { helper.KnownDataContracts = value; } } internal XmlSchemaType XsdType { [SecuritySafeCritical] get { return helper.XsdType; } [SecurityCritical] set { helper.XsdType = value; } } internal bool IsAnonymous { [SecuritySafeCritical] get { return helper.IsAnonymous; } } internal override bool HasRoot { [SecuritySafeCritical] get { return helper.HasRoot; } [SecurityCritical] set { helper.HasRoot = value; } } internal override XmlDictionaryString TopLevelElementName { [SecuritySafeCritical] get { return helper.TopLevelElementName; } [SecurityCritical] set { helper.TopLevelElementName = value; } } internal override XmlDictionaryString TopLevelElementNamespace { [SecuritySafeCritical] get { return helper.TopLevelElementNamespace; } [SecurityCritical] set { helper.TopLevelElementNamespace = value; } } internal bool IsTopLevelElementNullable { [SecuritySafeCritical] get { return helper.IsTopLevelElementNullable; } [SecurityCritical] set { helper.IsTopLevelElementNullable = value; } } internal bool IsTypeDefinedOnImport { [SecuritySafeCritical] get { return helper.IsTypeDefinedOnImport; } [SecurityCritical] set { helper.IsTypeDefinedOnImport = value; } } internal CreateXmlSerializableDelegate CreateXmlSerializableDelegate { [SecuritySafeCritical] get { if (helper.CreateXmlSerializableDelegate == null) { lock (this) { if (helper.CreateXmlSerializableDelegate == null) { CreateXmlSerializableDelegate createXmlSerializableDelegate = GenerateCreateXmlSerializableDelegate(); Thread.MemoryBarrier(); helper.CreateXmlSerializableDelegate = createXmlSerializableDelegate; } } } return helper.CreateXmlSerializableDelegate; } } internal override bool CanContainReferences => false; internal override bool IsBuiltInDataContract { get { if (!(base.UnderlyingType == Globals.TypeOfXmlElement)) { return base.UnderlyingType == Globals.TypeOfXmlNodeArray; } return true; } } [SecuritySafeCritical] internal XmlDataContract() : base(new XmlDataContractCriticalHelper()) { helper = base.Helper as XmlDataContractCriticalHelper; } [SecuritySafeCritical] internal XmlDataContract(Type type) : base(new XmlDataContractCriticalHelper(type)) { helper = base.Helper as XmlDataContractCriticalHelper; } private ConstructorInfo GetConstructor() { Type underlyingType = base.UnderlyingType; if (underlyingType.IsValueType) { return null; } ConstructorInfo constructor = underlyingType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Globals.EmptyTypeArray, null); if (constructor == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("IXmlSerializable Type '{0}' must have default constructor.", DataContract.GetClrTypeFullName(underlyingType)))); } return constructor; } [SecurityCritical] internal void SetTopLevelElementName(XmlQualifiedName elementName) { if (elementName != null) { XmlDictionary xmlDictionary = new XmlDictionary(); TopLevelElementName = xmlDictionary.Add(elementName.Name); TopLevelElementNamespace = xmlDictionary.Add(elementName.Namespace); } } internal override bool Equals(object other, Dictionary checkedContracts) { if (IsEqualOrChecked(other, checkedContracts)) { return true; } if (other is XmlDataContract xmlDataContract) { if (HasRoot != xmlDataContract.HasRoot) { return false; } if (IsAnonymous) { return xmlDataContract.IsAnonymous; } if (base.StableName.Name == xmlDataContract.StableName.Name) { return base.StableName.Namespace == xmlDataContract.StableName.Namespace; } return false; } return false; } public override int GetHashCode() { return base.GetHashCode(); } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { if (context == null) { XmlObjectSerializerWriteContext.WriteRootIXmlSerializable(xmlWriter, obj); } else { context.WriteIXmlSerializable(xmlWriter, obj); } } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { object obj; if (context == null) { obj = XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, this, isMemberType: true); } else { obj = context.ReadIXmlSerializable(xmlReader, this, isMemberType: true); context.AddNewObject(obj); } xmlReader.ReadEndElement(); return obj; } internal CreateXmlSerializableDelegate GenerateCreateXmlSerializableDelegate() { return () => new XmlDataContractInterpreter(this).CreateXmlSerializable(); } } internal static class XmlFormatGeneratorStatics { [SecurityCritical] private static MethodInfo writeStartElementMethod2; [SecurityCritical] private static MethodInfo writeStartElementMethod3; [SecurityCritical] private static MethodInfo writeEndElementMethod; [SecurityCritical] private static MethodInfo writeNamespaceDeclMethod; [SecurityCritical] private static PropertyInfo extensionDataProperty; [SecurityCritical] private static MethodInfo boxPointer; [SecurityCritical] private static ConstructorInfo dictionaryEnumeratorCtor; [SecurityCritical] private static MethodInfo ienumeratorMoveNextMethod; [SecurityCritical] private static MethodInfo ienumeratorGetCurrentMethod; [SecurityCritical] private static MethodInfo getItemContractMethod; [SecurityCritical] private static MethodInfo isStartElementMethod2; [SecurityCritical] private static MethodInfo isStartElementMethod0; [SecurityCritical] private static MethodInfo getUninitializedObjectMethod; [SecurityCritical] private static MethodInfo onDeserializationMethod; [SecurityCritical] private static MethodInfo unboxPointer; [SecurityCritical] private static PropertyInfo nodeTypeProperty; [SecurityCritical] private static ConstructorInfo serializationExceptionCtor; [SecurityCritical] private static ConstructorInfo extensionDataObjectCtor; [SecurityCritical] private static ConstructorInfo hashtableCtor; [SecurityCritical] private static MethodInfo getStreamingContextMethod; [SecurityCritical] private static MethodInfo getCollectionMemberMethod; [SecurityCritical] private static MethodInfo storeCollectionMemberInfoMethod; [SecurityCritical] private static MethodInfo storeIsGetOnlyCollectionMethod; [SecurityCritical] private static MethodInfo throwNullValueReturnedForGetOnlyCollectionExceptionMethod; private static MethodInfo throwArrayExceededSizeExceptionMethod; [SecurityCritical] private static MethodInfo incrementItemCountMethod; [SecurityCritical] private static MethodInfo demandSerializationFormatterPermissionMethod; [SecurityCritical] private static MethodInfo demandMemberAccessPermissionMethod; [SecurityCritical] private static MethodInfo internalDeserializeMethod; [SecurityCritical] private static MethodInfo moveToNextElementMethod; [SecurityCritical] private static MethodInfo getMemberIndexMethod; [SecurityCritical] private static MethodInfo getMemberIndexWithRequiredMembersMethod; [SecurityCritical] private static MethodInfo throwRequiredMemberMissingExceptionMethod; [SecurityCritical] private static MethodInfo skipUnknownElementMethod; [SecurityCritical] private static MethodInfo readIfNullOrRefMethod; [SecurityCritical] private static MethodInfo readAttributesMethod; [SecurityCritical] private static MethodInfo resetAttributesMethod; [SecurityCritical] private static MethodInfo getObjectIdMethod; [SecurityCritical] private static MethodInfo getArraySizeMethod; [SecurityCritical] private static MethodInfo addNewObjectMethod; [SecurityCritical] private static MethodInfo addNewObjectWithIdMethod; [SecurityCritical] private static MethodInfo replaceDeserializedObjectMethod; [SecurityCritical] private static MethodInfo getExistingObjectMethod; [SecurityCritical] private static MethodInfo getRealObjectMethod; [SecurityCritical] private static MethodInfo readMethod; [SecurityCritical] private static MethodInfo ensureArraySizeMethod; [SecurityCritical] private static MethodInfo trimArraySizeMethod; [SecurityCritical] private static MethodInfo checkEndOfArrayMethod; [SecurityCritical] private static MethodInfo getArrayLengthMethod; [SecurityCritical] private static MethodInfo readSerializationInfoMethod; [SecurityCritical] private static MethodInfo createUnexpectedStateExceptionMethod; [SecurityCritical] private static MethodInfo internalSerializeReferenceMethod; [SecurityCritical] private static MethodInfo internalSerializeMethod; [SecurityCritical] private static MethodInfo writeNullMethod; [SecurityCritical] private static MethodInfo incrementArrayCountMethod; [SecurityCritical] private static MethodInfo incrementCollectionCountMethod; [SecurityCritical] private static MethodInfo incrementCollectionCountGenericMethod; [SecurityCritical] private static MethodInfo getDefaultValueMethod; [SecurityCritical] private static MethodInfo getNullableValueMethod; [SecurityCritical] private static MethodInfo throwRequiredMemberMustBeEmittedMethod; [SecurityCritical] private static MethodInfo getHasValueMethod; [SecurityCritical] private static MethodInfo writeISerializableMethod; [SecurityCritical] private static MethodInfo writeExtensionDataMethod; [SecurityCritical] private static MethodInfo writeXmlValueMethod; [SecurityCritical] private static MethodInfo readXmlValueMethod; [SecurityCritical] private static MethodInfo throwTypeNotSerializableMethod; [SecurityCritical] private static PropertyInfo namespaceProperty; [SecurityCritical] private static FieldInfo contractNamespacesField; [SecurityCritical] private static FieldInfo memberNamesField; [SecurityCritical] private static MethodInfo extensionDataSetExplicitMethodInfo; [SecurityCritical] private static PropertyInfo childElementNamespacesProperty; [SecurityCritical] private static PropertyInfo collectionItemNameProperty; [SecurityCritical] private static PropertyInfo childElementNamespaceProperty; [SecurityCritical] private static MethodInfo getDateTimeOffsetMethod; [SecurityCritical] private static MethodInfo getDateTimeOffsetAdapterMethod; [SecurityCritical] private static MethodInfo traceInstructionMethod; [SecurityCritical] private static MethodInfo throwInvalidDataContractExceptionMethod; [SecurityCritical] private static PropertyInfo serializeReadOnlyTypesProperty; [SecurityCritical] private static PropertyInfo classSerializationExceptionMessageProperty; [SecurityCritical] private static PropertyInfo collectionSerializationExceptionMessageProperty; internal static MethodInfo WriteStartElementMethod2 { [SecuritySafeCritical] get { if (writeStartElementMethod2 == null) { writeStartElementMethod2 = typeof(XmlWriterDelegator).GetMethod("WriteStartElement", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2] { typeof(XmlDictionaryString), typeof(XmlDictionaryString) }, null); } return writeStartElementMethod2; } } internal static MethodInfo WriteStartElementMethod3 { [SecuritySafeCritical] get { if (writeStartElementMethod3 == null) { writeStartElementMethod3 = typeof(XmlWriterDelegator).GetMethod("WriteStartElement", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[3] { typeof(string), typeof(XmlDictionaryString), typeof(XmlDictionaryString) }, null); } return writeStartElementMethod3; } } internal static MethodInfo WriteEndElementMethod { [SecuritySafeCritical] get { if (writeEndElementMethod == null) { writeEndElementMethod = typeof(XmlWriterDelegator).GetMethod("WriteEndElement", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null); } return writeEndElementMethod; } } internal static MethodInfo WriteNamespaceDeclMethod { [SecuritySafeCritical] get { if (writeNamespaceDeclMethod == null) { writeNamespaceDeclMethod = typeof(XmlWriterDelegator).GetMethod("WriteNamespaceDecl", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(XmlDictionaryString) }, null); } return writeNamespaceDeclMethod; } } internal static PropertyInfo ExtensionDataProperty { [SecuritySafeCritical] get { if (extensionDataProperty == null) { extensionDataProperty = typeof(IExtensibleDataObject).GetProperty("ExtensionData"); } return extensionDataProperty; } } internal static MethodInfo BoxPointer { [SecuritySafeCritical] get { if (boxPointer == null) { boxPointer = typeof(Pointer).GetMethod("Box"); } return boxPointer; } } internal static ConstructorInfo DictionaryEnumeratorCtor { [SecuritySafeCritical] get { if (dictionaryEnumeratorCtor == null) { dictionaryEnumeratorCtor = Globals.TypeOfDictionaryEnumerator.GetConstructor(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { Globals.TypeOfIDictionaryEnumerator }, null); } return dictionaryEnumeratorCtor; } } internal static MethodInfo MoveNextMethod { [SecuritySafeCritical] get { if (ienumeratorMoveNextMethod == null) { ienumeratorMoveNextMethod = typeof(IEnumerator).GetMethod("MoveNext"); } return ienumeratorMoveNextMethod; } } internal static MethodInfo GetCurrentMethod { [SecuritySafeCritical] get { if (ienumeratorGetCurrentMethod == null) { ienumeratorGetCurrentMethod = typeof(IEnumerator).GetProperty("Current").GetGetMethod(); } return ienumeratorGetCurrentMethod; } } internal static MethodInfo GetItemContractMethod { [SecuritySafeCritical] get { if (getItemContractMethod == null) { getItemContractMethod = typeof(CollectionDataContract).GetProperty("ItemContract", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetGetMethod(nonPublic: true); } return getItemContractMethod; } } internal static MethodInfo IsStartElementMethod2 { [SecuritySafeCritical] get { if (isStartElementMethod2 == null) { isStartElementMethod2 = typeof(XmlReaderDelegator).GetMethod("IsStartElement", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2] { typeof(XmlDictionaryString), typeof(XmlDictionaryString) }, null); } return isStartElementMethod2; } } internal static MethodInfo IsStartElementMethod0 { [SecuritySafeCritical] get { if (isStartElementMethod0 == null) { isStartElementMethod0 = typeof(XmlReaderDelegator).GetMethod("IsStartElement", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null); } return isStartElementMethod0; } } internal static MethodInfo GetUninitializedObjectMethod { [SecuritySafeCritical] get { if (getUninitializedObjectMethod == null) { getUninitializedObjectMethod = typeof(XmlFormatReaderGenerator).GetMethod("UnsafeGetUninitializedObject", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(int) }, null); } return getUninitializedObjectMethod; } } internal static MethodInfo OnDeserializationMethod { [SecuritySafeCritical] get { if (onDeserializationMethod == null) { onDeserializationMethod = typeof(IDeserializationCallback).GetMethod("OnDeserialization"); } return onDeserializationMethod; } } internal static MethodInfo UnboxPointer { [SecuritySafeCritical] get { if (unboxPointer == null) { unboxPointer = typeof(Pointer).GetMethod("Unbox"); } return unboxPointer; } } internal static PropertyInfo NodeTypeProperty { [SecuritySafeCritical] get { if (nodeTypeProperty == null) { nodeTypeProperty = typeof(XmlReaderDelegator).GetProperty("NodeType", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return nodeTypeProperty; } } internal static ConstructorInfo SerializationExceptionCtor { [SecuritySafeCritical] get { if (serializationExceptionCtor == null) { serializationExceptionCtor = typeof(SerializationException).GetConstructor(new Type[1] { typeof(string) }); } return serializationExceptionCtor; } } internal static ConstructorInfo ExtensionDataObjectCtor { [SecuritySafeCritical] get { if (extensionDataObjectCtor == null) { extensionDataObjectCtor = typeof(ExtensionDataObject).GetConstructor(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null); } return extensionDataObjectCtor; } } internal static ConstructorInfo HashtableCtor { [SecuritySafeCritical] get { if (hashtableCtor == null) { hashtableCtor = Globals.TypeOfHashtable.GetConstructor(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, Globals.EmptyTypeArray, null); } return hashtableCtor; } } internal static MethodInfo GetStreamingContextMethod { [SecuritySafeCritical] get { if (getStreamingContextMethod == null) { getStreamingContextMethod = typeof(XmlObjectSerializerContext).GetMethod("GetStreamingContext", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return getStreamingContextMethod; } } internal static MethodInfo GetCollectionMemberMethod { [SecuritySafeCritical] get { if (getCollectionMemberMethod == null) { getCollectionMemberMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetCollectionMember", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return getCollectionMemberMethod; } } internal static MethodInfo StoreCollectionMemberInfoMethod { [SecuritySafeCritical] get { if (storeCollectionMemberInfoMethod == null) { storeCollectionMemberInfoMethod = typeof(XmlObjectSerializerReadContext).GetMethod("StoreCollectionMemberInfo", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(object) }, null); } return storeCollectionMemberInfoMethod; } } internal static MethodInfo StoreIsGetOnlyCollectionMethod { [SecuritySafeCritical] get { if (storeIsGetOnlyCollectionMethod == null) { storeIsGetOnlyCollectionMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("StoreIsGetOnlyCollection", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return storeIsGetOnlyCollectionMethod; } } internal static MethodInfo ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod { [SecuritySafeCritical] get { if (throwNullValueReturnedForGetOnlyCollectionExceptionMethod == null) { throwNullValueReturnedForGetOnlyCollectionExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ThrowNullValueReturnedForGetOnlyCollectionException", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return throwNullValueReturnedForGetOnlyCollectionExceptionMethod; } } internal static MethodInfo ThrowArrayExceededSizeExceptionMethod { [SecuritySafeCritical] get { if (throwArrayExceededSizeExceptionMethod == null) { throwArrayExceededSizeExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ThrowArrayExceededSizeException", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return throwArrayExceededSizeExceptionMethod; } } internal static MethodInfo IncrementItemCountMethod { [SecuritySafeCritical] get { if (incrementItemCountMethod == null) { incrementItemCountMethod = typeof(XmlObjectSerializerContext).GetMethod("IncrementItemCount", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return incrementItemCountMethod; } } internal static MethodInfo DemandSerializationFormatterPermissionMethod { [SecuritySafeCritical] get { if (demandSerializationFormatterPermissionMethod == null) { demandSerializationFormatterPermissionMethod = typeof(XmlObjectSerializerContext).GetMethod("DemandSerializationFormatterPermission", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return demandSerializationFormatterPermissionMethod; } } internal static MethodInfo DemandMemberAccessPermissionMethod { [SecuritySafeCritical] get { if (demandMemberAccessPermissionMethod == null) { demandMemberAccessPermissionMethod = typeof(XmlObjectSerializerContext).GetMethod("DemandMemberAccessPermission", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return demandMemberAccessPermissionMethod; } } internal static MethodInfo InternalDeserializeMethod { [SecuritySafeCritical] get { if (internalDeserializeMethod == null) { internalDeserializeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("InternalDeserialize", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[5] { typeof(XmlReaderDelegator), typeof(int), typeof(RuntimeTypeHandle), typeof(string), typeof(string) }, null); } return internalDeserializeMethod; } } internal static MethodInfo MoveToNextElementMethod { [SecuritySafeCritical] get { if (moveToNextElementMethod == null) { moveToNextElementMethod = typeof(XmlObjectSerializerReadContext).GetMethod("MoveToNextElement", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return moveToNextElementMethod; } } internal static MethodInfo GetMemberIndexMethod { [SecuritySafeCritical] get { if (getMemberIndexMethod == null) { getMemberIndexMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetMemberIndex", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return getMemberIndexMethod; } } internal static MethodInfo GetMemberIndexWithRequiredMembersMethod { [SecuritySafeCritical] get { if (getMemberIndexWithRequiredMembersMethod == null) { getMemberIndexWithRequiredMembersMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetMemberIndexWithRequiredMembers", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return getMemberIndexWithRequiredMembersMethod; } } internal static MethodInfo ThrowRequiredMemberMissingExceptionMethod { [SecuritySafeCritical] get { if (throwRequiredMemberMissingExceptionMethod == null) { throwRequiredMemberMissingExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ThrowRequiredMemberMissingException", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return throwRequiredMemberMissingExceptionMethod; } } internal static MethodInfo SkipUnknownElementMethod { [SecuritySafeCritical] get { if (skipUnknownElementMethod == null) { skipUnknownElementMethod = typeof(XmlObjectSerializerReadContext).GetMethod("SkipUnknownElement", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return skipUnknownElementMethod; } } internal static MethodInfo ReadIfNullOrRefMethod { [SecuritySafeCritical] get { if (readIfNullOrRefMethod == null) { readIfNullOrRefMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadIfNullOrRef", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[3] { typeof(XmlReaderDelegator), typeof(Type), typeof(bool) }, null); } return readIfNullOrRefMethod; } } internal static MethodInfo ReadAttributesMethod { [SecuritySafeCritical] get { if (readAttributesMethod == null) { readAttributesMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadAttributes", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return readAttributesMethod; } } internal static MethodInfo ResetAttributesMethod { [SecuritySafeCritical] get { if (resetAttributesMethod == null) { resetAttributesMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ResetAttributes", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return resetAttributesMethod; } } internal static MethodInfo GetObjectIdMethod { [SecuritySafeCritical] get { if (getObjectIdMethod == null) { getObjectIdMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetObjectId", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return getObjectIdMethod; } } internal static MethodInfo GetArraySizeMethod { [SecuritySafeCritical] get { if (getArraySizeMethod == null) { getArraySizeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetArraySize", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return getArraySizeMethod; } } internal static MethodInfo AddNewObjectMethod { [SecuritySafeCritical] get { if (addNewObjectMethod == null) { addNewObjectMethod = typeof(XmlObjectSerializerReadContext).GetMethod("AddNewObject", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return addNewObjectMethod; } } internal static MethodInfo AddNewObjectWithIdMethod { [SecuritySafeCritical] get { if (addNewObjectWithIdMethod == null) { addNewObjectWithIdMethod = typeof(XmlObjectSerializerReadContext).GetMethod("AddNewObjectWithId", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return addNewObjectWithIdMethod; } } internal static MethodInfo ReplaceDeserializedObjectMethod { [SecuritySafeCritical] get { if (replaceDeserializedObjectMethod == null) { replaceDeserializedObjectMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReplaceDeserializedObject", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return replaceDeserializedObjectMethod; } } internal static MethodInfo GetExistingObjectMethod { [SecuritySafeCritical] get { if (getExistingObjectMethod == null) { getExistingObjectMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetExistingObject", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return getExistingObjectMethod; } } internal static MethodInfo GetRealObjectMethod { [SecuritySafeCritical] get { if (getRealObjectMethod == null) { getRealObjectMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetRealObject", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return getRealObjectMethod; } } internal static MethodInfo ReadMethod { [SecuritySafeCritical] get { if (readMethod == null) { readMethod = typeof(XmlObjectSerializerReadContext).GetMethod("Read", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return readMethod; } } internal static MethodInfo EnsureArraySizeMethod { [SecuritySafeCritical] get { if (ensureArraySizeMethod == null) { ensureArraySizeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("EnsureArraySize", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return ensureArraySizeMethod; } } internal static MethodInfo TrimArraySizeMethod { [SecuritySafeCritical] get { if (trimArraySizeMethod == null) { trimArraySizeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("TrimArraySize", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return trimArraySizeMethod; } } internal static MethodInfo CheckEndOfArrayMethod { [SecuritySafeCritical] get { if (checkEndOfArrayMethod == null) { checkEndOfArrayMethod = typeof(XmlObjectSerializerReadContext).GetMethod("CheckEndOfArray", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return checkEndOfArrayMethod; } } internal static MethodInfo GetArrayLengthMethod { [SecuritySafeCritical] get { if (getArrayLengthMethod == null) { getArrayLengthMethod = Globals.TypeOfArray.GetProperty("Length").GetGetMethod(); } return getArrayLengthMethod; } } internal static MethodInfo ReadSerializationInfoMethod { [SecuritySafeCritical] get { if (readSerializationInfoMethod == null) { readSerializationInfoMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadSerializationInfo", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return readSerializationInfoMethod; } } internal static MethodInfo CreateUnexpectedStateExceptionMethod { [SecuritySafeCritical] get { if (createUnexpectedStateExceptionMethod == null) { createUnexpectedStateExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("CreateUnexpectedStateException", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2] { typeof(XmlNodeType), typeof(XmlReaderDelegator) }, null); } return createUnexpectedStateExceptionMethod; } } internal static MethodInfo InternalSerializeReferenceMethod { [SecuritySafeCritical] get { if (internalSerializeReferenceMethod == null) { internalSerializeReferenceMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("InternalSerializeReference", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return internalSerializeReferenceMethod; } } internal static MethodInfo InternalSerializeMethod { [SecuritySafeCritical] get { if (internalSerializeMethod == null) { internalSerializeMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("InternalSerialize", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return internalSerializeMethod; } } internal static MethodInfo WriteNullMethod { [SecuritySafeCritical] get { if (writeNullMethod == null) { writeNullMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteNull", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[3] { typeof(XmlWriterDelegator), typeof(Type), typeof(bool) }, null); } return writeNullMethod; } } internal static MethodInfo IncrementArrayCountMethod { [SecuritySafeCritical] get { if (incrementArrayCountMethod == null) { incrementArrayCountMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("IncrementArrayCount", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return incrementArrayCountMethod; } } internal static MethodInfo IncrementCollectionCountMethod { [SecuritySafeCritical] get { if (incrementCollectionCountMethod == null) { incrementCollectionCountMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("IncrementCollectionCount", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2] { typeof(XmlWriterDelegator), typeof(ICollection) }, null); } return incrementCollectionCountMethod; } } internal static MethodInfo IncrementCollectionCountGenericMethod { [SecuritySafeCritical] get { if (incrementCollectionCountGenericMethod == null) { incrementCollectionCountGenericMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("IncrementCollectionCountGeneric", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return incrementCollectionCountGenericMethod; } } internal static MethodInfo GetDefaultValueMethod { [SecuritySafeCritical] get { if (getDefaultValueMethod == null) { getDefaultValueMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("GetDefaultValue", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return getDefaultValueMethod; } } internal static MethodInfo GetNullableValueMethod { [SecuritySafeCritical] get { if (getNullableValueMethod == null) { getNullableValueMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("GetNullableValue", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return getNullableValueMethod; } } internal static MethodInfo ThrowRequiredMemberMustBeEmittedMethod { [SecuritySafeCritical] get { if (throwRequiredMemberMustBeEmittedMethod == null) { throwRequiredMemberMustBeEmittedMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("ThrowRequiredMemberMustBeEmitted", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return throwRequiredMemberMustBeEmittedMethod; } } internal static MethodInfo GetHasValueMethod { [SecuritySafeCritical] get { if (getHasValueMethod == null) { getHasValueMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("GetHasValue", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return getHasValueMethod; } } internal static MethodInfo WriteISerializableMethod { [SecuritySafeCritical] get { if (writeISerializableMethod == null) { writeISerializableMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteISerializable", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return writeISerializableMethod; } } internal static MethodInfo WriteExtensionDataMethod { [SecuritySafeCritical] get { if (writeExtensionDataMethod == null) { writeExtensionDataMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteExtensionData", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return writeExtensionDataMethod; } } internal static MethodInfo WriteXmlValueMethod { [SecuritySafeCritical] get { if (writeXmlValueMethod == null) { writeXmlValueMethod = typeof(DataContract).GetMethod("WriteXmlValue", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return writeXmlValueMethod; } } internal static MethodInfo ReadXmlValueMethod { [SecuritySafeCritical] get { if (readXmlValueMethod == null) { readXmlValueMethod = typeof(DataContract).GetMethod("ReadXmlValue", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return readXmlValueMethod; } } internal static MethodInfo ThrowTypeNotSerializableMethod { [SecuritySafeCritical] get { if (throwTypeNotSerializableMethod == null) { throwTypeNotSerializableMethod = typeof(DataContract).GetMethod("ThrowTypeNotSerializable", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return throwTypeNotSerializableMethod; } } internal static PropertyInfo NamespaceProperty { [SecuritySafeCritical] get { if (namespaceProperty == null) { namespaceProperty = typeof(DataContract).GetProperty("Namespace", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return namespaceProperty; } } internal static FieldInfo ContractNamespacesField { [SecuritySafeCritical] get { if (contractNamespacesField == null) { contractNamespacesField = typeof(ClassDataContract).GetField("ContractNamespaces", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return contractNamespacesField; } } internal static FieldInfo MemberNamesField { [SecuritySafeCritical] get { if (memberNamesField == null) { memberNamesField = typeof(ClassDataContract).GetField("MemberNames", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return memberNamesField; } } internal static MethodInfo ExtensionDataSetExplicitMethodInfo { [SecuritySafeCritical] get { if (extensionDataSetExplicitMethodInfo == null) { extensionDataSetExplicitMethodInfo = typeof(IExtensibleDataObject).GetMethod("set_ExtensionData"); } return extensionDataSetExplicitMethodInfo; } } internal static PropertyInfo ChildElementNamespacesProperty { [SecuritySafeCritical] get { if (childElementNamespacesProperty == null) { childElementNamespacesProperty = typeof(ClassDataContract).GetProperty("ChildElementNamespaces", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return childElementNamespacesProperty; } } internal static PropertyInfo CollectionItemNameProperty { [SecuritySafeCritical] get { if (collectionItemNameProperty == null) { collectionItemNameProperty = typeof(CollectionDataContract).GetProperty("CollectionItemName", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return collectionItemNameProperty; } } internal static PropertyInfo ChildElementNamespaceProperty { [SecuritySafeCritical] get { if (childElementNamespaceProperty == null) { childElementNamespaceProperty = typeof(CollectionDataContract).GetProperty("ChildElementNamespace", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return childElementNamespaceProperty; } } internal static MethodInfo GetDateTimeOffsetMethod { [SecuritySafeCritical] get { if (getDateTimeOffsetMethod == null) { getDateTimeOffsetMethod = typeof(DateTimeOffsetAdapter).GetMethod("GetDateTimeOffset", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return getDateTimeOffsetMethod; } } internal static MethodInfo GetDateTimeOffsetAdapterMethod { [SecuritySafeCritical] get { if (getDateTimeOffsetAdapterMethod == null) { getDateTimeOffsetAdapterMethod = typeof(DateTimeOffsetAdapter).GetMethod("GetDateTimeOffsetAdapter", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return getDateTimeOffsetAdapterMethod; } } internal static MethodInfo TraceInstructionMethod { [SecuritySafeCritical] get { if (traceInstructionMethod == null) { traceInstructionMethod = typeof(SerializationTrace).GetMethod("TraceInstruction", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return traceInstructionMethod; } } internal static MethodInfo ThrowInvalidDataContractExceptionMethod { [SecuritySafeCritical] get { if (throwInvalidDataContractExceptionMethod == null) { throwInvalidDataContractExceptionMethod = typeof(DataContract).GetMethod("ThrowInvalidDataContractException", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2] { typeof(string), typeof(Type) }, null); } return throwInvalidDataContractExceptionMethod; } } internal static PropertyInfo SerializeReadOnlyTypesProperty { [SecuritySafeCritical] get { if (serializeReadOnlyTypesProperty == null) { serializeReadOnlyTypesProperty = typeof(XmlObjectSerializerWriteContext).GetProperty("SerializeReadOnlyTypes", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return serializeReadOnlyTypesProperty; } } internal static PropertyInfo ClassSerializationExceptionMessageProperty { [SecuritySafeCritical] get { if (classSerializationExceptionMessageProperty == null) { classSerializationExceptionMessageProperty = typeof(ClassDataContract).GetProperty("SerializationExceptionMessage", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return classSerializationExceptionMessageProperty; } } internal static PropertyInfo CollectionSerializationExceptionMessageProperty { [SecuritySafeCritical] get { if (collectionSerializationExceptionMessageProperty == null) { collectionSerializationExceptionMessageProperty = typeof(CollectionDataContract).GetProperty("SerializationExceptionMessage", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return collectionSerializationExceptionMessageProperty; } } } internal delegate object XmlFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces); internal delegate object XmlFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract); internal delegate void XmlFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract); internal sealed class XmlFormatReaderGenerator { private class CriticalHelper { internal XmlFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract) { return (XmlReaderDelegator xr, XmlObjectSerializerReadContext ctx, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces) => new XmlFormatReaderInterpreter(classContract).ReadFromXml(xr, ctx, memberNames, memberNamespaces); } internal XmlFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract) { return (XmlReaderDelegator xr, XmlObjectSerializerReadContext ctx, XmlDictionaryString inm, XmlDictionaryString ins, CollectionDataContract cc) => new XmlFormatReaderInterpreter(collectionContract, isGetOnly: false).ReadCollectionFromXml(xr, ctx, inm, ins, cc); } internal XmlFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract) { return delegate(XmlReaderDelegator xr, XmlObjectSerializerReadContext ctx, XmlDictionaryString inm, XmlDictionaryString ins, CollectionDataContract cc) { new XmlFormatReaderInterpreter(collectionContract, isGetOnly: true).ReadGetOnlyCollectionFromXml(xr, ctx, inm, ins, cc); }; } } [SecurityCritical] private CriticalHelper helper; [SecurityCritical] public XmlFormatReaderGenerator() { helper = new CriticalHelper(); } [SecurityCritical] public XmlFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract) { try { if (TD.DCGenReaderStartIsEnabled()) { TD.DCGenReaderStart("Class", classContract.UnderlyingType.FullName); } return helper.GenerateClassReader(classContract); } finally { if (TD.DCGenReaderStopIsEnabled()) { TD.DCGenReaderStop(); } } } [SecurityCritical] public XmlFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract) { try { if (TD.DCGenReaderStartIsEnabled()) { TD.DCGenReaderStart("Collection", collectionContract.UnderlyingType.FullName); } return helper.GenerateCollectionReader(collectionContract); } finally { if (TD.DCGenReaderStopIsEnabled()) { TD.DCGenReaderStop(); } } } [SecurityCritical] public XmlFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract) { try { if (TD.DCGenReaderStartIsEnabled()) { TD.DCGenReaderStart("GetOnlyCollection", collectionContract.UnderlyingType.FullName); } return helper.GenerateGetOnlyCollectionReader(collectionContract); } finally { if (TD.DCGenReaderStopIsEnabled()) { TD.DCGenReaderStop(); } } } [SecuritySafeCritical] internal static object UnsafeGetUninitializedObject(int id) { return FormatterServices.GetUninitializedObject(DataContract.GetDataContractForInitialization(id).TypeForInitialization); } } internal delegate void XmlFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract dataContract); internal delegate void XmlFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract dataContract); internal sealed class XmlFormatWriterGenerator { private class CriticalHelper { internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract) { return delegate(XmlWriterDelegator xw, object obj, XmlObjectSerializerWriteContext ctx, ClassDataContract ctr) { new XmlFormatWriterInterpreter(classContract).WriteToXml(xw, obj, ctx, ctr); }; } internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract) { return delegate(XmlWriterDelegator xw, object obj, XmlObjectSerializerWriteContext ctx, CollectionDataContract ctr) { new XmlFormatWriterInterpreter(collectionContract).WriteCollectionToXml(xw, obj, ctx, ctr); }; } } [SecurityCritical] private CriticalHelper helper; [SecurityCritical] public XmlFormatWriterGenerator() { helper = new CriticalHelper(); } [SecurityCritical] internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract) { try { if (TD.DCGenWriterStartIsEnabled()) { TD.DCGenWriterStart("Class", classContract.UnderlyingType.FullName); } return helper.GenerateClassWriter(classContract); } finally { if (TD.DCGenWriterStopIsEnabled()) { TD.DCGenWriterStop(); } } } [SecurityCritical] internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract) { try { if (TD.DCGenWriterStartIsEnabled()) { TD.DCGenWriterStart("Collection", collectionContract.UnderlyingType.FullName); } return helper.GenerateCollectionWriter(collectionContract); } finally { if (TD.DCGenWriterStopIsEnabled()) { TD.DCGenWriterStop(); } } } } public abstract class XmlObjectSerializer { [SecurityCritical] private static IFormatterConverter formatterConverter; internal virtual Dictionary KnownDataContracts => null; internal static IFormatterConverter FormatterConverter { [SecuritySafeCritical] get { if (formatterConverter == null) { formatterConverter = new FormatterConverter(); } return formatterConverter; } } public abstract void WriteStartObject(XmlDictionaryWriter writer, object graph); public abstract void WriteObjectContent(XmlDictionaryWriter writer, object graph); public abstract void WriteEndObject(XmlDictionaryWriter writer); public virtual void WriteObject(Stream stream, object graph) { CheckNull(stream, "stream"); XmlDictionaryWriter xmlDictionaryWriter = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8, ownsStream: false); WriteObject(xmlDictionaryWriter, graph); xmlDictionaryWriter.Flush(); } public virtual void WriteObject(XmlWriter writer, object graph) { CheckNull(writer, "writer"); WriteObject(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph); } public virtual void WriteStartObject(XmlWriter writer, object graph) { CheckNull(writer, "writer"); WriteStartObject(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph); } public virtual void WriteObjectContent(XmlWriter writer, object graph) { CheckNull(writer, "writer"); WriteObjectContent(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph); } public virtual void WriteEndObject(XmlWriter writer) { CheckNull(writer, "writer"); WriteEndObject(XmlDictionaryWriter.CreateDictionaryWriter(writer)); } public virtual void WriteObject(XmlDictionaryWriter writer, object graph) { WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object graph) { WriteObjectHandleExceptions(writer, graph, null); } internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected O, but got Unknown try { CheckNull(writer, "writer"); if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.Trace(TraceEventType.Information, 196609, SR.GetString("WriteObject begins"), (TraceRecord)new StringTraceRecord("Type", GetTypeInfo(GetSerializeType(graph)))); InternalWriteObject(writer, graph, dataContractResolver); TraceUtility.Trace(TraceEventType.Information, 196610, SR.GetString("WriteObject ends"), (TraceRecord)new StringTraceRecord("Type", GetTypeInfo(GetSerializeType(graph)))); } else { InternalWriteObject(writer, graph, dataContractResolver); } } catch (XmlException innerException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateSerializationException(GetTypeInfoError("There was an error serializing the object {0}. {1}", GetSerializeType(graph), innerException), innerException)); } catch (FormatException innerException2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateSerializationException(GetTypeInfoError("There was an error serializing the object {0}. {1}", GetSerializeType(graph), innerException2), innerException2)); } } internal virtual void InternalWriteObject(XmlWriterDelegator writer, object graph) { WriteStartObject(writer.Writer, graph); WriteObjectContent(writer.Writer, graph); WriteEndObject(writer.Writer); } internal virtual void InternalWriteObject(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver) { InternalWriteObject(writer, graph); } internal virtual void InternalWriteStartObject(XmlWriterDelegator writer, object graph) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } internal virtual void InternalWriteObjectContent(XmlWriterDelegator writer, object graph) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } internal virtual void InternalWriteEndObject(XmlWriterDelegator writer) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } internal void WriteStartObjectHandleExceptions(XmlWriterDelegator writer, object graph) { try { CheckNull(writer, "writer"); InternalWriteStartObject(writer, graph); } catch (XmlException innerException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateSerializationException(GetTypeInfoError("There was an error writing start element of object {0}. {1}", GetSerializeType(graph), innerException), innerException)); } catch (FormatException innerException2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateSerializationException(GetTypeInfoError("There was an error writing start element of object {0}. {1}", GetSerializeType(graph), innerException2), innerException2)); } } internal void WriteObjectContentHandleExceptions(XmlWriterDelegator writer, object graph) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Expected O, but got Unknown try { CheckNull(writer, "writer"); if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.Trace(TraceEventType.Information, 196611, SR.GetString("WriteObjectContent begins"), (TraceRecord)new StringTraceRecord("Type", GetTypeInfo(GetSerializeType(graph)))); if (writer.WriteState != WriteState.Element) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateSerializationException(SR.GetString("WriteState '{0}' not valid. Caller must write start element before serializing in contentOnly mode.", writer.WriteState))); } InternalWriteObjectContent(writer, graph); TraceUtility.Trace(TraceEventType.Information, 196612, SR.GetString("WriteObjectContent ends"), (TraceRecord)new StringTraceRecord("Type", GetTypeInfo(GetSerializeType(graph)))); } else { if (writer.WriteState != WriteState.Element) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateSerializationException(SR.GetString("WriteState '{0}' not valid. Caller must write start element before serializing in contentOnly mode.", writer.WriteState))); } InternalWriteObjectContent(writer, graph); } } catch (XmlException innerException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateSerializationException(GetTypeInfoError("There was an error serializing the object {0}. {1}", GetSerializeType(graph), innerException), innerException)); } catch (FormatException innerException2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateSerializationException(GetTypeInfoError("There was an error serializing the object {0}. {1}", GetSerializeType(graph), innerException2), innerException2)); } } internal void WriteEndObjectHandleExceptions(XmlWriterDelegator writer) { try { CheckNull(writer, "writer"); InternalWriteEndObject(writer); } catch (XmlException innerException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateSerializationException(GetTypeInfoError("There was an error writing end element of object {0}. {1}", null, innerException), innerException)); } catch (FormatException innerException2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateSerializationException(GetTypeInfoError("There was an error writing end element of object {0}. {1}", null, innerException2), innerException2)); } } internal void WriteRootElement(XmlWriterDelegator writer, DataContract contract, XmlDictionaryString name, XmlDictionaryString ns, bool needsContractNsAtRoot) { if (name == null) { if (contract.HasRoot) { contract.WriteRootElement(writer, contract.TopLevelElementName, contract.TopLevelElementNamespace); } return; } contract.WriteRootElement(writer, name, ns); if (needsContractNsAtRoot) { writer.WriteNamespaceDecl(contract.Namespace); } } internal bool CheckIfNeedsContractNsAtRoot(XmlDictionaryString name, XmlDictionaryString ns, DataContract contract) { if (name == null) { return false; } if (contract.IsBuiltInDataContract || !contract.CanContainReferences || contract.IsISerializable) { return false; } string @string = XmlDictionaryString.GetString(contract.Namespace); if (string.IsNullOrEmpty(@string) || @string == XmlDictionaryString.GetString(ns)) { return false; } return true; } internal static void WriteNull(XmlWriterDelegator writer) { writer.WriteAttributeBool("i", DictionaryGlobals.XsiNilLocalName, DictionaryGlobals.SchemaInstanceNamespace, value: true); } internal static bool IsContractDeclared(DataContract contract, DataContract declaredContract) { if (contract.Name != declaredContract.Name || contract.Namespace != declaredContract.Namespace) { if (contract.Name.Value == declaredContract.Name.Value) { return contract.Namespace.Value == declaredContract.Namespace.Value; } return false; } return true; } public virtual object ReadObject(Stream stream) { CheckNull(stream, "stream"); return ReadObject(XmlDictionaryReader.CreateTextReader(stream, XmlDictionaryReaderQuotas.Max)); } public virtual object ReadObject(XmlReader reader) { CheckNull(reader, "reader"); return ReadObject(XmlDictionaryReader.CreateDictionaryReader(reader)); } public virtual object ReadObject(XmlDictionaryReader reader) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName: true); } public virtual object ReadObject(XmlReader reader, bool verifyObjectName) { CheckNull(reader, "reader"); return ReadObject(XmlDictionaryReader.CreateDictionaryReader(reader), verifyObjectName); } public abstract object ReadObject(XmlDictionaryReader reader, bool verifyObjectName); public virtual bool IsStartObject(XmlReader reader) { CheckNull(reader, "reader"); return IsStartObject(XmlDictionaryReader.CreateDictionaryReader(reader)); } public abstract bool IsStartObject(XmlDictionaryReader reader); internal virtual object InternalReadObject(XmlReaderDelegator reader, bool verifyObjectName) { return ReadObject(reader.UnderlyingReader, verifyObjectName); } internal virtual object InternalReadObject(XmlReaderDelegator reader, bool verifyObjectName, DataContractResolver dataContractResolver) { return InternalReadObject(reader, verifyObjectName); } internal virtual bool InternalIsStartObject(XmlReaderDelegator reader) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } internal object ReadObjectHandleExceptions(XmlReaderDelegator reader, bool verifyObjectName) { return ReadObjectHandleExceptions(reader, verifyObjectName, null); } internal object ReadObjectHandleExceptions(XmlReaderDelegator reader, bool verifyObjectName, DataContractResolver dataContractResolver) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Expected O, but got Unknown try { CheckNull(reader, "reader"); if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.Trace(TraceEventType.Information, 196613, SR.GetString("ReadObject begins"), (TraceRecord)new StringTraceRecord("Type", GetTypeInfo(GetDeserializeType()))); object result = InternalReadObject(reader, verifyObjectName, dataContractResolver); TraceUtility.Trace(TraceEventType.Information, 196614, SR.GetString("ReadObject ends"), (TraceRecord)new StringTraceRecord("Type", GetTypeInfo(GetDeserializeType()))); return result; } return InternalReadObject(reader, verifyObjectName, dataContractResolver); } catch (XmlException innerException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateSerializationException(GetTypeInfoError("There was an error deserializing the object {0}. {1}", GetDeserializeType(), innerException), innerException)); } catch (FormatException innerException2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateSerializationException(GetTypeInfoError("There was an error deserializing the object {0}. {1}", GetDeserializeType(), innerException2), innerException2)); } } internal bool IsStartObjectHandleExceptions(XmlReaderDelegator reader) { try { CheckNull(reader, "reader"); return InternalIsStartObject(reader); } catch (XmlException innerException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateSerializationException(GetTypeInfoError("There was an error checking start element of object {0}. {1}", GetDeserializeType(), innerException), innerException)); } catch (FormatException innerException2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateSerializationException(GetTypeInfoError("There was an error checking start element of object {0}. {1}", GetDeserializeType(), innerException2), innerException2)); } } internal bool IsRootXmlAny(XmlDictionaryString rootName, DataContract contract) { if (rootName == null) { return !contract.HasRoot; } return false; } internal bool IsStartElement(XmlReaderDelegator reader) { if (!reader.MoveToElement()) { return reader.IsStartElement(); } return true; } internal bool IsRootElement(XmlReaderDelegator reader, DataContract contract, XmlDictionaryString name, XmlDictionaryString ns) { reader.MoveToElement(); if (name != null) { return reader.IsStartElement(name, ns); } if (!contract.HasRoot) { return reader.IsStartElement(); } if (reader.IsStartElement(contract.TopLevelElementName, contract.TopLevelElementNamespace)) { return true; } ClassDataContract classDataContract = contract as ClassDataContract; if (classDataContract != null) { classDataContract = classDataContract.BaseContract; } while (classDataContract != null) { if (reader.IsStartElement(classDataContract.TopLevelElementName, classDataContract.TopLevelElementNamespace)) { return true; } classDataContract = classDataContract.BaseContract; } if (classDataContract == null) { DataContract primitiveDataContract = PrimitiveDataContract.GetPrimitiveDataContract(Globals.TypeOfObject); if (reader.IsStartElement(primitiveDataContract.TopLevelElementName, primitiveDataContract.TopLevelElementNamespace)) { return true; } } return false; } internal static void CheckNull(object obj, string name) { if (obj == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(name)); } } internal static string TryAddLineInfo(XmlReaderDelegator reader, string errorMessage) { if (reader.HasLineInfo()) { return string.Format(CultureInfo.InvariantCulture, "{0} {1}", SR.GetString("Error in line {0} position {1}.", reader.LineNumber, reader.LinePosition), errorMessage); } return errorMessage; } internal static Exception CreateSerializationExceptionWithReaderDetails(string errorMessage, XmlReaderDelegator reader) { return CreateSerializationException(TryAddLineInfo(reader, SR.GetString("{0}. Encountered '{1}' with name '{2}', namespace '{3}'.", errorMessage, reader.NodeType, reader.LocalName, reader.NamespaceURI))); } internal static SerializationException CreateSerializationException(string errorMessage) { return CreateSerializationException(errorMessage, null); } [MethodImpl(MethodImplOptions.NoInlining)] internal static SerializationException CreateSerializationException(string errorMessage, Exception innerException) { return new SerializationException(errorMessage, innerException); } private static string GetTypeInfo(Type type) { if (!(type == null)) { return DataContract.GetClrTypeFullName(type); } return string.Empty; } private static string GetTypeInfoError(string errorMessage, Type type, Exception innerException) { string text = ((type == null) ? string.Empty : SR.GetString("of type {0}", DataContract.GetClrTypeFullName(type))); string text2 = ((innerException == null) ? string.Empty : innerException.Message); return SR.GetString(errorMessage, text, text2); } internal virtual Type GetSerializeType(object graph) { return graph?.GetType(); } internal virtual Type GetDeserializeType() { return null; } } internal class XmlObjectSerializerContext { protected XmlObjectSerializer serializer; protected DataContract rootTypeDataContract; internal ScopedKnownTypes scopedKnownTypes; protected Dictionary serializerKnownDataContracts; private bool isSerializerKnownDataContractsSetExplicit; protected IList serializerKnownTypeList; [SecurityCritical] private bool demandedSerializationFormatterPermission; [SecurityCritical] private bool demandedMemberAccessPermission; private int itemCount; private int maxItemsInObjectGraph; private StreamingContext streamingContext; private bool ignoreExtensionDataObject; private DataContractResolver dataContractResolver; private KnownTypeDataContractResolver knownTypeResolver; private static MethodInfo incrementItemCountMethod; internal virtual SerializationMode Mode => SerializationMode.SharedContract; internal virtual bool IsGetOnlyCollection { get { return false; } set { } } internal static MethodInfo IncrementItemCountMethod { get { if (incrementItemCountMethod == null) { incrementItemCountMethod = typeof(XmlObjectSerializerContext).GetMethod("IncrementItemCount", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } return incrementItemCountMethod; } } internal int RemainingItemCount => maxItemsInObjectGraph - itemCount; internal bool IgnoreExtensionDataObject => ignoreExtensionDataObject; protected DataContractResolver DataContractResolver => dataContractResolver; protected KnownTypeDataContractResolver KnownTypeResolver { get { if (knownTypeResolver == null) { knownTypeResolver = new KnownTypeDataContractResolver(this); } return knownTypeResolver; } } private Dictionary SerializerKnownDataContracts { get { if (!isSerializerKnownDataContractsSetExplicit) { serializerKnownDataContracts = serializer.KnownDataContracts; isSerializerKnownDataContractsSetExplicit = true; } return serializerKnownDataContracts; } } internal XmlObjectSerializerContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject, DataContractResolver dataContractResolver) { this.serializer = serializer; itemCount = 1; this.maxItemsInObjectGraph = maxItemsInObjectGraph; this.streamingContext = streamingContext; this.ignoreExtensionDataObject = ignoreExtensionDataObject; this.dataContractResolver = dataContractResolver; } internal XmlObjectSerializerContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : this(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject, null) { } internal XmlObjectSerializerContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) : this(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(StreamingContextStates.All), serializer.IgnoreExtensionDataObject, dataContractResolver) { this.rootTypeDataContract = rootTypeDataContract; serializerKnownTypeList = serializer.knownTypeList; } internal XmlObjectSerializerContext(NetDataContractSerializer serializer) : this(serializer, serializer.MaxItemsInObjectGraph, serializer.Context, serializer.IgnoreExtensionDataObject) { } [SecuritySafeCritical] public void DemandSerializationFormatterPermission() { } [SecuritySafeCritical] public void DemandMemberAccessPermission() { } public StreamingContext GetStreamingContext() { return streamingContext; } public void IncrementItemCount(int count) { if (count > maxItemsInObjectGraph - itemCount) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Maximum number of items that can be serialized or deserialized in an object graph is '{0}'.", maxItemsInObjectGraph))); } itemCount += count; } internal DataContract GetDataContract(Type type) { return GetDataContract(type.TypeHandle, type); } internal virtual DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type) { if (IsGetOnlyCollection) { return DataContract.GetGetOnlyCollectionDataContract(DataContract.GetId(typeHandle), typeHandle, type, Mode); } return DataContract.GetDataContract(typeHandle, type, Mode); } internal virtual DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type) { if (IsGetOnlyCollection) { return DataContract.GetGetOnlyCollectionDataContractSkipValidation(typeId, typeHandle, type); } return DataContract.GetDataContractSkipValidation(typeId, typeHandle, type); } internal virtual DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle) { if (IsGetOnlyCollection) { return DataContract.GetGetOnlyCollectionDataContract(id, typeHandle, null, Mode); } return DataContract.GetDataContract(id, typeHandle, Mode); } internal virtual void CheckIfTypeSerializable(Type memberType, bool isMemberTypeSerializable) { if (!isMemberTypeSerializable) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Type '{0}' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required.", memberType))); } } internal virtual Type GetSurrogatedType(Type type) { return type; } private DataContract GetDataContractFromSerializerKnownTypes(XmlQualifiedName qname) { Dictionary dictionary = SerializerKnownDataContracts; if (dictionary == null) { return null; } if (!dictionary.TryGetValue(qname, out var value)) { return null; } return value; } internal static Dictionary GetDataContractsForKnownTypes(IList knownTypeList) { if (knownTypeList == null) { return null; } Dictionary nameToDataContractTable = new Dictionary(); Dictionary typesChecked = new Dictionary(); for (int i = 0; i < knownTypeList.Count; i++) { Type type = knownTypeList[i]; if (type == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString("One of the known types provided to the serializer via '{0}' argument was invalid because it was null. All known types specified must be non-null values.", "knownTypes"))); } DataContract.CheckAndAdd(type, typesChecked, ref nameToDataContractTable); } return nameToDataContractTable; } internal bool IsKnownType(DataContract dataContract, Dictionary knownDataContracts, Type declaredType) { bool flag = false; if (knownDataContracts != null) { scopedKnownTypes.Push(knownDataContracts); flag = true; } bool result = IsKnownType(dataContract, declaredType); if (flag) { scopedKnownTypes.Pop(); } return result; } internal bool IsKnownType(DataContract dataContract, Type declaredType) { DataContract dataContract2 = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null, declaredType); if (dataContract2 != null) { return dataContract2.UnderlyingType == dataContract.UnderlyingType; } return false; } private DataContract ResolveDataContractFromKnownTypes(XmlQualifiedName typeName) { DataContract dataContract = PrimitiveDataContract.GetPrimitiveDataContract(typeName.Name, typeName.Namespace); if (dataContract == null) { dataContract = scopedKnownTypes.GetDataContract(typeName); if (dataContract == null) { dataContract = GetDataContractFromSerializerKnownTypes(typeName); } } return dataContract; } private DataContract ResolveDataContractFromDataContractResolver(XmlQualifiedName typeName, Type declaredType) { if (TD.DCResolverResolveIsEnabled()) { TD.DCResolverResolve(typeName.Name + ":" + typeName.Namespace); } Type type = DataContractResolver.ResolveName(typeName.Name, typeName.Namespace, declaredType, KnownTypeResolver); if (type == null) { return null; } return GetDataContract(type); } internal Type ResolveNameFromKnownTypes(XmlQualifiedName typeName) { return ResolveDataContractFromKnownTypes(typeName)?.OriginalUnderlyingType; } protected DataContract ResolveDataContractFromKnownTypes(string typeName, string typeNs, DataContract memberTypeContract, Type declaredType) { XmlQualifiedName xmlQualifiedName = new XmlQualifiedName(typeName, typeNs); DataContract dataContract = ((DataContractResolver != null) ? ResolveDataContractFromDataContractResolver(xmlQualifiedName, declaredType) : ResolveDataContractFromKnownTypes(xmlQualifiedName)); if (dataContract == null) { if (memberTypeContract != null && !memberTypeContract.UnderlyingType.IsInterface && memberTypeContract.StableName == xmlQualifiedName) { dataContract = memberTypeContract; } if (dataContract == null && rootTypeDataContract != null) { dataContract = ResolveDataContractFromRootDataContract(xmlQualifiedName); } } return dataContract; } protected virtual DataContract ResolveDataContractFromRootDataContract(XmlQualifiedName typeQName) { if (rootTypeDataContract.StableName == typeQName) { return rootTypeDataContract; } CollectionDataContract collectionDataContract = rootTypeDataContract as CollectionDataContract; while (collectionDataContract != null) { DataContract dataContract = GetDataContract(GetSurrogatedType(collectionDataContract.ItemType)); if (dataContract.StableName == typeQName) { return dataContract; } collectionDataContract = dataContract as CollectionDataContract; } return null; } } internal class XmlObjectSerializerReadContext : XmlObjectSerializerContext { internal Attributes attributes; private HybridObjectCache deserializedObjects; private XmlSerializableReader xmlSerializableReader; private XmlDocument xmlDocument; private Attributes attributesInXmlData; private XmlReaderDelegator extensionDataReader; private object getOnlyCollectionValue; private bool isGetOnlyCollection; private HybridObjectCache DeserializedObjects { get { if (deserializedObjects == null) { deserializedObjects = new HybridObjectCache(); } return deserializedObjects; } } private XmlDocument Document { get { if (xmlDocument == null) { xmlDocument = new XmlDocument(); } return xmlDocument; } } internal override bool IsGetOnlyCollection { get { return isGetOnlyCollection; } set { isGetOnlyCollection = value; } } internal object GetCollectionMember() { return getOnlyCollectionValue; } internal void StoreCollectionMemberInfo(object collectionMember) { getOnlyCollectionValue = collectionMember; isGetOnlyCollection = true; } internal static void ThrowNullValueReturnedForGetOnlyCollectionException(Type type) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("The get-only collection of type '{0}' returned a null value. The input stream contains collection items which cannot be added if the instance is null. Consider initializing the collection either in the constructor of the the object or in the getter.", DataContract.GetClrTypeFullName(type)))); } internal static void ThrowArrayExceededSizeException(int arraySize, Type type) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Array length '{0}' provided by the get-only collection of type '{1}' is less than the number of array elements found in the input stream. Consider increasing the length of the array.", arraySize, DataContract.GetClrTypeFullName(type)))); } internal static XmlObjectSerializerReadContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) { if (!serializer.PreserveObjectReferences && serializer.DataContractSurrogate == null) { return new XmlObjectSerializerReadContext(serializer, rootTypeDataContract, dataContractResolver); } return new XmlObjectSerializerReadContextComplex(serializer, rootTypeDataContract, dataContractResolver); } internal static XmlObjectSerializerReadContext CreateContext(NetDataContractSerializer serializer) { return new XmlObjectSerializerReadContextComplex(serializer); } internal XmlObjectSerializerReadContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { } internal XmlObjectSerializerReadContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) : base(serializer, rootTypeDataContract, dataContractResolver) { attributes = new Attributes(); } protected XmlObjectSerializerReadContext(NetDataContractSerializer serializer) : base(serializer) { attributes = new Attributes(); } public virtual object InternalDeserialize(XmlReaderDelegator xmlReader, int id, RuntimeTypeHandle declaredTypeHandle, string name, string ns) { DataContract dataContract = GetDataContract(id, declaredTypeHandle); return InternalDeserialize(xmlReader, name, ns, Type.GetTypeFromHandle(declaredTypeHandle), ref dataContract); } internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns) { DataContract dataContract = GetDataContract(declaredType); return InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract); } internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns) { if (dataContract == null) { GetDataContract(declaredType); } return InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract); } protected bool TryHandleNullOrRef(XmlReaderDelegator reader, Type declaredType, string name, string ns, ref object retObj) { ReadAttributes(reader); if (attributes.Ref != Globals.NewObjectId) { if (isGetOnlyCollection) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("On type '{1}', attribute '{0}' points to get-only collection, which is not supported.", attributes.Ref, DataContract.GetClrTypeFullName(declaredType)))); } retObj = GetExistingObject(attributes.Ref, declaredType, name, ns); reader.Skip(); return true; } if (attributes.XsiNil) { reader.Skip(); return true; } return false; } protected object InternalDeserialize(XmlReaderDelegator reader, string name, string ns, Type declaredType, ref DataContract dataContract) { //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_024b: Expected O, but got Unknown object retObj = null; if (TryHandleNullOrRef(reader, dataContract.UnderlyingType, name, ns, ref retObj)) { return retObj; } bool flag = false; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); flag = true; } if (attributes.XsiTypeName != null) { dataContract = ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, dataContract, declaredType); if (dataContract == null) { if (base.DataContractResolver == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, SR.GetString("Element '{2}:{3}' contains data of the '{0}:{1}' data contract. The deserializer has no knowledge of any type that maps to this contract. Add the type corresponding to '{1}' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer.", attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName)))); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, SR.GetString("Element '{2}:{3}' contains data from a type that maps to the name '{0}:{1}'. The deserializer has no knowledge of any type that maps to this name. Consider changing the implementation of the ResolveName method on your DataContractResolver to return a non-null value for name '{1}' and namespace '{0}'.", attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName)))); } flag = ReplaceScopedKnownTypesTop(dataContract.KnownDataContracts, flag); } if (dataContract.IsISerializable && attributes.FactoryTypeName != null) { DataContract dataContract2 = ResolveDataContractFromKnownTypes(attributes.FactoryTypeName, attributes.FactoryTypeNamespace, dataContract, declaredType); if (dataContract2 != null) { if (!dataContract2.IsISerializable) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("For data contract '{1}', factory type '{0}' is not ISerializable.", DataContract.GetClrTypeFullName(dataContract2.UnderlyingType), DataContract.GetClrTypeFullName(dataContract.UnderlyingType)))); } dataContract = dataContract2; flag = ReplaceScopedKnownTypesTop(dataContract.KnownDataContracts, flag); } else if (DiagnosticUtility.ShouldTraceWarning) { Dictionary dictionary = new Dictionary(2); dictionary["FactoryType"] = attributes.FactoryTypeNamespace + ":" + attributes.FactoryTypeName; dictionary["ISerializableType"] = dataContract.StableName.Namespace + ":" + dataContract.StableName.Name; TraceUtility.Trace(TraceEventType.Warning, 196625, SR.GetString("Factory type not found"), (TraceRecord)new DictionaryTraceRecord((IDictionary)dictionary)); } } if (flag) { object result = ReadDataContractValue(dataContract, reader); scopedKnownTypes.Pop(); return result; } return ReadDataContractValue(dataContract, reader); } private bool ReplaceScopedKnownTypesTop(Dictionary knownDataContracts, bool knownTypesAddedInCurrentScope) { if (knownTypesAddedInCurrentScope) { scopedKnownTypes.Pop(); knownTypesAddedInCurrentScope = false; } if (knownDataContracts != null) { scopedKnownTypes.Push(knownDataContracts); knownTypesAddedInCurrentScope = true; } return knownTypesAddedInCurrentScope; } public static bool MoveToNextElement(XmlReaderDelegator xmlReader) { return xmlReader.MoveToContent() != XmlNodeType.EndElement; } public int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, ExtensionDataObject extensionData) { for (int i = memberIndex + 1; i < memberNames.Length; i++) { if (xmlReader.IsStartElement(memberNames[i], memberNamespaces[i])) { return i; } } HandleMemberNotFound(xmlReader, extensionData, memberIndex); return memberNames.Length; } public int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, int requiredIndex, ExtensionDataObject extensionData) { for (int i = memberIndex + 1; i < memberNames.Length; i++) { if (xmlReader.IsStartElement(memberNames[i], memberNamespaces[i])) { if (requiredIndex < i) { ThrowRequiredMemberMissingException(xmlReader, memberIndex, requiredIndex, memberNames); } return i; } } HandleMemberNotFound(xmlReader, extensionData, memberIndex); return memberNames.Length; } public static void ThrowRequiredMemberMissingException(XmlReaderDelegator xmlReader, int memberIndex, int requiredIndex, XmlDictionaryString[] memberNames) { StringBuilder stringBuilder = new StringBuilder(); if (requiredIndex == memberNames.Length) { requiredIndex--; } for (int i = memberIndex + 1; i <= requiredIndex; i++) { if (stringBuilder.Length != 0) { stringBuilder.Append(" | "); } stringBuilder.Append(memberNames[i].Value); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.GetString("'{0}' '{1}' from namespace '{2}' is not expected. Expecting element '{3}'.", xmlReader.NodeType, xmlReader.LocalName, xmlReader.NamespaceURI, stringBuilder.ToString())))); } protected void HandleMemberNotFound(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, int memberIndex) { xmlReader.MoveToContent(); if (xmlReader.NodeType != XmlNodeType.Element) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); } if (base.IgnoreExtensionDataObject || extensionData == null) { SkipUnknownElement(xmlReader); } else { HandleUnknownElement(xmlReader, extensionData, memberIndex); } } internal void HandleUnknownElement(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, int memberIndex) { if (extensionData.Members == null) { extensionData.Members = new List(); } extensionData.Members.Add(ReadExtensionDataMember(xmlReader, memberIndex)); } public void SkipUnknownElement(XmlReaderDelegator xmlReader) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown ReadAttributes(xmlReader); if (DiagnosticUtility.ShouldTraceVerbose) { TraceUtility.Trace(TraceEventType.Verbose, 196615, SR.GetString("Element ignored"), (TraceRecord)new StringTraceRecord("Element", xmlReader.NamespaceURI + ":" + xmlReader.LocalName)); } xmlReader.Skip(); } public string ReadIfNullOrRef(XmlReaderDelegator xmlReader, Type memberType, bool isMemberTypeSerializable) { if (attributes.Ref != Globals.NewObjectId) { CheckIfTypeSerializable(memberType, isMemberTypeSerializable); xmlReader.Skip(); return attributes.Ref; } if (attributes.XsiNil) { CheckIfTypeSerializable(memberType, isMemberTypeSerializable); xmlReader.Skip(); return null; } return Globals.NewObjectId; } internal virtual void ReadAttributes(XmlReaderDelegator xmlReader) { if (attributes == null) { attributes = new Attributes(); } attributes.Read(xmlReader); } public void ResetAttributes() { if (attributes != null) { attributes.Reset(); } } public string GetObjectId() { return attributes.Id; } internal virtual int GetArraySize() { return -1; } public void AddNewObject(object obj) { AddNewObjectWithId(attributes.Id, obj); } public void AddNewObjectWithId(string id, object obj) { if (id != Globals.NewObjectId) { DeserializedObjects.Add(id, obj); } if (extensionDataReader != null) { extensionDataReader.UnderlyingExtensionDataReader.SetDeserializedValue(obj); } } public void ReplaceDeserializedObject(string id, object oldObj, object newObj) { if (oldObj == newObj) { return; } if (id != Globals.NewObjectId) { if (DeserializedObjects.IsObjectReferenced(id)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Factory object contains a reference to self. Old object is '{0}', new object is '{1}'.", DataContract.GetClrTypeFullName(oldObj.GetType()), DataContract.GetClrTypeFullName(newObj.GetType()), id))); } DeserializedObjects.Remove(id); DeserializedObjects.Add(id, newObj); } if (extensionDataReader != null) { extensionDataReader.UnderlyingExtensionDataReader.SetDeserializedValue(newObj); } } public object GetExistingObject(string id, Type type, string name, string ns) { object obj = DeserializedObjects.GetObject(id); if (obj == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Deserialized object with reference id '{0}' not found in stream.", id))); } if (obj is IDataNode) { IDataNode dataNode = (IDataNode)obj; obj = ((dataNode.Value != null && dataNode.IsFinalValue) ? dataNode.Value : DeserializeFromExtensionData(dataNode, type, name, ns)); } return obj; } private object GetExistingObjectOrExtensionData(string id) { object @object = DeserializedObjects.GetObject(id); if (@object == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Deserialized object with reference id '{0}' not found in stream.", id))); } return @object; } public object GetRealObject(IObjectReference obj, string id) { object realObject = SurrogateDataContract.GetRealObject(obj, GetStreamingContext()); if (realObject == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("On the surrogate data contract for '{0}', GetRealObject method returned null.", DataContract.GetClrTypeFullName(obj.GetType())))); } ReplaceDeserializedObject(id, obj, realObject); return realObject; } private object DeserializeFromExtensionData(IDataNode dataNode, Type type, string name, string ns) { ExtensionDataReader extensionDataReader; if (this.extensionDataReader == null) { extensionDataReader = new ExtensionDataReader(this); this.extensionDataReader = CreateReaderDelegatorForReader(extensionDataReader); } else { extensionDataReader = this.extensionDataReader.UnderlyingExtensionDataReader; } extensionDataReader.SetDataNode(dataNode, name, ns); object result = InternalDeserialize(this.extensionDataReader, type, name, ns); dataNode.Clear(); extensionDataReader.Reset(); return result; } public static void Read(XmlReaderDelegator xmlReader) { if (!xmlReader.Read()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Unexpected end of file."))); } } internal static void ParseQualifiedName(string qname, XmlReaderDelegator xmlReader, out string name, out string ns, out string prefix) { int num = qname.IndexOf(':'); prefix = ""; if (num >= 0) { prefix = qname.Substring(0, num); } name = qname.Substring(num + 1); ns = xmlReader.LookupNamespace(prefix); } public static T[] EnsureArraySize(T[] array, int index) { if (array.Length <= index) { if (index == int.MaxValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("The maximum array length ({0}) has been exceeded while reading XML data for array of type '{1}'.", int.MaxValue, DataContract.GetClrTypeFullName(typeof(T))))); } T[] array2 = new T[(index < 1073741823) ? (index * 2) : int.MaxValue]; Array.Copy(array, 0, array2, 0, array.Length); array = array2; } return array; } public static T[] TrimArraySize(T[] array, int size) { if (size != array.Length) { T[] array2 = new T[size]; Array.Copy(array, 0, array2, 0, size); array = array2; } return array; } public void CheckEndOfArray(XmlReaderDelegator xmlReader, int arraySize, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { if (xmlReader.NodeType == XmlNodeType.EndElement) { return; } while (xmlReader.IsStartElement()) { if (xmlReader.IsStartElement(itemName, itemNamespace)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Array length '{0}' provided by Size attribute is not equal to the number of array elements '{1}' from namespace '{2}' found.", arraySize, itemName.Value, itemNamespace.Value))); } SkipUnknownElement(xmlReader); } if (xmlReader.NodeType == XmlNodeType.EndElement) { return; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.EndElement, xmlReader)); } internal object ReadIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { if (xmlSerializableReader == null) { xmlSerializableReader = new XmlSerializableReader(); } return ReadIXmlSerializable(xmlSerializableReader, xmlReader, xmlDataContract, isMemberType); } internal static object ReadRootIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { return ReadIXmlSerializable(new XmlSerializableReader(), xmlReader, xmlDataContract, isMemberType); } internal static object ReadIXmlSerializable(XmlSerializableReader xmlSerializableReader, XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { object obj = null; xmlSerializableReader.BeginRead(xmlReader); if (isMemberType && !xmlDataContract.HasRoot) { xmlReader.Read(); xmlReader.MoveToContent(); } if (xmlDataContract.UnderlyingType == Globals.TypeOfXmlElement) { if (!xmlReader.IsStartElement()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); } obj = (XmlElement)new XmlDocument().ReadNode(xmlSerializableReader); } else if (xmlDataContract.UnderlyingType == Globals.TypeOfXmlNodeArray) { obj = XmlSerializableServices.ReadNodes(xmlSerializableReader); } else { IXmlSerializable xmlSerializable = xmlDataContract.CreateXmlSerializableDelegate(); xmlSerializable.ReadXml(xmlSerializableReader); obj = xmlSerializable; } xmlSerializableReader.EndRead(); return obj; } public SerializationInfo ReadSerializationInfo(XmlReaderDelegator xmlReader, Type type) { SerializationInfo serializationInfo = new SerializationInfo(type, XmlObjectSerializer.FormatterConverter); XmlNodeType xmlNodeType; while ((xmlNodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (xmlNodeType != XmlNodeType.Element) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); } if (xmlReader.NamespaceURI.Length != 0) { SkipUnknownElement(xmlReader); continue; } string name = XmlConvert.DecodeName(xmlReader.LocalName); IncrementItemCount(1); ReadAttributes(xmlReader); object value; if (attributes.Ref != Globals.NewObjectId) { xmlReader.Skip(); value = GetExistingObject(attributes.Ref, null, name, string.Empty); } else if (attributes.XsiNil) { xmlReader.Skip(); value = null; } else { value = InternalDeserialize(xmlReader, Globals.TypeOfObject, name, string.Empty); } serializationInfo.AddValue(name, value); } return serializationInfo; } protected virtual DataContract ResolveDataContractFromTypeName() { if (attributes.XsiTypeName != null) { return ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, null, null); } return null; } private ExtensionDataMember ReadExtensionDataMember(XmlReaderDelegator xmlReader, int memberIndex) { ExtensionDataMember extensionDataMember = new ExtensionDataMember(); extensionDataMember.Name = xmlReader.LocalName; extensionDataMember.Namespace = xmlReader.NamespaceURI; extensionDataMember.MemberIndex = memberIndex; if (xmlReader.UnderlyingExtensionDataReader != null) { extensionDataMember.Value = xmlReader.UnderlyingExtensionDataReader.GetCurrentNode(); } else { extensionDataMember.Value = ReadExtensionDataValue(xmlReader); } return extensionDataMember; } public IDataNode ReadExtensionDataValue(XmlReaderDelegator xmlReader) { ReadAttributes(xmlReader); IncrementItemCount(1); IDataNode dataNode = null; if (attributes.Ref != Globals.NewObjectId) { xmlReader.Skip(); object existingObjectOrExtensionData = GetExistingObjectOrExtensionData(attributes.Ref); object obj; if (!(existingObjectOrExtensionData is IDataNode)) { IDataNode dataNode2 = new DataNode(existingObjectOrExtensionData); obj = dataNode2; } else { obj = (IDataNode)existingObjectOrExtensionData; } dataNode = (IDataNode)obj; dataNode.Id = attributes.Ref; } else if (attributes.XsiNil) { xmlReader.Skip(); dataNode = null; } else { string dataContractName = null; string dataContractNamespace = null; if (attributes.XsiTypeName != null) { dataContractName = attributes.XsiTypeName; dataContractNamespace = attributes.XsiTypeNamespace; } if (IsReadingCollectionExtensionData(xmlReader)) { Read(xmlReader); dataNode = ReadUnknownCollectionData(xmlReader, dataContractName, dataContractNamespace); } else if (attributes.FactoryTypeName != null) { Read(xmlReader); dataNode = ReadUnknownISerializableData(xmlReader, dataContractName, dataContractNamespace); } else if (IsReadingClassExtensionData(xmlReader)) { Read(xmlReader); dataNode = ReadUnknownClassData(xmlReader, dataContractName, dataContractNamespace); } else { DataContract dataContract = ResolveDataContractFromTypeName(); if (dataContract == null) { dataNode = ReadExtensionDataValue(xmlReader, dataContractName, dataContractNamespace); } else if (dataContract is XmlDataContract) { dataNode = ReadUnknownXmlData(xmlReader, dataContractName, dataContractNamespace); } else if (dataContract.IsISerializable) { Read(xmlReader); dataNode = ReadUnknownISerializableData(xmlReader, dataContractName, dataContractNamespace); } else if (dataContract is PrimitiveDataContract) { if (attributes.Id == Globals.NewObjectId) { Read(xmlReader); xmlReader.MoveToContent(); dataNode = ReadUnknownPrimitiveData(xmlReader, dataContract.UnderlyingType, dataContractName, dataContractNamespace); xmlReader.ReadEndElement(); } else { dataNode = new DataNode(xmlReader.ReadElementContentAsAnyType(dataContract.UnderlyingType)); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); } } else if (dataContract is EnumDataContract) { dataNode = new DataNode(((EnumDataContract)dataContract).ReadEnumValue(xmlReader)); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); } else if (dataContract is ClassDataContract) { Read(xmlReader); dataNode = ReadUnknownClassData(xmlReader, dataContractName, dataContractNamespace); } else if (dataContract is CollectionDataContract) { Read(xmlReader); dataNode = ReadUnknownCollectionData(xmlReader, dataContractName, dataContractNamespace); } } } return dataNode; } protected virtual void StartReadExtensionDataValue(XmlReaderDelegator xmlReader) { } private IDataNode ReadExtensionDataValue(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { StartReadExtensionDataValue(xmlReader); if (attributes.UnrecognizedAttributesFound) { return ReadUnknownXmlData(xmlReader, dataContractName, dataContractNamespace); } IDictionary namespacesInScope = xmlReader.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml); Read(xmlReader); xmlReader.MoveToContent(); switch (xmlReader.NodeType) { case XmlNodeType.Text: return ReadPrimitiveExtensionDataValue(xmlReader, dataContractName, dataContractNamespace); case XmlNodeType.Element: if (xmlReader.NamespaceURI.StartsWith("http://schemas.datacontract.org/2004/07/", StringComparison.Ordinal)) { return ReadUnknownClassData(xmlReader, dataContractName, dataContractNamespace); } return ReadAndResolveUnknownXmlData(xmlReader, namespacesInScope, dataContractName, dataContractNamespace); case XmlNodeType.EndElement: { IDataNode dataNode = ReadUnknownPrimitiveData(xmlReader, Globals.TypeOfObject, dataContractName, dataContractNamespace); xmlReader.ReadEndElement(); dataNode.IsFinalValue = false; return dataNode; } default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); } } protected virtual IDataNode ReadPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { Type valueType = xmlReader.ValueType; if (valueType == Globals.TypeOfString) { IDataNode dataNode = new DataNode(xmlReader.ReadContentAsString()); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); dataNode.IsFinalValue = false; xmlReader.ReadEndElement(); return dataNode; } IDataNode result = ReadUnknownPrimitiveData(xmlReader, valueType, dataContractName, dataContractNamespace); xmlReader.ReadEndElement(); return result; } protected void InitializeExtensionDataNode(IDataNode dataNode, string dataContractName, string dataContractNamespace) { dataNode.DataContractName = dataContractName; dataNode.DataContractNamespace = dataContractNamespace; dataNode.ClrAssemblyName = attributes.ClrAssembly; dataNode.ClrTypeName = attributes.ClrType; AddNewObject(dataNode); dataNode.Id = attributes.Id; } private IDataNode ReadUnknownPrimitiveData(XmlReaderDelegator xmlReader, Type type, string dataContractName, string dataContractNamespace) { IDataNode dataNode = xmlReader.ReadExtensionData(type); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); return dataNode; } private ClassDataNode ReadUnknownClassData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { ClassDataNode classDataNode = new ClassDataNode(); InitializeExtensionDataNode(classDataNode, dataContractName, dataContractNamespace); int num = 0; XmlNodeType xmlNodeType; while ((xmlNodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (xmlNodeType != XmlNodeType.Element) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); } if (classDataNode.Members == null) { classDataNode.Members = new List(); } classDataNode.Members.Add(ReadExtensionDataMember(xmlReader, num++)); } xmlReader.ReadEndElement(); return classDataNode; } private CollectionDataNode ReadUnknownCollectionData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { CollectionDataNode collectionDataNode = new CollectionDataNode(); InitializeExtensionDataNode(collectionDataNode, dataContractName, dataContractNamespace); int arraySZSize = attributes.ArraySZSize; XmlNodeType xmlNodeType; while ((xmlNodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (xmlNodeType != XmlNodeType.Element) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); } if (collectionDataNode.ItemName == null) { collectionDataNode.ItemName = xmlReader.LocalName; collectionDataNode.ItemNamespace = xmlReader.NamespaceURI; } if (xmlReader.IsStartElement(collectionDataNode.ItemName, collectionDataNode.ItemNamespace)) { if (collectionDataNode.Items == null) { collectionDataNode.Items = new List(); } collectionDataNode.Items.Add(ReadExtensionDataValue(xmlReader)); } else { SkipUnknownElement(xmlReader); } } xmlReader.ReadEndElement(); if (arraySZSize != -1) { collectionDataNode.Size = arraySZSize; if (collectionDataNode.Items == null) { if (collectionDataNode.Size > 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Array size attribute is incorrect; must be between {0} and {1}.", arraySZSize, 0))); } } else if (collectionDataNode.Size != collectionDataNode.Items.Count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Array size attribute is incorrect; must be between {0} and {1}.", arraySZSize, collectionDataNode.Items.Count))); } } else if (collectionDataNode.Items != null) { collectionDataNode.Size = collectionDataNode.Items.Count; } else { collectionDataNode.Size = 0; } return collectionDataNode; } private ISerializableDataNode ReadUnknownISerializableData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { ISerializableDataNode serializableDataNode = new ISerializableDataNode(); InitializeExtensionDataNode(serializableDataNode, dataContractName, dataContractNamespace); serializableDataNode.FactoryTypeName = attributes.FactoryTypeName; serializableDataNode.FactoryTypeNamespace = attributes.FactoryTypeNamespace; XmlNodeType xmlNodeType; while ((xmlNodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (xmlNodeType != XmlNodeType.Element) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); } if (xmlReader.NamespaceURI.Length != 0) { SkipUnknownElement(xmlReader); continue; } ISerializableDataMember serializableDataMember = new ISerializableDataMember(); serializableDataMember.Name = xmlReader.LocalName; serializableDataMember.Value = ReadExtensionDataValue(xmlReader); if (serializableDataNode.Members == null) { serializableDataNode.Members = new List(); } serializableDataNode.Members.Add(serializableDataMember); } xmlReader.ReadEndElement(); return serializableDataNode; } private IDataNode ReadUnknownXmlData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { XmlDataNode xmlDataNode = new XmlDataNode(); InitializeExtensionDataNode(xmlDataNode, dataContractName, dataContractNamespace); xmlDataNode.OwnerDocument = Document; if (xmlReader.NodeType == XmlNodeType.EndElement) { return xmlDataNode; } IList list = null; IList list2 = null; if (xmlReader.MoveToContent() != XmlNodeType.Text) { while (xmlReader.MoveToNextAttribute()) { string namespaceURI = xmlReader.NamespaceURI; if (namespaceURI != "http://schemas.microsoft.com/2003/10/Serialization/" && namespaceURI != "http://www.w3.org/2001/XMLSchema-instance") { if (list == null) { list = new List(); } list.Add((XmlAttribute)Document.ReadNode(xmlReader.UnderlyingReader)); } } Read(xmlReader); } while (xmlReader.MoveToContent() != XmlNodeType.EndElement) { if (xmlReader.EOF) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Unexpected end of file."))); } if (list2 == null) { list2 = new List(); } list2.Add(Document.ReadNode(xmlReader.UnderlyingReader)); } xmlReader.ReadEndElement(); xmlDataNode.XmlAttributes = list; xmlDataNode.XmlChildNodes = list2; return xmlDataNode; } private IDataNode ReadAndResolveUnknownXmlData(XmlReaderDelegator xmlReader, IDictionary namespaces, string dataContractName, string dataContractNamespace) { bool flag = true; bool flag2 = true; bool flag3 = true; string strA = null; string text = null; IList list = new List(); IList list2 = null; if (namespaces != null) { list2 = new List(); foreach (KeyValuePair @namespace in namespaces) { list2.Add(AddNamespaceDeclaration(@namespace.Key, @namespace.Value)); } } XmlNodeType nodeType; while ((nodeType = xmlReader.NodeType) != XmlNodeType.EndElement) { if (nodeType == XmlNodeType.Element) { string namespaceURI = xmlReader.NamespaceURI; string localName = xmlReader.LocalName; if (flag) { flag = namespaceURI.Length == 0; } if (flag2) { if (text == null) { text = localName; strA = namespaceURI; } else { flag2 = string.CompareOrdinal(text, localName) == 0 && string.CompareOrdinal(strA, namespaceURI) == 0; } } } else { if (xmlReader.EOF) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Unexpected end of file."))); } if (IsContentNode(xmlReader.NodeType)) { flag3 = (flag = (flag2 = false)); } } if (attributesInXmlData == null) { attributesInXmlData = new Attributes(); } attributesInXmlData.Read(xmlReader); XmlNode xmlNode = Document.ReadNode(xmlReader.UnderlyingReader); list.Add(xmlNode); if (namespaces == null) { if (attributesInXmlData.XsiTypeName != null) { xmlNode.Attributes.Append(AddNamespaceDeclaration(attributesInXmlData.XsiTypePrefix, attributesInXmlData.XsiTypeNamespace)); } if (attributesInXmlData.FactoryTypeName != null) { xmlNode.Attributes.Append(AddNamespaceDeclaration(attributesInXmlData.FactoryTypePrefix, attributesInXmlData.FactoryTypeNamespace)); } } } xmlReader.ReadEndElement(); if (text != null && flag2) { return ReadUnknownCollectionData(CreateReaderOverChildNodes(list2, list), dataContractName, dataContractNamespace); } if (flag) { return ReadUnknownISerializableData(CreateReaderOverChildNodes(list2, list), dataContractName, dataContractNamespace); } if (flag3) { return ReadUnknownClassData(CreateReaderOverChildNodes(list2, list), dataContractName, dataContractNamespace); } XmlDataNode xmlDataNode = new XmlDataNode(); InitializeExtensionDataNode(xmlDataNode, dataContractName, dataContractNamespace); xmlDataNode.OwnerDocument = Document; xmlDataNode.XmlChildNodes = list; xmlDataNode.XmlAttributes = list2; return xmlDataNode; } private bool IsContentNode(XmlNodeType nodeType) { switch (nodeType) { case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.DocumentType: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: return false; default: return true; } } internal XmlReaderDelegator CreateReaderOverChildNodes(IList xmlAttributes, IList xmlChildNodes) { XmlNode node = CreateWrapperXmlElement(Document, xmlAttributes, xmlChildNodes, null, null, null); XmlReaderDelegator xmlReaderDelegator = CreateReaderDelegatorForReader(new XmlNodeReader(node)); xmlReaderDelegator.MoveToContent(); Read(xmlReaderDelegator); return xmlReaderDelegator; } internal static XmlNode CreateWrapperXmlElement(XmlDocument document, IList xmlAttributes, IList xmlChildNodes, string prefix, string localName, string ns) { localName = localName ?? "wrapper"; ns = ns ?? string.Empty; XmlNode xmlNode = document.CreateElement(prefix, localName, ns); if (xmlAttributes != null) { for (int i = 0; i < xmlAttributes.Count; i++) { xmlNode.Attributes.Append(xmlAttributes[i]); } } if (xmlChildNodes != null) { for (int j = 0; j < xmlChildNodes.Count; j++) { xmlNode.AppendChild(xmlChildNodes[j]); } } return xmlNode; } private XmlAttribute AddNamespaceDeclaration(string prefix, string ns) { XmlAttribute obj = ((prefix == null || prefix.Length == 0) ? Document.CreateAttribute(null, "xmlns", "http://www.w3.org/2000/xmlns/") : Document.CreateAttribute("xmlns", prefix, "http://www.w3.org/2000/xmlns/")); obj.Value = ns; return obj; } public static Exception CreateUnexpectedStateException(XmlNodeType expectedState, XmlReaderDelegator xmlReader) { return XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.GetString("Expecting state '{0}'.", expectedState), xmlReader); } protected virtual object ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) { return dataContract.ReadXmlValue(reader, this); } protected virtual XmlReaderDelegator CreateReaderDelegatorForReader(XmlReader xmlReader) { return new XmlReaderDelegator(xmlReader); } protected virtual bool IsReadingCollectionExtensionData(XmlReaderDelegator xmlReader) { return attributes.ArraySZSize != -1; } protected virtual bool IsReadingClassExtensionData(XmlReaderDelegator xmlReader) { return false; } } internal class XmlObjectSerializerReadContextComplex : XmlObjectSerializerReadContext { private sealed class TopLevelAssemblyTypeResolver { private Assembly topLevelAssembly; public TopLevelAssemblyTypeResolver(Assembly topLevelAssembly) { this.topLevelAssembly = topLevelAssembly; } public Type ResolveType(Assembly assembly, string simpleTypeName, bool ignoreCase) { if (assembly == null) { assembly = topLevelAssembly; } return assembly.GetType(simpleTypeName, throwOnError: false, ignoreCase); } } private class XmlObjectDataContractTypeInfo { private Assembly assembly; private Type type; public Assembly Assembly => assembly; public Type Type => type; public XmlObjectDataContractTypeInfo(Assembly assembly, Type type) { this.assembly = assembly; this.type = type; } } private class XmlObjectDataContractTypeKey { private string assemblyName; private string typeName; public XmlObjectDataContractTypeKey(string assemblyName, string typeName) { this.assemblyName = assemblyName; this.typeName = typeName; } public override bool Equals(object obj) { if (this == obj) { return true; } if (!(obj is XmlObjectDataContractTypeKey xmlObjectDataContractTypeKey)) { return false; } if (assemblyName != xmlObjectDataContractTypeKey.assemblyName) { return false; } if (typeName != xmlObjectDataContractTypeKey.typeName) { return false; } return true; } public override int GetHashCode() { int num = 0; if (assemblyName != null) { num = assemblyName.GetHashCode(); } if (typeName != null) { num ^= typeName.GetHashCode(); } return num; } } private static Hashtable dataContractTypeCache = new Hashtable(); private bool preserveObjectReferences; protected IDataContractSurrogate dataContractSurrogate; private SerializationMode mode; private SerializationBinder binder; private ISurrogateSelector surrogateSelector; private FormatterAssemblyStyle assemblyFormat; private Hashtable surrogateDataContracts; internal override SerializationMode Mode => mode; internal XmlObjectSerializerReadContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) : base(serializer, rootTypeDataContract, dataContractResolver) { mode = SerializationMode.SharedContract; preserveObjectReferences = serializer.PreserveObjectReferences; dataContractSurrogate = serializer.DataContractSurrogate; } internal XmlObjectSerializerReadContextComplex(NetDataContractSerializer serializer) : base(serializer) { mode = SerializationMode.SharedType; preserveObjectReferences = true; binder = serializer.Binder; surrogateSelector = serializer.SurrogateSelector; assemblyFormat = serializer.AssemblyFormat; } internal XmlObjectSerializerReadContextComplex(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { } internal override DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle) { DataContract dataContract = null; if (mode == SerializationMode.SharedType && surrogateSelector != null) { dataContract = NetDataContractSerializer.GetDataContractFromSurrogateSelector(surrogateSelector, GetStreamingContext(), typeHandle, null, ref surrogateDataContracts); } if (dataContract != null) { if (IsGetOnlyCollection && dataContract is SurrogateDataContract) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Surrogates with get-only collections are not supported. Found on type '{0}'.", DataContract.GetClrTypeFullName(dataContract.UnderlyingType)))); } return dataContract; } return base.GetDataContract(id, typeHandle); } internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type) { DataContract dataContract = null; if (mode == SerializationMode.SharedType && surrogateSelector != null) { dataContract = NetDataContractSerializer.GetDataContractFromSurrogateSelector(surrogateSelector, GetStreamingContext(), typeHandle, type, ref surrogateDataContracts); } if (dataContract != null) { if (IsGetOnlyCollection && dataContract is SurrogateDataContract) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Surrogates with get-only collections are not supported. Found on type '{0}'.", DataContract.GetClrTypeFullName(dataContract.UnderlyingType)))); } return dataContract; } return base.GetDataContract(typeHandle, type); } public override object InternalDeserialize(XmlReaderDelegator xmlReader, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, string name, string ns) { if (mode == SerializationMode.SharedContract) { if (dataContractSurrogate == null) { return base.InternalDeserialize(xmlReader, declaredTypeID, declaredTypeHandle, name, ns); } return InternalDeserializeWithSurrogate(xmlReader, Type.GetTypeFromHandle(declaredTypeHandle), null, name, ns); } return InternalDeserializeInSharedTypeMode(xmlReader, declaredTypeID, Type.GetTypeFromHandle(declaredTypeHandle), name, ns); } internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns) { if (mode == SerializationMode.SharedContract) { if (dataContractSurrogate == null) { return base.InternalDeserialize(xmlReader, declaredType, name, ns); } return InternalDeserializeWithSurrogate(xmlReader, declaredType, null, name, ns); } return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns); } internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns) { if (mode == SerializationMode.SharedContract) { if (dataContractSurrogate == null) { return base.InternalDeserialize(xmlReader, declaredType, dataContract, name, ns); } return InternalDeserializeWithSurrogate(xmlReader, declaredType, dataContract, name, ns); } return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns); } private object InternalDeserializeInSharedTypeMode(XmlReaderDelegator xmlReader, int declaredTypeID, Type declaredType, string name, string ns) { object retObj = null; if (TryHandleNullOrRef(xmlReader, declaredType, name, ns, ref retObj)) { return retObj; } string clrAssembly = attributes.ClrAssembly; string clrType = attributes.ClrType; DataContract dataContract; if (clrAssembly != null && clrType != null) { dataContract = ResolveDataContractInSharedTypeMode(clrAssembly, clrType, out var assembly, out var type); if (dataContract == null) { if (assembly == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Assembly '{0}' was not found.", clrAssembly))); } if (type == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("CLR type '{1}' in assembly '{0}' is not found.", assembly.FullName, clrType))); } } if (declaredType != null && declaredType.IsArray) { dataContract = ((declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle)); } } else { if (clrAssembly != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.GetString("Attribute was not found for CLR type '{1}' in namespace '{0}'. XML reader node is on {2}, '{4}' node in '{3}' namespace.", "http://schemas.microsoft.com/2003/10/Serialization/", "Type", xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)))); } if (clrType != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.GetString("Attribute was not found for CLR type '{1}' in namespace '{0}'. XML reader node is on {2}, '{4}' node in '{3}' namespace.", "http://schemas.microsoft.com/2003/10/Serialization/", "Assembly", xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)))); } if (declaredType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.GetString("Attribute was not found for CLR type '{1}' in namespace '{0}'. XML reader node is on {2}, '{4}' node in '{3}' namespace.", "http://schemas.microsoft.com/2003/10/Serialization/", "Type", xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName)))); } dataContract = ((declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle)); } return ReadDataContractValue(dataContract, xmlReader); } private object InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract surrogateDataContract, string name, string ns) { if (TD.DCDeserializeWithSurrogateStartIsEnabled()) { TD.DCDeserializeWithSurrogateStart(declaredType.FullName); } DataContract dataContract = surrogateDataContract ?? GetDataContract(DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, declaredType)); if (IsGetOnlyCollection && dataContract.UnderlyingType != declaredType) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Surrogates with get-only collections are not supported. Found on type '{0}'.", DataContract.GetClrTypeFullName(declaredType)))); } ReadAttributes(xmlReader); string objectId = GetObjectId(); object obj = InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract); object deserializedObject = DataContractSurrogateCaller.GetDeserializedObject(dataContractSurrogate, obj, dataContract.UnderlyingType, declaredType); ReplaceDeserializedObject(objectId, obj, deserializedObject); if (TD.DCDeserializeWithSurrogateStopIsEnabled()) { TD.DCDeserializeWithSurrogateStop(); } return deserializedObject; } private Type ResolveDataContractTypeInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly) { assembly = null; Type type = null; if (binder != null) { type = binder.BindToType(assemblyName, typeName); } if (type == null) { XmlObjectDataContractTypeKey key = new XmlObjectDataContractTypeKey(assemblyName, typeName); XmlObjectDataContractTypeInfo xmlObjectDataContractTypeInfo = (XmlObjectDataContractTypeInfo)dataContractTypeCache[key]; if (xmlObjectDataContractTypeInfo == null) { if (assemblyFormat == FormatterAssemblyStyle.Full) { if (assemblyName == "0") { assembly = Globals.TypeOfInt.Assembly; } else { assembly = Assembly.Load(assemblyName); } if (assembly != null) { type = assembly.GetType(typeName); } } else { assembly = ResolveSimpleAssemblyName(assemblyName); if (assembly != null) { try { type = assembly.GetType(typeName); } catch (TypeLoadException) { } catch (FileNotFoundException) { } catch (FileLoadException) { } catch (BadImageFormatException) { } if (type == null) { type = Type.GetType(typeName, ResolveSimpleAssemblyName, new TopLevelAssemblyTypeResolver(assembly).ResolveType, throwOnError: false); } } } if (type != null) { CheckTypeForwardedTo(assembly, type.Assembly, type); xmlObjectDataContractTypeInfo = new XmlObjectDataContractTypeInfo(assembly, type); lock (dataContractTypeCache) { if (!dataContractTypeCache.ContainsKey(key)) { dataContractTypeCache[key] = xmlObjectDataContractTypeInfo; } } } } else { assembly = xmlObjectDataContractTypeInfo.Assembly; type = xmlObjectDataContractTypeInfo.Type; } } return type; } private DataContract ResolveDataContractInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly, out Type type) { type = ResolveDataContractTypeInSharedTypeMode(assemblyName, typeName, out assembly); if (type != null) { return GetDataContract(type); } return null; } protected override DataContract ResolveDataContractFromTypeName() { if (mode == SerializationMode.SharedContract) { return base.ResolveDataContractFromTypeName(); } Assembly assembly; Type type; if (attributes.ClrAssembly != null && attributes.ClrType != null) { return ResolveDataContractInSharedTypeMode(attributes.ClrAssembly, attributes.ClrType, out assembly, out type); } return null; } [MethodImpl(MethodImplOptions.NoInlining)] [SecuritySafeCritical] [PermissionSet(SecurityAction.Demand, Unrestricted = true)] private bool CheckIfTypeSerializableForSharedTypeMode(Type memberType) { ISurrogateSelector selector; return surrogateSelector.GetSurrogate(memberType, GetStreamingContext(), out selector) != null; } internal override void CheckIfTypeSerializable(Type memberType, bool isMemberTypeSerializable) { if (mode == SerializationMode.SharedType && surrogateSelector != null && CheckIfTypeSerializableForSharedTypeMode(memberType)) { return; } if (dataContractSurrogate != null) { while (memberType.IsArray) { memberType = memberType.GetElementType(); } memberType = DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, memberType); if (!DataContract.IsTypeSerializable(memberType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Type '{0}' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required.", memberType))); } } else { base.CheckIfTypeSerializable(memberType, isMemberTypeSerializable); } } internal override Type GetSurrogatedType(Type type) { if (dataContractSurrogate == null) { return base.GetSurrogatedType(type); } type = DataContract.UnwrapNullableType(type); Type surrogatedType = DataContractSerializer.GetSurrogatedType(dataContractSurrogate, type); if (IsGetOnlyCollection && surrogatedType != type) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Surrogates with get-only collections are not supported. Found on type '{0}'.", DataContract.GetClrTypeFullName(type)))); } return surrogatedType; } internal override int GetArraySize() { if (!preserveObjectReferences) { return -1; } return attributes.ArraySZSize; } private static Assembly ResolveSimpleAssemblyName(AssemblyName assemblyName) { return ResolveSimpleAssemblyName(assemblyName.FullName); } private static Assembly ResolveSimpleAssemblyName(string assemblyName) { Assembly assembly; if (assemblyName == "0") { assembly = Globals.TypeOfInt.Assembly; } else { assembly = Assembly.LoadWithPartialName(assemblyName); if (assembly == null) { assembly = Assembly.LoadWithPartialName(new AssemblyName(assemblyName) { Version = null }.FullName); } } return assembly; } [SecuritySafeCritical] private static void CheckTypeForwardedTo(Assembly sourceAssembly, Assembly destinationAssembly, Type resolvedType) { if (sourceAssembly != destinationAssembly && !NetDataContractSerializer.UnsafeTypeForwardingEnabled) { _ = sourceAssembly.IsFullyTrusted; } } } internal class XmlObjectSerializerWriteContext : XmlObjectSerializerContext { private ObjectReferenceStack byValObjectsInScope; private XmlSerializableWriter xmlSerializableWriter; private const int depthToCheckCyclicReference = 512; protected bool preserveObjectReferences; private ObjectToIdCache serializedObjects; private bool isGetOnlyCollection; private readonly bool unsafeTypeForwardingEnabled; protected bool serializeReadOnlyTypes; protected ObjectToIdCache SerializedObjects { get { if (serializedObjects == null) { serializedObjects = new ObjectToIdCache(); } return serializedObjects; } } internal override bool IsGetOnlyCollection { get { return isGetOnlyCollection; } set { isGetOnlyCollection = value; } } internal bool SerializeReadOnlyTypes => serializeReadOnlyTypes; internal bool UnsafeTypeForwardingEnabled => unsafeTypeForwardingEnabled; internal static XmlObjectSerializerWriteContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) { if (!serializer.PreserveObjectReferences && serializer.DataContractSurrogate == null) { return new XmlObjectSerializerWriteContext(serializer, rootTypeDataContract, dataContractResolver); } return new XmlObjectSerializerWriteContextComplex(serializer, rootTypeDataContract, dataContractResolver); } internal static XmlObjectSerializerWriteContext CreateContext(NetDataContractSerializer serializer, Hashtable surrogateDataContracts) { return new XmlObjectSerializerWriteContextComplex(serializer, surrogateDataContracts); } protected XmlObjectSerializerWriteContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver resolver) : base(serializer, rootTypeDataContract, resolver) { serializeReadOnlyTypes = serializer.SerializeReadOnlyTypes; unsafeTypeForwardingEnabled = true; } protected XmlObjectSerializerWriteContext(NetDataContractSerializer serializer) : base(serializer) { unsafeTypeForwardingEnabled = NetDataContractSerializer.UnsafeTypeForwardingEnabled; } internal XmlObjectSerializerWriteContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { unsafeTypeForwardingEnabled = true; } internal void StoreIsGetOnlyCollection() { isGetOnlyCollection = true; } public void InternalSerializeReference(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) { if (!OnHandleReference(xmlWriter, obj, canContainCyclicReference: true)) { InternalSerialize(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeID, declaredTypeHandle); } OnEndHandleReference(xmlWriter, obj, canContainCyclicReference: true); } public virtual void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) { if (writeXsiType) { Type typeOfObject = Globals.TypeOfObject; SerializeWithXsiType(xmlWriter, obj, Type.GetTypeHandle(obj), null, -1, typeOfObject.TypeHandle, typeOfObject); return; } if (isDeclaredType) { DataContract dataContract = GetDataContract(declaredTypeID, declaredTypeHandle); SerializeWithoutXsiType(dataContract, xmlWriter, obj, declaredTypeHandle); return; } RuntimeTypeHandle typeHandle = Type.GetTypeHandle(obj); if (declaredTypeHandle.Equals(typeHandle)) { DataContract dataContract2 = ((declaredTypeID >= 0) ? GetDataContract(declaredTypeID, declaredTypeHandle) : GetDataContract(declaredTypeHandle, null)); SerializeWithoutXsiType(dataContract2, xmlWriter, obj, declaredTypeHandle); } else { SerializeWithXsiType(xmlWriter, obj, typeHandle, null, declaredTypeID, declaredTypeHandle, Type.GetTypeFromHandle(declaredTypeHandle)); } } internal void SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle) { if (!OnHandleIsReference(xmlWriter, dataContract, obj)) { if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle); scopedKnownTypes.Pop(); } else { WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle); } } } internal virtual void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType) { bool verifyKnownType = false; Type originalUnderlyingType = rootTypeDataContract.OriginalUnderlyingType; if (originalUnderlyingType.IsInterface && CollectionDataContract.IsCollectionInterface(originalUnderlyingType)) { if (base.DataContractResolver != null) { WriteResolvedTypeInfo(xmlWriter, graphType, originalUnderlyingType); } } else if (!originalUnderlyingType.IsArray) { verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, rootTypeDataContract); } SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, originalDeclaredTypeHandle, originalUnderlyingType); } protected virtual void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType) { bool verifyKnownType = false; DataContract dataContractSkipValidation; if (declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType)) { dataContractSkipValidation = GetDataContractSkipValidation(DataContract.GetId(objectTypeHandle), objectTypeHandle, objectType); if (OnHandleIsReference(xmlWriter, dataContractSkipValidation, obj)) { return; } dataContractSkipValidation = ((Mode != SerializationMode.SharedType || !dataContractSkipValidation.IsValidContract(Mode)) ? GetDataContract(declaredTypeHandle, declaredType) : dataContractSkipValidation.GetValidContract(Mode)); if (!WriteClrTypeInfo(xmlWriter, dataContractSkipValidation) && base.DataContractResolver != null) { if (objectType == null) { objectType = Type.GetTypeFromHandle(objectTypeHandle); } WriteResolvedTypeInfo(xmlWriter, objectType, declaredType); } } else if (declaredType.IsArray) { dataContractSkipValidation = GetDataContract(objectTypeHandle, objectType); WriteClrTypeInfo(xmlWriter, dataContractSkipValidation); dataContractSkipValidation = GetDataContract(declaredTypeHandle, declaredType); } else { dataContractSkipValidation = GetDataContract(objectTypeHandle, objectType); if (OnHandleIsReference(xmlWriter, dataContractSkipValidation, obj)) { return; } if (!WriteClrTypeInfo(xmlWriter, dataContractSkipValidation)) { DataContract declaredContract = ((declaredTypeID >= 0) ? GetDataContract(declaredTypeID, declaredTypeHandle) : GetDataContract(declaredTypeHandle, declaredType)); verifyKnownType = WriteTypeInfo(xmlWriter, dataContractSkipValidation, declaredContract); } } SerializeAndVerifyType(dataContractSkipValidation, xmlWriter, obj, verifyKnownType, declaredTypeHandle, declaredType); } internal bool OnHandleIsReference(XmlWriterDelegator xmlWriter, DataContract contract, object obj) { if (preserveObjectReferences || !contract.IsReference || isGetOnlyCollection) { return false; } bool newId = true; int id = SerializedObjects.GetId(obj, ref newId); byValObjectsInScope.EnsureSetAsIsReference(obj); if (newId) { xmlWriter.WriteAttributeString("z", DictionaryGlobals.IdLocalName, DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "i", id)); return false; } xmlWriter.WriteAttributeString("z", DictionaryGlobals.RefLocalName, DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "i", id)); return true; } protected void SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, bool verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType) { bool flag = false; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); flag = true; } if (verifyKnownType && !IsKnownType(dataContract, declaredType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Type '{0}' with data contract name '{1}:{2}' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.", DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace))); } WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle); if (flag) { scopedKnownTypes.Pop(); } } internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract) { return false; } internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName) { return false; } internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, SerializationInfo serInfo) { return false; } public virtual void WriteAnyType(XmlWriterDelegator xmlWriter, object value) { xmlWriter.WriteAnyType(value); } public virtual void WriteString(XmlWriterDelegator xmlWriter, string value) { xmlWriter.WriteString(value); } public virtual void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns) { if (value == null) { WriteNull(xmlWriter, typeof(string), isMemberTypeSerializable: true, name, ns); return; } xmlWriter.WriteStartElementPrimitive(name, ns); xmlWriter.WriteString(value); xmlWriter.WriteEndElementPrimitive(); } public virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value) { xmlWriter.WriteBase64(value); } public virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns) { if (value == null) { WriteNull(xmlWriter, typeof(byte[]), isMemberTypeSerializable: true, name, ns); return; } xmlWriter.WriteStartElementPrimitive(name, ns); xmlWriter.WriteBase64(value); xmlWriter.WriteEndElementPrimitive(); } public virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value) { xmlWriter.WriteUri(value); } public virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns) { if (value == null) { WriteNull(xmlWriter, typeof(Uri), isMemberTypeSerializable: true, name, ns); return; } xmlWriter.WriteStartElementPrimitive(name, ns); xmlWriter.WriteUri(value); xmlWriter.WriteEndElementPrimitive(); } public virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value) { xmlWriter.WriteQName(value); } public virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns) { if (value == null) { WriteNull(xmlWriter, typeof(XmlQualifiedName), isMemberTypeSerializable: true, name, ns); return; } if (ns != null && ns.Value != null && ns.Value.Length > 0) { xmlWriter.WriteStartElement("q", name, ns); } else { xmlWriter.WriteStartElement(name, ns); } xmlWriter.WriteQName(value); xmlWriter.WriteEndElement(); } internal void HandleGraphAtTopLevel(XmlWriterDelegator writer, object obj, DataContract contract) { writer.WriteXmlnsAttribute("i", DictionaryGlobals.SchemaInstanceNamespace); if (contract.IsISerializable) { writer.WriteXmlnsAttribute("x", DictionaryGlobals.SchemaNamespace); } OnHandleReference(writer, obj, canContainCyclicReference: true); } internal virtual bool OnHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (xmlWriter.depth < 512) { return false; } if (canContainCyclicReference) { if (byValObjectsInScope.Count == 0 && DiagnosticUtility.ShouldTraceWarning) { TraceUtility.Trace(TraceEventType.Warning, 196626, SR.GetString("Object with large depth")); } if (byValObjectsInScope.Contains(obj)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Object graph for type '{0}' contains cycles and cannot be serialized if references are not tracked. Consider using the DataContractAttribute with the IsReference property set to true.", DataContract.GetClrTypeFullName(obj.GetType())))); } byValObjectsInScope.Push(obj); } return false; } internal virtual void OnEndHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (xmlWriter.depth >= 512 && canContainCyclicReference) { byValObjectsInScope.Pop(obj); } } public void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable) { CheckIfTypeSerializable(memberType, isMemberTypeSerializable); WriteNull(xmlWriter); } internal void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteStartElement(name, ns); WriteNull(xmlWriter, memberType, isMemberTypeSerializable); xmlWriter.WriteEndElement(); } public void IncrementArrayCount(XmlWriterDelegator xmlWriter, Array array) { IncrementCollectionCount(xmlWriter, array.GetLength(0)); } public void IncrementCollectionCount(XmlWriterDelegator xmlWriter, ICollection collection) { IncrementCollectionCount(xmlWriter, collection.Count); } public void IncrementCollectionCountGeneric(XmlWriterDelegator xmlWriter, ICollection collection) { IncrementCollectionCount(xmlWriter, collection.Count); } private void IncrementCollectionCount(XmlWriterDelegator xmlWriter, int size) { IncrementItemCount(size); WriteArraySize(xmlWriter, size); } internal virtual void WriteArraySize(XmlWriterDelegator xmlWriter, int size) { } public static T GetDefaultValue() { return default(T); } public static T GetNullableValue(T? value) where T : struct { return value.Value; } public static void ThrowRequiredMemberMustBeEmitted(string memberName, Type type) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString("Member {0} in type {1} cannot be serialized. This exception is usually caused by trying to use a null value where a null value is not allowed. The '{0}' member is set to its default value (usually null or zero). The member's EmitDefault setting is 'false', indicating that the member should not be serialized. However, the member's IsRequired setting is 'true', indicating that it must be serialized. This conflict cannot be resolved. Consider setting '{0}' to a non-default value. Alternatively, you can change the EmitDefaultValue property on the DataMemberAttribute attribute to true, or changing the IsRequired property to false.", memberName, type.FullName))); } public static bool GetHasValue(T? value) where T : struct { return value.HasValue; } internal void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj) { if (xmlSerializableWriter == null) { xmlSerializableWriter = new XmlSerializableWriter(); } WriteIXmlSerializable(xmlWriter, obj, xmlSerializableWriter); } internal static void WriteRootIXmlSerializable(XmlWriterDelegator xmlWriter, object obj) { WriteIXmlSerializable(xmlWriter, obj, new XmlSerializableWriter()); } private static void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj, XmlSerializableWriter xmlSerializableWriter) { xmlSerializableWriter.BeginWrite(xmlWriter.Writer, obj); if (obj is IXmlSerializable xmlSerializable) { xmlSerializable.WriteXml(xmlSerializableWriter); } else if (obj is XmlElement xmlElement) { xmlElement.WriteTo(xmlSerializableWriter); } else { if (!(obj is XmlNode[] array)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Unknown XML type: '{0}'.", DataContract.GetClrTypeFullName(obj.GetType())))); } XmlNode[] array2 = array; for (int i = 0; i < array2.Length; i++) { array2[i].WriteTo(xmlSerializableWriter); } } xmlSerializableWriter.EndWrite(); } [MethodImpl(MethodImplOptions.NoInlining)] [SecuritySafeCritical] internal void GetObjectData(ISerializable obj, SerializationInfo serInfo, StreamingContext context) { obj.GetObjectData(serInfo, context); } public void WriteISerializable(XmlWriterDelegator xmlWriter, ISerializable obj) { Type type = obj.GetType(); SerializationInfo serializationInfo = new SerializationInfo(type, XmlObjectSerializer.FormatterConverter, !UnsafeTypeForwardingEnabled); GetObjectData(obj, serializationInfo, GetStreamingContext()); if (!UnsafeTypeForwardingEnabled && serializationInfo.AssemblyName == "0") { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("ISerializable AssemblyName is set to \"0\" for type '{0}'.", DataContract.GetClrTypeFullName(obj.GetType())))); } WriteSerializationInfo(xmlWriter, type, serializationInfo); } internal void WriteSerializationInfo(XmlWriterDelegator xmlWriter, Type objType, SerializationInfo serInfo) { if (DataContract.GetClrTypeFullName(objType) != serInfo.FullTypeName) { if (base.DataContractResolver != null) { if (ResolveType(serInfo.ObjectType, objType, out var typeName, out var typeNamespace)) { xmlWriter.WriteAttributeQualifiedName("z", DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, typeName, typeNamespace); } } else { DataContract.GetDefaultStableName(serInfo.FullTypeName, out var localName, out var ns); xmlWriter.WriteAttributeQualifiedName("z", DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, DataContract.GetClrTypeString(localName), DataContract.GetClrTypeString(ns)); } } WriteClrTypeInfo(xmlWriter, objType, serInfo); IncrementItemCount(serInfo.MemberCount); SerializationInfoEnumerator enumerator = serInfo.GetEnumerator(); while (enumerator.MoveNext()) { SerializationEntry current = enumerator.Current; XmlDictionaryString clrTypeString = DataContract.GetClrTypeString(DataContract.EncodeLocalName(current.Name)); xmlWriter.WriteStartElement(clrTypeString, DictionaryGlobals.EmptyString); object value = current.Value; if (value == null) { WriteNull(xmlWriter); } else { InternalSerializeReference(xmlWriter, value, isDeclaredType: false, writeXsiType: false, -1, Globals.TypeOfObject.TypeHandle); } xmlWriter.WriteEndElement(); } } public void WriteExtensionData(XmlWriterDelegator xmlWriter, ExtensionDataObject extensionData, int memberIndex) { if (base.IgnoreExtensionDataObject || extensionData == null || extensionData.Members == null) { return; } for (int i = 0; i < extensionData.Members.Count; i++) { ExtensionDataMember extensionDataMember = extensionData.Members[i]; if (extensionDataMember.MemberIndex == memberIndex) { WriteExtensionDataMember(xmlWriter, extensionDataMember); } } } private void WriteExtensionDataMember(XmlWriterDelegator xmlWriter, ExtensionDataMember member) { xmlWriter.WriteStartElement(member.Name, member.Namespace); IDataNode value = member.Value; WriteExtensionDataValue(xmlWriter, value); xmlWriter.WriteEndElement(); } internal virtual void WriteExtensionDataTypeInfo(XmlWriterDelegator xmlWriter, IDataNode dataNode) { if (dataNode.DataContractName != null) { WriteTypeInfo(xmlWriter, dataNode.DataContractName, dataNode.DataContractNamespace); } WriteClrTypeInfo(xmlWriter, dataNode.DataType, dataNode.ClrTypeName, dataNode.ClrAssemblyName); } internal void WriteExtensionDataValue(XmlWriterDelegator xmlWriter, IDataNode dataNode) { IncrementItemCount(1); if (dataNode == null) { WriteNull(xmlWriter); } else { if (dataNode.PreservesReferences && OnHandleReference(xmlWriter, (dataNode.Value == null) ? dataNode : dataNode.Value, canContainCyclicReference: true)) { return; } Type dataType = dataNode.DataType; if (dataType == Globals.TypeOfClassDataNode) { WriteExtensionClassData(xmlWriter, (ClassDataNode)dataNode); } else if (dataType == Globals.TypeOfCollectionDataNode) { WriteExtensionCollectionData(xmlWriter, (CollectionDataNode)dataNode); } else if (dataType == Globals.TypeOfXmlDataNode) { WriteExtensionXmlData(xmlWriter, (XmlDataNode)dataNode); } else if (dataType == Globals.TypeOfISerializableDataNode) { WriteExtensionISerializableData(xmlWriter, (ISerializableDataNode)dataNode); } else { WriteExtensionDataTypeInfo(xmlWriter, dataNode); if (dataType == Globals.TypeOfObject) { object value = dataNode.Value; if (value != null) { InternalSerialize(xmlWriter, value, isDeclaredType: false, writeXsiType: false, -1, value.GetType().TypeHandle); } } else { xmlWriter.WriteExtensionData(dataNode); } } if (dataNode.PreservesReferences) { OnEndHandleReference(xmlWriter, (dataNode.Value == null) ? dataNode : dataNode.Value, canContainCyclicReference: true); } } } internal bool TryWriteDeserializedExtensionData(XmlWriterDelegator xmlWriter, IDataNode dataNode) { object value = dataNode.Value; if (value == null) { return false; } Type type = ((dataNode.DataContractName == null) ? value.GetType() : Globals.TypeOfObject); InternalSerialize(xmlWriter, value, isDeclaredType: false, writeXsiType: false, -1, type.TypeHandle); return true; } private void WriteExtensionClassData(XmlWriterDelegator xmlWriter, ClassDataNode dataNode) { if (TryWriteDeserializedExtensionData(xmlWriter, dataNode)) { return; } WriteExtensionDataTypeInfo(xmlWriter, dataNode); IList members = dataNode.Members; if (members != null) { for (int i = 0; i < members.Count; i++) { WriteExtensionDataMember(xmlWriter, members[i]); } } } private void WriteExtensionCollectionData(XmlWriterDelegator xmlWriter, CollectionDataNode dataNode) { if (TryWriteDeserializedExtensionData(xmlWriter, dataNode)) { return; } WriteExtensionDataTypeInfo(xmlWriter, dataNode); WriteArraySize(xmlWriter, dataNode.Size); IList items = dataNode.Items; if (items != null) { for (int i = 0; i < items.Count; i++) { xmlWriter.WriteStartElement(dataNode.ItemName, dataNode.ItemNamespace); WriteExtensionDataValue(xmlWriter, items[i]); xmlWriter.WriteEndElement(); } } } private void WriteExtensionISerializableData(XmlWriterDelegator xmlWriter, ISerializableDataNode dataNode) { if (TryWriteDeserializedExtensionData(xmlWriter, dataNode)) { return; } WriteExtensionDataTypeInfo(xmlWriter, dataNode); if (dataNode.FactoryTypeName != null) { xmlWriter.WriteAttributeQualifiedName("z", DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, dataNode.FactoryTypeName, dataNode.FactoryTypeNamespace); } IList members = dataNode.Members; if (members != null) { for (int i = 0; i < members.Count; i++) { ISerializableDataMember serializableDataMember = members[i]; xmlWriter.WriteStartElement(serializableDataMember.Name, string.Empty); WriteExtensionDataValue(xmlWriter, serializableDataMember.Value); xmlWriter.WriteEndElement(); } } } private void WriteExtensionXmlData(XmlWriterDelegator xmlWriter, XmlDataNode dataNode) { if (TryWriteDeserializedExtensionData(xmlWriter, dataNode)) { return; } IList xmlAttributes = dataNode.XmlAttributes; if (xmlAttributes != null) { foreach (XmlAttribute item in xmlAttributes) { item.WriteTo(xmlWriter.Writer); } } WriteExtensionDataTypeInfo(xmlWriter, dataNode); IList xmlChildNodes = dataNode.XmlChildNodes; if (xmlChildNodes == null) { return; } foreach (XmlNode item2 in xmlChildNodes) { item2.WriteTo(xmlWriter.Writer); } } protected virtual void WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle) { dataContract.WriteXmlValue(xmlWriter, obj, this); } protected virtual void WriteNull(XmlWriterDelegator xmlWriter) { XmlObjectSerializer.WriteNull(xmlWriter); } private void WriteResolvedTypeInfo(XmlWriterDelegator writer, Type objectType, Type declaredType) { if (ResolveType(objectType, declaredType, out var typeName, out var typeNamespace)) { WriteTypeInfo(writer, typeName, typeNamespace); } } private bool ResolveType(Type objectType, Type declaredType, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { if (!base.DataContractResolver.TryResolveType(objectType, declaredType, base.KnownTypeResolver, out typeName, out typeNamespace)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("An object of type '{0}' which derives from DataContractResolver returned false from its TryResolveType method when attempting to resolve the name for an object of type '{1}', indicating that the resolution failed. Change the TryResolveType implementation to return true.", DataContract.GetClrTypeFullName(base.DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); } if (typeName == null) { if (typeNamespace == null) { return false; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("An object of type '{0}' which derives from DataContractResolver returned a null typeName or typeNamespace but not both from its TryResolveType method when attempting to resolve the name for an object of type '{1}'. Change the TryResolveType implementation to return non-null values, or to return null values for both typeName and typeNamespace in order to serialize as the declared type.", DataContract.GetClrTypeFullName(base.DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); } if (typeNamespace == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("An object of type '{0}' which derives from DataContractResolver returned a null typeName or typeNamespace but not both from its TryResolveType method when attempting to resolve the name for an object of type '{1}'. Change the TryResolveType implementation to return non-null values, or to return null values for both typeName and typeNamespace in order to serialize as the declared type.", DataContract.GetClrTypeFullName(base.DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); } return true; } protected virtual bool WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract) { if (!XmlObjectSerializer.IsContractDeclared(contract, declaredContract)) { if (base.DataContractResolver == null) { WriteTypeInfo(writer, contract.Name, contract.Namespace); return true; } WriteResolvedTypeInfo(writer, contract.OriginalUnderlyingType, declaredContract.OriginalUnderlyingType); return false; } return false; } protected virtual void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string dataContractNamespace) { writer.WriteAttributeQualifiedName("i", DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace); } protected virtual void WriteTypeInfo(XmlWriterDelegator writer, XmlDictionaryString dataContractName, XmlDictionaryString dataContractNamespace) { writer.WriteAttributeQualifiedName("i", DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace); } } internal class XmlObjectSerializerWriteContextComplex : XmlObjectSerializerWriteContext { protected IDataContractSurrogate dataContractSurrogate; private SerializationMode mode; private SerializationBinder binder; private ISurrogateSelector surrogateSelector; private StreamingContext streamingContext; private Hashtable surrogateDataContracts; internal override SerializationMode Mode => mode; internal XmlObjectSerializerWriteContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) : base(serializer, rootTypeDataContract, dataContractResolver) { mode = SerializationMode.SharedContract; preserveObjectReferences = serializer.PreserveObjectReferences; dataContractSurrogate = serializer.DataContractSurrogate; } internal XmlObjectSerializerWriteContextComplex(NetDataContractSerializer serializer, Hashtable surrogateDataContracts) : base(serializer) { mode = SerializationMode.SharedType; preserveObjectReferences = true; streamingContext = serializer.Context; binder = serializer.Binder; surrogateSelector = serializer.SurrogateSelector; this.surrogateDataContracts = surrogateDataContracts; } internal XmlObjectSerializerWriteContextComplex(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { } internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type) { DataContract dataContract = null; if (mode == SerializationMode.SharedType && surrogateSelector != null) { dataContract = NetDataContractSerializer.GetDataContractFromSurrogateSelector(surrogateSelector, streamingContext, typeHandle, type, ref surrogateDataContracts); } if (dataContract != null) { if (IsGetOnlyCollection && dataContract is SurrogateDataContract) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Surrogates with get-only collections are not supported. Found on type '{0}'.", DataContract.GetClrTypeFullName(dataContract.UnderlyingType)))); } return dataContract; } return base.GetDataContract(typeHandle, type); } internal override DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle) { DataContract dataContract = null; if (mode == SerializationMode.SharedType && surrogateSelector != null) { dataContract = NetDataContractSerializer.GetDataContractFromSurrogateSelector(surrogateSelector, streamingContext, typeHandle, null, ref surrogateDataContracts); } if (dataContract != null) { if (IsGetOnlyCollection && dataContract is SurrogateDataContract) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Surrogates with get-only collections are not supported. Found on type '{0}'.", DataContract.GetClrTypeFullName(dataContract.UnderlyingType)))); } return dataContract; } return base.GetDataContract(id, typeHandle); } internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type) { DataContract dataContract = null; if (mode == SerializationMode.SharedType && surrogateSelector != null) { dataContract = NetDataContractSerializer.GetDataContractFromSurrogateSelector(surrogateSelector, streamingContext, typeHandle, null, ref surrogateDataContracts); } if (dataContract != null) { if (IsGetOnlyCollection && dataContract is SurrogateDataContract) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Surrogates with get-only collections are not supported. Found on type '{0}'.", DataContract.GetClrTypeFullName(dataContract.UnderlyingType)))); } return dataContract; } return base.GetDataContractSkipValidation(typeId, typeHandle, type); } internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract) { if (mode == SerializationMode.SharedType) { NetDataContractSerializer.WriteClrTypeInfo(xmlWriter, dataContract, binder); return true; } return false; } internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName) { if (mode == SerializationMode.SharedType) { NetDataContractSerializer.WriteClrTypeInfo(xmlWriter, dataContractType, binder, clrTypeName, clrAssemblyName); return true; } return false; } internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, SerializationInfo serInfo) { if (mode == SerializationMode.SharedType) { NetDataContractSerializer.WriteClrTypeInfo(xmlWriter, dataContractType, binder, serInfo); return true; } return false; } public override void WriteAnyType(XmlWriterDelegator xmlWriter, object value) { if (!OnHandleReference(xmlWriter, value, canContainCyclicReference: false)) { xmlWriter.WriteAnyType(value); } } public override void WriteString(XmlWriterDelegator xmlWriter, string value) { if (!OnHandleReference(xmlWriter, value, canContainCyclicReference: false)) { xmlWriter.WriteString(value); } } public override void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns) { if (value == null) { WriteNull(xmlWriter, typeof(string), isMemberTypeSerializable: true, name, ns); return; } xmlWriter.WriteStartElementPrimitive(name, ns); if (!OnHandleReference(xmlWriter, value, canContainCyclicReference: false)) { xmlWriter.WriteString(value); } xmlWriter.WriteEndElementPrimitive(); } public override void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value) { if (!OnHandleReference(xmlWriter, value, canContainCyclicReference: false)) { xmlWriter.WriteBase64(value); } } public override void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns) { if (value == null) { WriteNull(xmlWriter, typeof(byte[]), isMemberTypeSerializable: true, name, ns); return; } xmlWriter.WriteStartElementPrimitive(name, ns); if (!OnHandleReference(xmlWriter, value, canContainCyclicReference: false)) { xmlWriter.WriteBase64(value); } xmlWriter.WriteEndElementPrimitive(); } public override void WriteUri(XmlWriterDelegator xmlWriter, Uri value) { if (!OnHandleReference(xmlWriter, value, canContainCyclicReference: false)) { xmlWriter.WriteUri(value); } } public override void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns) { if (value == null) { WriteNull(xmlWriter, typeof(Uri), isMemberTypeSerializable: true, name, ns); return; } xmlWriter.WriteStartElementPrimitive(name, ns); if (!OnHandleReference(xmlWriter, value, canContainCyclicReference: false)) { xmlWriter.WriteUri(value); } xmlWriter.WriteEndElementPrimitive(); } public override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value) { if (!OnHandleReference(xmlWriter, value, canContainCyclicReference: false)) { xmlWriter.WriteQName(value); } } public override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns) { if (value == null) { WriteNull(xmlWriter, typeof(XmlQualifiedName), isMemberTypeSerializable: true, name, ns); return; } if (ns != null && ns.Value != null && ns.Value.Length > 0) { xmlWriter.WriteStartElement("q", name, ns); } else { xmlWriter.WriteStartElement(name, ns); } if (!OnHandleReference(xmlWriter, value, canContainCyclicReference: false)) { xmlWriter.WriteQName(value); } xmlWriter.WriteEndElement(); } public override void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) { if (dataContractSurrogate == null) { base.InternalSerialize(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeID, declaredTypeHandle); } else { InternalSerializeWithSurrogate(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeID, declaredTypeHandle); } } internal override bool OnHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (preserveObjectReferences && !IsGetOnlyCollection) { bool newId = true; int id = base.SerializedObjects.GetId(obj, ref newId); if (newId) { xmlWriter.WriteAttributeInt("z", DictionaryGlobals.IdLocalName, DictionaryGlobals.SerializationNamespace, id); } else { xmlWriter.WriteAttributeInt("z", DictionaryGlobals.RefLocalName, DictionaryGlobals.SerializationNamespace, id); xmlWriter.WriteAttributeBool("i", DictionaryGlobals.XsiNilLocalName, DictionaryGlobals.SchemaInstanceNamespace, value: true); } return !newId; } return base.OnHandleReference(xmlWriter, obj, canContainCyclicReference); } internal override void OnEndHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (!preserveObjectReferences || IsGetOnlyCollection) { base.OnEndHandleReference(xmlWriter, obj, canContainCyclicReference); } } [MethodImpl(MethodImplOptions.NoInlining)] [SecuritySafeCritical] [PermissionSet(SecurityAction.Demand, Unrestricted = true)] private bool CheckIfTypeSerializableForSharedTypeMode(Type memberType) { ISurrogateSelector selector; return surrogateSelector.GetSurrogate(memberType, streamingContext, out selector) != null; } internal override void CheckIfTypeSerializable(Type memberType, bool isMemberTypeSerializable) { if (mode == SerializationMode.SharedType && surrogateSelector != null && CheckIfTypeSerializableForSharedTypeMode(memberType)) { return; } if (dataContractSurrogate != null) { while (memberType.IsArray) { memberType = memberType.GetElementType(); } memberType = DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, memberType); if (!DataContract.IsTypeSerializable(memberType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Type '{0}' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required.", memberType))); } } else { base.CheckIfTypeSerializable(memberType, isMemberTypeSerializable); } } internal override Type GetSurrogatedType(Type type) { if (dataContractSurrogate == null) { return base.GetSurrogatedType(type); } type = DataContract.UnwrapNullableType(type); Type surrogatedType = DataContractSerializer.GetSurrogatedType(dataContractSurrogate, type); if (IsGetOnlyCollection && surrogatedType != type) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Surrogates with get-only collections are not supported. Found on type '{0}'.", DataContract.GetClrTypeFullName(type)))); } return surrogatedType; } private void InternalSerializeWithSurrogate(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) { RuntimeTypeHandle handle = (isDeclaredType ? declaredTypeHandle : Type.GetTypeHandle(obj)); object obj2 = obj; int oldObjId = 0; Type objType = Type.GetTypeFromHandle(handle); Type surrogatedType = GetSurrogatedType(Type.GetTypeFromHandle(declaredTypeHandle)); if (TD.DCSerializeWithSurrogateStartIsEnabled()) { TD.DCSerializeWithSurrogateStart(surrogatedType.FullName); } declaredTypeHandle = surrogatedType.TypeHandle; obj = DataContractSerializer.SurrogateToDataContractType(dataContractSurrogate, obj, surrogatedType, ref objType); handle = objType.TypeHandle; if (obj2 != obj) { oldObjId = base.SerializedObjects.ReassignId(0, obj2, obj); } if (writeXsiType) { surrogatedType = Globals.TypeOfObject; SerializeWithXsiType(xmlWriter, obj, handle, objType, -1, surrogatedType.TypeHandle, surrogatedType); } else if (declaredTypeHandle.Equals(handle)) { DataContract dataContract = GetDataContract(handle, objType); SerializeWithoutXsiType(dataContract, xmlWriter, obj, declaredTypeHandle); } else { SerializeWithXsiType(xmlWriter, obj, handle, objType, -1, declaredTypeHandle, surrogatedType); } if (obj2 != obj) { base.SerializedObjects.ReassignId(oldObjId, obj, obj2); } if (TD.DCSerializeWithSurrogateStopIsEnabled()) { TD.DCSerializeWithSurrogateStop(); } } internal override void WriteArraySize(XmlWriterDelegator xmlWriter, int size) { if (preserveObjectReferences && size > -1) { xmlWriter.WriteAttributeInt("z", DictionaryGlobals.ArraySizeLocalName, DictionaryGlobals.SerializationNamespace, size); } } } internal class XmlReaderDelegator { protected XmlReader reader; protected XmlDictionaryReader dictionaryReader; protected bool isEndOfEmptyElement; internal XmlReader UnderlyingReader => reader; internal ExtensionDataReader UnderlyingExtensionDataReader => reader as ExtensionDataReader; internal int AttributeCount { get { if (!isEndOfEmptyElement) { return reader.AttributeCount; } return 0; } } internal bool IsEmptyElement => false; public XmlNodeType NodeType { get { if (!isEndOfEmptyElement) { return reader.NodeType; } return XmlNodeType.EndElement; } } internal int LineNumber { get { if (reader is IXmlLineInfo xmlLineInfo) { return xmlLineInfo.LineNumber; } return 0; } } internal int LinePosition { get { if (reader is IXmlLineInfo xmlLineInfo) { return xmlLineInfo.LinePosition; } return 0; } } internal bool Normalized { get { if (!(reader is XmlTextReader xmlTextReader)) { if (reader is IXmlTextParser xmlTextParser) { return xmlTextParser.Normalized; } return false; } return xmlTextReader.Normalization; } set { if (!(reader is XmlTextReader xmlTextReader)) { if (reader is IXmlTextParser xmlTextParser) { xmlTextParser.Normalized = value; } } else { xmlTextReader.Normalization = value; } } } internal WhitespaceHandling WhitespaceHandling { get { if (!(reader is XmlTextReader xmlTextReader)) { if (reader is IXmlTextParser xmlTextParser) { return xmlTextParser.WhitespaceHandling; } return WhitespaceHandling.None; } return xmlTextReader.WhitespaceHandling; } set { if (!(reader is XmlTextReader xmlTextReader)) { if (reader is IXmlTextParser xmlTextParser) { xmlTextParser.WhitespaceHandling = value; } } else { xmlTextReader.WhitespaceHandling = value; } } } internal string Name => reader.Name; public string LocalName => reader.LocalName; internal string NamespaceURI => reader.NamespaceURI; internal string Value => reader.Value; internal Type ValueType => reader.ValueType; internal int Depth => reader.Depth; internal bool EOF => reader.EOF; public XmlReaderDelegator(XmlReader reader) { XmlObjectSerializer.CheckNull(reader, "reader"); this.reader = reader; dictionaryReader = reader as XmlDictionaryReader; } internal string GetAttribute(string name) { if (!isEndOfEmptyElement) { return reader.GetAttribute(name); } return null; } internal string GetAttribute(string name, string namespaceUri) { if (!isEndOfEmptyElement) { return reader.GetAttribute(name, namespaceUri); } return null; } internal string GetAttribute(int i) { if (isEndOfEmptyElement) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("i", SR.GetString("Only Element nodes have attributes."))); } return reader.GetAttribute(i); } internal bool IsNamespaceURI(string ns) { if (dictionaryReader == null) { return ns == reader.NamespaceURI; } return dictionaryReader.IsNamespaceUri(ns); } internal bool IsLocalName(string localName) { if (dictionaryReader == null) { return localName == reader.LocalName; } return dictionaryReader.IsLocalName(localName); } internal bool IsNamespaceUri(XmlDictionaryString ns) { if (dictionaryReader == null) { return ns.Value == reader.NamespaceURI; } return dictionaryReader.IsNamespaceUri(ns); } internal bool IsLocalName(XmlDictionaryString localName) { if (dictionaryReader == null) { return localName.Value == reader.LocalName; } return dictionaryReader.IsLocalName(localName); } internal int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictionaryString ns) { if (dictionaryReader != null) { return dictionaryReader.IndexOfLocalName(localNames, ns); } if (reader.NamespaceURI == ns.Value) { string localName = LocalName; for (int i = 0; i < localNames.Length; i++) { if (localName == localNames[i].Value) { return i; } } } return -1; } public bool IsStartElement() { if (!isEndOfEmptyElement) { return reader.IsStartElement(); } return false; } internal bool IsStartElement(string localname, string ns) { if (!isEndOfEmptyElement) { return reader.IsStartElement(localname, ns); } return false; } public bool IsStartElement(XmlDictionaryString localname, XmlDictionaryString ns) { if (dictionaryReader == null) { if (!isEndOfEmptyElement) { return reader.IsStartElement(localname.Value, ns.Value); } return false; } if (!isEndOfEmptyElement) { return dictionaryReader.IsStartElement(localname, ns); } return false; } internal bool MoveToAttribute(string name) { if (!isEndOfEmptyElement) { return reader.MoveToAttribute(name); } return false; } internal bool MoveToAttribute(string name, string ns) { if (!isEndOfEmptyElement) { return reader.MoveToAttribute(name, ns); } return false; } internal void MoveToAttribute(int i) { if (isEndOfEmptyElement) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("i", SR.GetString("Only Element nodes have attributes."))); } reader.MoveToAttribute(i); } internal bool MoveToElement() { if (!isEndOfEmptyElement) { return reader.MoveToElement(); } return false; } internal bool MoveToFirstAttribute() { if (!isEndOfEmptyElement) { return reader.MoveToFirstAttribute(); } return false; } internal bool MoveToNextAttribute() { if (!isEndOfEmptyElement) { return reader.MoveToNextAttribute(); } return false; } internal bool Read() { reader.MoveToElement(); if (!reader.IsEmptyElement) { return reader.Read(); } if (isEndOfEmptyElement) { isEndOfEmptyElement = false; return reader.Read(); } isEndOfEmptyElement = true; return true; } internal XmlNodeType MoveToContent() { if (isEndOfEmptyElement) { return XmlNodeType.EndElement; } return reader.MoveToContent(); } internal bool ReadAttributeValue() { if (!isEndOfEmptyElement) { return reader.ReadAttributeValue(); } return false; } public void ReadEndElement() { if (isEndOfEmptyElement) { Read(); } else { reader.ReadEndElement(); } } private Exception CreateInvalidPrimitiveTypeException(Type type) { return new InvalidDataContractException(SR.GetString(type.IsInterface ? "Interface type '{0}' cannot be created. Consider replacing with a non-interface serializable type." : "Type '{0}' is not a valid serializable type.", DataContract.GetClrTypeFullName(type))); } public object ReadElementContentAsAnyType(Type valueType) { Read(); object result = ReadContentAsAnyType(valueType); ReadEndElement(); return result; } internal object ReadContentAsAnyType(Type valueType) { switch (Type.GetTypeCode(valueType)) { case TypeCode.Boolean: return ReadContentAsBoolean(); case TypeCode.Char: return ReadContentAsChar(); case TypeCode.Byte: return ReadContentAsUnsignedByte(); case TypeCode.Int16: return ReadContentAsShort(); case TypeCode.Int32: return ReadContentAsInt(); case TypeCode.Int64: return ReadContentAsLong(); case TypeCode.Single: return ReadContentAsSingle(); case TypeCode.Double: return ReadContentAsDouble(); case TypeCode.Decimal: return ReadContentAsDecimal(); case TypeCode.DateTime: return ReadContentAsDateTime(); case TypeCode.String: return ReadContentAsString(); case TypeCode.SByte: return ReadContentAsSignedByte(); case TypeCode.UInt16: return ReadContentAsUnsignedShort(); case TypeCode.UInt32: return ReadContentAsUnsignedInt(); case TypeCode.UInt64: return ReadContentAsUnsignedLong(); default: if (valueType == Globals.TypeOfByteArray) { return ReadContentAsBase64(); } if (valueType == Globals.TypeOfObject) { return new object(); } if (valueType == Globals.TypeOfTimeSpan) { return ReadContentAsTimeSpan(); } if (valueType == Globals.TypeOfGuid) { return ReadContentAsGuid(); } if (valueType == Globals.TypeOfUri) { return ReadContentAsUri(); } if (valueType == Globals.TypeOfXmlQualifiedName) { return ReadContentAsQName(); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidPrimitiveTypeException(valueType)); } } internal IDataNode ReadExtensionData(Type valueType) { switch (Type.GetTypeCode(valueType)) { case TypeCode.Boolean: return new DataNode(ReadContentAsBoolean()); case TypeCode.Char: return new DataNode(ReadContentAsChar()); case TypeCode.Byte: return new DataNode(ReadContentAsUnsignedByte()); case TypeCode.Int16: return new DataNode(ReadContentAsShort()); case TypeCode.Int32: return new DataNode(ReadContentAsInt()); case TypeCode.Int64: return new DataNode(ReadContentAsLong()); case TypeCode.Single: return new DataNode(ReadContentAsSingle()); case TypeCode.Double: return new DataNode(ReadContentAsDouble()); case TypeCode.Decimal: return new DataNode(ReadContentAsDecimal()); case TypeCode.DateTime: return new DataNode(ReadContentAsDateTime()); case TypeCode.String: return new DataNode(ReadContentAsString()); case TypeCode.SByte: return new DataNode(ReadContentAsSignedByte()); case TypeCode.UInt16: return new DataNode(ReadContentAsUnsignedShort()); case TypeCode.UInt32: return new DataNode(ReadContentAsUnsignedInt()); case TypeCode.UInt64: return new DataNode(ReadContentAsUnsignedLong()); default: if (valueType == Globals.TypeOfByteArray) { return new DataNode(ReadContentAsBase64()); } if (valueType == Globals.TypeOfObject) { return new DataNode(new object()); } if (valueType == Globals.TypeOfTimeSpan) { return new DataNode(ReadContentAsTimeSpan()); } if (valueType == Globals.TypeOfGuid) { return new DataNode(ReadContentAsGuid()); } if (valueType == Globals.TypeOfUri) { return new DataNode(ReadContentAsUri()); } if (valueType == Globals.TypeOfXmlQualifiedName) { return new DataNode(ReadContentAsQName()); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidPrimitiveTypeException(valueType)); } } private void ThrowConversionException(string value, string type) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.GetString("The value '{0}' cannot be parsed as the type '{1}'.", value, type)))); } private void ThrowNotAtElement() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Start element expected. Found {0}.", "EndElement"))); } internal virtual char ReadElementContentAsChar() { return ToChar(ReadElementContentAsInt()); } internal virtual char ReadContentAsChar() { return ToChar(ReadContentAsInt()); } private char ToChar(int value) { if (value < 0 || value > 65535) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "Char"); } return (char)value; } public string ReadElementContentAsString() { if (isEndOfEmptyElement) { ThrowNotAtElement(); } return reader.ReadElementContentAsString(); } internal string ReadContentAsString() { if (!isEndOfEmptyElement) { return reader.ReadContentAsString(); } return string.Empty; } public bool ReadElementContentAsBoolean() { if (isEndOfEmptyElement) { ThrowNotAtElement(); } return reader.ReadElementContentAsBoolean(); } internal bool ReadContentAsBoolean() { if (isEndOfEmptyElement) { ThrowConversionException(string.Empty, "Boolean"); } return reader.ReadContentAsBoolean(); } public float ReadElementContentAsFloat() { if (isEndOfEmptyElement) { ThrowNotAtElement(); } return reader.ReadElementContentAsFloat(); } internal float ReadContentAsSingle() { if (isEndOfEmptyElement) { ThrowConversionException(string.Empty, "Float"); } return reader.ReadContentAsFloat(); } public double ReadElementContentAsDouble() { if (isEndOfEmptyElement) { ThrowNotAtElement(); } return reader.ReadElementContentAsDouble(); } internal double ReadContentAsDouble() { if (isEndOfEmptyElement) { ThrowConversionException(string.Empty, "Double"); } return reader.ReadContentAsDouble(); } public decimal ReadElementContentAsDecimal() { if (isEndOfEmptyElement) { ThrowNotAtElement(); } return reader.ReadElementContentAsDecimal(); } internal decimal ReadContentAsDecimal() { if (isEndOfEmptyElement) { ThrowConversionException(string.Empty, "Decimal"); } return reader.ReadContentAsDecimal(); } internal virtual byte[] ReadElementContentAsBase64() { if (isEndOfEmptyElement) { ThrowNotAtElement(); } if (dictionaryReader == null) { return ReadContentAsBase64(reader.ReadElementContentAsString()); } return dictionaryReader.ReadElementContentAsBase64(); } internal virtual byte[] ReadContentAsBase64() { if (isEndOfEmptyElement) { return new byte[0]; } if (dictionaryReader == null) { return ReadContentAsBase64(reader.ReadContentAsString()); } return dictionaryReader.ReadContentAsBase64(); } internal byte[] ReadContentAsBase64(string str) { if (str == null) { return null; } str = str.Trim(); if (str.Length == 0) { return new byte[0]; } try { return Convert.FromBase64String(str); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "byte[]", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "byte[]", exception2)); } } internal virtual DateTime ReadElementContentAsDateTime() { if (isEndOfEmptyElement) { ThrowNotAtElement(); } return reader.ReadElementContentAsDateTime(); } internal virtual DateTime ReadContentAsDateTime() { if (isEndOfEmptyElement) { ThrowConversionException(string.Empty, "DateTime"); } return reader.ReadContentAsDateTime(); } public int ReadElementContentAsInt() { if (isEndOfEmptyElement) { ThrowNotAtElement(); } return reader.ReadElementContentAsInt(); } internal int ReadContentAsInt() { if (isEndOfEmptyElement) { ThrowConversionException(string.Empty, "Int32"); } return reader.ReadContentAsInt(); } public long ReadElementContentAsLong() { if (isEndOfEmptyElement) { ThrowNotAtElement(); } return reader.ReadElementContentAsLong(); } internal long ReadContentAsLong() { if (isEndOfEmptyElement) { ThrowConversionException(string.Empty, "Int64"); } return reader.ReadContentAsLong(); } public short ReadElementContentAsShort() { return ToShort(ReadElementContentAsInt()); } internal short ReadContentAsShort() { return ToShort(ReadContentAsInt()); } private short ToShort(int value) { if (value < -32768 || value > 32767) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "Int16"); } return (short)value; } public byte ReadElementContentAsUnsignedByte() { return ToByte(ReadElementContentAsInt()); } internal byte ReadContentAsUnsignedByte() { return ToByte(ReadContentAsInt()); } private byte ToByte(int value) { if (value < 0 || value > 255) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "Byte"); } return (byte)value; } public sbyte ReadElementContentAsSignedByte() { return ToSByte(ReadElementContentAsInt()); } internal sbyte ReadContentAsSignedByte() { return ToSByte(ReadContentAsInt()); } private sbyte ToSByte(int value) { if (value < -128 || value > 127) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "SByte"); } return (sbyte)value; } public uint ReadElementContentAsUnsignedInt() { return ToUInt32(ReadElementContentAsLong()); } internal uint ReadContentAsUnsignedInt() { return ToUInt32(ReadContentAsLong()); } private uint ToUInt32(long value) { if (value < 0 || value > uint.MaxValue) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "UInt32"); } return (uint)value; } internal virtual ulong ReadElementContentAsUnsignedLong() { if (isEndOfEmptyElement) { ThrowNotAtElement(); } string text = reader.ReadElementContentAsString(); if (text == null || text.Length == 0) { ThrowConversionException(string.Empty, "UInt64"); } return XmlConverter.ToUInt64(text); } internal virtual ulong ReadContentAsUnsignedLong() { string text = reader.ReadContentAsString(); if (text == null || text.Length == 0) { ThrowConversionException(string.Empty, "UInt64"); } return XmlConverter.ToUInt64(text); } public ushort ReadElementContentAsUnsignedShort() { return ToUInt16(ReadElementContentAsInt()); } internal ushort ReadContentAsUnsignedShort() { return ToUInt16(ReadContentAsInt()); } private ushort ToUInt16(int value) { if (value < 0 || value > 65535) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "UInt16"); } return (ushort)value; } public TimeSpan ReadElementContentAsTimeSpan() { if (isEndOfEmptyElement) { ThrowNotAtElement(); } return XmlConverter.ToTimeSpan(reader.ReadElementContentAsString()); } internal TimeSpan ReadContentAsTimeSpan() { return XmlConverter.ToTimeSpan(reader.ReadContentAsString()); } public Guid ReadElementContentAsGuid() { if (isEndOfEmptyElement) { ThrowNotAtElement(); } string text = reader.ReadElementContentAsString(); try { return Guid.Parse(text); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text, "Guid", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text, "Guid", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text, "Guid", exception3)); } } internal Guid ReadContentAsGuid() { string text = reader.ReadContentAsString(); try { return Guid.Parse(text); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text, "Guid", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text, "Guid", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text, "Guid", exception3)); } } public Uri ReadElementContentAsUri() { if (isEndOfEmptyElement) { ThrowNotAtElement(); } string text = ReadElementContentAsString(); try { return new Uri(text, UriKind.RelativeOrAbsolute); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text, "Uri", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text, "Uri", exception2)); } } internal Uri ReadContentAsUri() { string text = ReadContentAsString(); try { return new Uri(text, UriKind.RelativeOrAbsolute); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text, "Uri", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text, "Uri", exception2)); } } public XmlQualifiedName ReadElementContentAsQName() { Read(); XmlQualifiedName result = ReadContentAsQName(); ReadEndElement(); return result; } internal virtual XmlQualifiedName ReadContentAsQName() { return ParseQualifiedName(ReadContentAsString()); } private XmlQualifiedName ParseQualifiedName(string str) { string name; string ns; if (str == null || str.Length == 0) { name = (ns = string.Empty); } else { XmlObjectSerializerReadContext.ParseQualifiedName(str, this, out name, out ns, out var _); } return new XmlQualifiedName(name, ns); } private void CheckExpectedArrayLength(XmlObjectSerializerReadContext context, int arrayLength) { context.IncrementItemCount(arrayLength); } protected int GetArrayLengthQuota(XmlObjectSerializerReadContext context) { if (dictionaryReader.Quotas == null) { return context.RemainingItemCount; } return Math.Min(context.RemainingItemCount, dictionaryReader.Quotas.MaxArrayLength); } private void CheckActualArrayLength(int expectedLength, int actualLength, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { if (expectedLength != actualLength) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Array length '{0}' provided by Size attribute is not equal to the number of array elements '{1}' from namespace '{2}' found.", expectedLength, itemName.Value, itemNamespace.Value))); } } internal bool TryReadBooleanArray(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out bool[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new bool[arrayLength]; int num = 0; int num2 = 0; while ((num = dictionaryReader.ReadArray(itemName, itemNamespace, array, num2, arrayLength - num2)) > 0) { num2 += num; } CheckActualArrayLength(arrayLength, num2, itemName, itemNamespace); } else { array = BooleanArrayHelperWithDictionaryString.Instance.ReadArray(dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } internal bool TryReadDateTimeArray(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out DateTime[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new DateTime[arrayLength]; int num = 0; int num2 = 0; while ((num = dictionaryReader.ReadArray(itemName, itemNamespace, array, num2, arrayLength - num2)) > 0) { num2 += num; } CheckActualArrayLength(arrayLength, num2, itemName, itemNamespace); } else { array = DateTimeArrayHelperWithDictionaryString.Instance.ReadArray(dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } internal bool TryReadDecimalArray(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out decimal[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new decimal[arrayLength]; int num = 0; int num2 = 0; while ((num = dictionaryReader.ReadArray(itemName, itemNamespace, array, num2, arrayLength - num2)) > 0) { num2 += num; } CheckActualArrayLength(arrayLength, num2, itemName, itemNamespace); } else { array = DecimalArrayHelperWithDictionaryString.Instance.ReadArray(dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } internal bool TryReadInt32Array(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out int[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new int[arrayLength]; int num = 0; int num2 = 0; while ((num = dictionaryReader.ReadArray(itemName, itemNamespace, array, num2, arrayLength - num2)) > 0) { num2 += num; } CheckActualArrayLength(arrayLength, num2, itemName, itemNamespace); } else { array = Int32ArrayHelperWithDictionaryString.Instance.ReadArray(dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } internal bool TryReadInt64Array(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out long[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new long[arrayLength]; int num = 0; int num2 = 0; while ((num = dictionaryReader.ReadArray(itemName, itemNamespace, array, num2, arrayLength - num2)) > 0) { num2 += num; } CheckActualArrayLength(arrayLength, num2, itemName, itemNamespace); } else { array = Int64ArrayHelperWithDictionaryString.Instance.ReadArray(dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } internal bool TryReadSingleArray(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out float[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new float[arrayLength]; int num = 0; int num2 = 0; while ((num = dictionaryReader.ReadArray(itemName, itemNamespace, array, num2, arrayLength - num2)) > 0) { num2 += num; } CheckActualArrayLength(arrayLength, num2, itemName, itemNamespace); } else { array = SingleArrayHelperWithDictionaryString.Instance.ReadArray(dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } internal bool TryReadDoubleArray(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out double[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new double[arrayLength]; int num = 0; int num2 = 0; while ((num = dictionaryReader.ReadArray(itemName, itemNamespace, array, num2, arrayLength - num2)) > 0) { num2 += num; } CheckActualArrayLength(arrayLength, num2, itemName, itemNamespace); } else { array = DoubleArrayHelperWithDictionaryString.Instance.ReadArray(dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } internal IDictionary GetNamespacesInScope(XmlNamespaceScope scope) { if (!(reader is IXmlNamespaceResolver)) { return null; } return ((IXmlNamespaceResolver)reader).GetNamespacesInScope(scope); } internal bool HasLineInfo() { if (reader is IXmlLineInfo xmlLineInfo) { return xmlLineInfo.HasLineInfo(); } return false; } internal string LookupNamespace(string prefix) { return reader.LookupNamespace(prefix); } internal void Skip() { reader.Skip(); isEndOfEmptyElement = false; } } internal class XmlSerializableReader : XmlReader, IXmlLineInfo, IXmlTextParser { private XmlReaderDelegator xmlReader; private int startDepth; private bool isRootEmptyElement; private XmlReader innerReader; private XmlReader InnerReader => innerReader; public override XmlReaderSettings Settings => InnerReader.Settings; public override XmlNodeType NodeType => InnerReader.NodeType; public override string Name => InnerReader.Name; public override string LocalName => InnerReader.LocalName; public override string NamespaceURI => InnerReader.NamespaceURI; public override string Prefix => InnerReader.Prefix; public override bool HasValue => InnerReader.HasValue; public override string Value => InnerReader.Value; public override int Depth => InnerReader.Depth; public override string BaseURI => InnerReader.BaseURI; public override bool IsEmptyElement => InnerReader.IsEmptyElement; public override bool IsDefault => InnerReader.IsDefault; public override char QuoteChar => InnerReader.QuoteChar; public override XmlSpace XmlSpace => InnerReader.XmlSpace; public override string XmlLang => InnerReader.XmlLang; public override IXmlSchemaInfo SchemaInfo => InnerReader.SchemaInfo; public override Type ValueType => InnerReader.ValueType; public override int AttributeCount => InnerReader.AttributeCount; public override string this[int i] => InnerReader[i]; public override string this[string name] => InnerReader[name]; public override string this[string name, string namespaceURI] => InnerReader[name, namespaceURI]; public override bool EOF => InnerReader.EOF; public override ReadState ReadState => InnerReader.ReadState; public override XmlNameTable NameTable => InnerReader.NameTable; public override bool CanResolveEntity => InnerReader.CanResolveEntity; public override bool CanReadBinaryContent => InnerReader.CanReadBinaryContent; public override bool CanReadValueChunk => InnerReader.CanReadValueChunk; public override bool HasAttributes => InnerReader.HasAttributes; bool IXmlTextParser.Normalized { get { if (InnerReader is IXmlTextParser xmlTextParser) { return xmlTextParser.Normalized; } return xmlReader.Normalized; } set { if (!(InnerReader is IXmlTextParser xmlTextParser)) { xmlReader.Normalized = value; } else { xmlTextParser.Normalized = value; } } } WhitespaceHandling IXmlTextParser.WhitespaceHandling { get { if (InnerReader is IXmlTextParser xmlTextParser) { return xmlTextParser.WhitespaceHandling; } return xmlReader.WhitespaceHandling; } set { if (!(InnerReader is IXmlTextParser xmlTextParser)) { xmlReader.WhitespaceHandling = value; } else { xmlTextParser.WhitespaceHandling = value; } } } int IXmlLineInfo.LineNumber { get { if (InnerReader is IXmlLineInfo xmlLineInfo) { return xmlLineInfo.LineNumber; } return xmlReader.LineNumber; } } int IXmlLineInfo.LinePosition { get { if (InnerReader is IXmlLineInfo xmlLineInfo) { return xmlLineInfo.LinePosition; } return xmlReader.LinePosition; } } internal void BeginRead(XmlReaderDelegator xmlReader) { if (xmlReader.NodeType != XmlNodeType.Element) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializerReadContext.CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); } this.xmlReader = xmlReader; startDepth = xmlReader.Depth; innerReader = xmlReader.UnderlyingReader; isRootEmptyElement = InnerReader.IsEmptyElement; } internal void EndRead() { if (isRootEmptyElement) { xmlReader.Read(); return; } if (xmlReader.IsStartElement() && xmlReader.Depth == startDepth) { xmlReader.Read(); } while (xmlReader.Depth > startDepth) { if (!xmlReader.Read()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializerReadContext.CreateUnexpectedStateException(XmlNodeType.EndElement, xmlReader)); } } } public override bool Read() { XmlReader xmlReader = InnerReader; if (xmlReader.Depth == startDepth && (xmlReader.NodeType == XmlNodeType.EndElement || (xmlReader.NodeType == XmlNodeType.Element && xmlReader.IsEmptyElement))) { return false; } return xmlReader.Read(); } public override void Close() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("This method cannot be called from IXmlSerializable implementations."))); } public override string GetAttribute(string name) { return InnerReader.GetAttribute(name); } public override string GetAttribute(string name, string namespaceURI) { return InnerReader.GetAttribute(name, namespaceURI); } public override string GetAttribute(int i) { return InnerReader.GetAttribute(i); } public override bool MoveToAttribute(string name) { return InnerReader.MoveToAttribute(name); } public override bool MoveToAttribute(string name, string ns) { return InnerReader.MoveToAttribute(name, ns); } public override void MoveToAttribute(int i) { InnerReader.MoveToAttribute(i); } public override bool MoveToFirstAttribute() { return InnerReader.MoveToFirstAttribute(); } public override bool MoveToNextAttribute() { return InnerReader.MoveToNextAttribute(); } public override bool MoveToElement() { return InnerReader.MoveToElement(); } public override string LookupNamespace(string prefix) { return InnerReader.LookupNamespace(prefix); } public override bool ReadAttributeValue() { return InnerReader.ReadAttributeValue(); } public override void ResolveEntity() { InnerReader.ResolveEntity(); } public override bool IsStartElement() { return InnerReader.IsStartElement(); } public override bool IsStartElement(string name) { return InnerReader.IsStartElement(name); } public override bool IsStartElement(string localname, string ns) { return InnerReader.IsStartElement(localname, ns); } public override XmlNodeType MoveToContent() { return InnerReader.MoveToContent(); } public override object ReadContentAsObject() { return InnerReader.ReadContentAsObject(); } public override bool ReadContentAsBoolean() { return InnerReader.ReadContentAsBoolean(); } public override DateTime ReadContentAsDateTime() { return InnerReader.ReadContentAsDateTime(); } public override double ReadContentAsDouble() { return InnerReader.ReadContentAsDouble(); } public override int ReadContentAsInt() { return InnerReader.ReadContentAsInt(); } public override long ReadContentAsLong() { return InnerReader.ReadContentAsLong(); } public override string ReadContentAsString() { return InnerReader.ReadContentAsString(); } public override object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) { return InnerReader.ReadContentAs(returnType, namespaceResolver); } public override int ReadContentAsBase64(byte[] buffer, int index, int count) { return InnerReader.ReadContentAsBase64(buffer, index, count); } public override int ReadContentAsBinHex(byte[] buffer, int index, int count) { return InnerReader.ReadContentAsBinHex(buffer, index, count); } public override int ReadValueChunk(char[] buffer, int index, int count) { return InnerReader.ReadValueChunk(buffer, index, count); } public override string ReadString() { return InnerReader.ReadString(); } bool IXmlLineInfo.HasLineInfo() { if (InnerReader is IXmlLineInfo xmlLineInfo) { return xmlLineInfo.HasLineInfo(); } return xmlReader.HasLineInfo(); } } public static class XmlSerializableServices { internal static readonly string ReadNodesMethodName = "ReadNodes"; internal static string WriteNodesMethodName = "WriteNodes"; internal static string AddDefaultSchemaMethodName = "AddDefaultSchema"; public static XmlNode[] ReadNodes(XmlReader xmlReader) { if (xmlReader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("xmlReader"); } XmlDocument xmlDocument = new XmlDocument(); List list = new List(); if (xmlReader.MoveToFirstAttribute()) { do { if (IsValidAttribute(xmlReader)) { XmlNode xmlNode = xmlDocument.ReadNode(xmlReader); if (xmlNode == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Unexpected end of file."))); } list.Add(xmlNode); } } while (xmlReader.MoveToNextAttribute()); } xmlReader.MoveToElement(); if (!xmlReader.IsEmptyElement) { int depth = xmlReader.Depth; xmlReader.Read(); while (xmlReader.Depth > depth && xmlReader.NodeType != XmlNodeType.EndElement) { XmlNode xmlNode2 = xmlDocument.ReadNode(xmlReader); if (xmlNode2 == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Unexpected end of file."))); } list.Add(xmlNode2); } } return list.ToArray(); } private static bool IsValidAttribute(XmlReader xmlReader) { if (xmlReader.NamespaceURI != "http://schemas.microsoft.com/2003/10/Serialization/" && xmlReader.NamespaceURI != "http://www.w3.org/2001/XMLSchema-instance" && xmlReader.Prefix != "xmlns") { return xmlReader.LocalName != "xmlns"; } return false; } public static void WriteNodes(XmlWriter xmlWriter, XmlNode[] nodes) { if (xmlWriter == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("xmlWriter"); } if (nodes == null) { return; } for (int i = 0; i < nodes.Length; i++) { if (nodes[i] != null) { nodes[i].WriteTo(xmlWriter); } } } public static void AddDefaultSchema(XmlSchemaSet schemas, XmlQualifiedName typeQName) { if (schemas == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("schemas"); } if (typeQName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("typeQName"); } SchemaExporter.AddDefaultXmlType(schemas, typeQName.Name, typeQName.Namespace); } } internal class XmlSerializableWriter : XmlWriter { private XmlWriter xmlWriter; private int depth; private object obj; public override WriteState WriteState => xmlWriter.WriteState; public override XmlSpace XmlSpace => xmlWriter.XmlSpace; public override string XmlLang => xmlWriter.XmlLang; internal void BeginWrite(XmlWriter xmlWriter, object obj) { depth = 0; this.xmlWriter = xmlWriter; this.obj = obj; } internal void EndWrite() { if (depth != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("IXmlSerializable.WriteXml method of type '{0}' did not close all open tags. Verify that the IXmlSerializable implementation is correct.", (obj == null) ? string.Empty : DataContract.GetClrTypeFullName(obj.GetType())))); } obj = null; } public override void WriteStartDocument() { if (WriteState == WriteState.Start) { xmlWriter.WriteStartDocument(); } } public override void WriteEndDocument() { xmlWriter.WriteEndDocument(); } public override void WriteStartDocument(bool standalone) { if (WriteState == WriteState.Start) { xmlWriter.WriteStartDocument(standalone); } } public override void WriteDocType(string name, string pubid, string sysid, string subset) { } public override void WriteStartElement(string prefix, string localName, string ns) { xmlWriter.WriteStartElement(prefix, localName, ns); depth++; } public override void WriteEndElement() { if (depth == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("IXmlSerializable.WriteXml method of type '{0}' attempted to close too many tags. Verify that the IXmlSerializable implementation is correct.", (obj == null) ? string.Empty : DataContract.GetClrTypeFullName(obj.GetType())))); } xmlWriter.WriteEndElement(); depth--; } public override void WriteFullEndElement() { if (depth == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("IXmlSerializable.WriteXml method of type '{0}' attempted to close too many tags. Verify that the IXmlSerializable implementation is correct.", (obj == null) ? string.Empty : DataContract.GetClrTypeFullName(obj.GetType())))); } xmlWriter.WriteFullEndElement(); depth--; } public override void Close() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("This method cannot be called from IXmlSerializable implementations."))); } public override void WriteStartAttribute(string prefix, string localName, string ns) { xmlWriter.WriteStartAttribute(prefix, localName, ns); } public override void WriteEndAttribute() { xmlWriter.WriteEndAttribute(); } public override void WriteCData(string text) { xmlWriter.WriteCData(text); } public override void WriteComment(string text) { xmlWriter.WriteComment(text); } public override void WriteProcessingInstruction(string name, string text) { xmlWriter.WriteProcessingInstruction(name, text); } public override void WriteEntityRef(string name) { xmlWriter.WriteEntityRef(name); } public override void WriteCharEntity(char ch) { xmlWriter.WriteCharEntity(ch); } public override void WriteWhitespace(string ws) { xmlWriter.WriteWhitespace(ws); } public override void WriteString(string text) { xmlWriter.WriteString(text); } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { xmlWriter.WriteSurrogateCharEntity(lowChar, highChar); } public override void WriteChars(char[] buffer, int index, int count) { xmlWriter.WriteChars(buffer, index, count); } public override void WriteRaw(char[] buffer, int index, int count) { xmlWriter.WriteRaw(buffer, index, count); } public override void WriteRaw(string data) { xmlWriter.WriteRaw(data); } public override void WriteBase64(byte[] buffer, int index, int count) { xmlWriter.WriteBase64(buffer, index, count); } public override void WriteBinHex(byte[] buffer, int index, int count) { xmlWriter.WriteBinHex(buffer, index, count); } public override void Flush() { xmlWriter.Flush(); } public override void WriteName(string name) { xmlWriter.WriteName(name); } public override void WriteQualifiedName(string localName, string ns) { xmlWriter.WriteQualifiedName(localName, ns); } public override string LookupPrefix(string ns) { return xmlWriter.LookupPrefix(ns); } public override void WriteNmToken(string name) { xmlWriter.WriteNmToken(name); } } internal class XmlWriterDelegator { protected XmlWriter writer; protected XmlDictionaryWriter dictionaryWriter; internal int depth; private int prefixes; private const int CharChunkSize = 76; private const int ByteChunkSize = 57; internal XmlWriter Writer => writer; internal WriteState WriteState => writer.WriteState; internal string XmlLang => writer.XmlLang; internal XmlSpace XmlSpace => writer.XmlSpace; public XmlWriterDelegator(XmlWriter writer) { XmlObjectSerializer.CheckNull(writer, "writer"); this.writer = writer; dictionaryWriter = writer as XmlDictionaryWriter; } internal void Flush() { writer.Flush(); } internal string LookupPrefix(string ns) { return writer.LookupPrefix(ns); } private void WriteEndAttribute() { writer.WriteEndAttribute(); } public void WriteEndElement() { writer.WriteEndElement(); depth--; } internal void WriteRaw(char[] buffer, int index, int count) { writer.WriteRaw(buffer, index, count); } internal void WriteRaw(string data) { writer.WriteRaw(data); } internal void WriteXmlnsAttribute(XmlDictionaryString ns) { if (dictionaryWriter != null) { if (ns != null) { dictionaryWriter.WriteXmlnsAttribute(null, ns); } } else { WriteXmlnsAttribute(ns.Value); } } internal void WriteXmlnsAttribute(string ns) { if (ns == null) { return; } if (ns.Length == 0) { writer.WriteAttributeString("xmlns", string.Empty, null, ns); return; } if (dictionaryWriter != null) { dictionaryWriter.WriteXmlnsAttribute(null, ns); return; } string text = writer.LookupPrefix(ns); if (text == null) { text = string.Format(CultureInfo.InvariantCulture, "d{0}p{1}", depth, prefixes); prefixes++; writer.WriteAttributeString("xmlns", text, null, ns); } } internal void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) { if (dictionaryWriter != null) { dictionaryWriter.WriteXmlnsAttribute(prefix, ns); } else { writer.WriteAttributeString("xmlns", prefix, null, ns.Value); } } private void WriteStartAttribute(string prefix, string localName, string ns) { writer.WriteStartAttribute(prefix, localName, ns); } private void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri) { if (dictionaryWriter != null) { dictionaryWriter.WriteStartAttribute(prefix, localName, namespaceUri); } else { writer.WriteStartAttribute(prefix, localName?.Value, namespaceUri?.Value); } } internal void WriteAttributeString(string prefix, string localName, string ns, string value) { WriteStartAttribute(prefix, localName, ns); WriteAttributeStringValue(value); WriteEndAttribute(); } internal void WriteAttributeString(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, string value) { WriteStartAttribute(prefix, attrName, attrNs); WriteAttributeStringValue(value); WriteEndAttribute(); } private void WriteAttributeStringValue(string value) { writer.WriteValue(value); } internal void WriteAttributeString(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, XmlDictionaryString value) { WriteStartAttribute(prefix, attrName, attrNs); WriteAttributeStringValue(value); WriteEndAttribute(); } private void WriteAttributeStringValue(XmlDictionaryString value) { if (dictionaryWriter == null) { writer.WriteString(value.Value); } else { dictionaryWriter.WriteString(value); } } internal void WriteAttributeInt(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, int value) { WriteStartAttribute(prefix, attrName, attrNs); WriteAttributeIntValue(value); WriteEndAttribute(); } private void WriteAttributeIntValue(int value) { writer.WriteValue(value); } internal void WriteAttributeBool(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, bool value) { WriteStartAttribute(prefix, attrName, attrNs); WriteAttributeBoolValue(value); WriteEndAttribute(); } private void WriteAttributeBoolValue(bool value) { writer.WriteValue(value); } internal void WriteAttributeQualifiedName(string attrPrefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, string name, string ns) { WriteXmlnsAttribute(ns); WriteStartAttribute(attrPrefix, attrName, attrNs); WriteAttributeQualifiedNameValue(name, ns); WriteEndAttribute(); } private void WriteAttributeQualifiedNameValue(string name, string ns) { writer.WriteQualifiedName(name, ns); } internal void WriteAttributeQualifiedName(string attrPrefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, XmlDictionaryString name, XmlDictionaryString ns) { WriteXmlnsAttribute(ns); WriteStartAttribute(attrPrefix, attrName, attrNs); WriteAttributeQualifiedNameValue(name, ns); WriteEndAttribute(); } private void WriteAttributeQualifiedNameValue(XmlDictionaryString name, XmlDictionaryString ns) { if (dictionaryWriter == null) { writer.WriteQualifiedName(name.Value, ns.Value); } else { dictionaryWriter.WriteQualifiedName(name, ns); } } internal void WriteStartElement(string localName, string ns) { WriteStartElement(null, localName, ns); } internal virtual void WriteStartElement(string prefix, string localName, string ns) { writer.WriteStartElement(prefix, localName, ns); depth++; prefixes = 1; } public void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { WriteStartElement(null, localName, namespaceUri); } internal void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri) { if (dictionaryWriter != null) { dictionaryWriter.WriteStartElement(prefix, localName, namespaceUri); } else { writer.WriteStartElement(prefix, localName?.Value, namespaceUri?.Value); } depth++; prefixes = 1; } internal void WriteStartElementPrimitive(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { if (dictionaryWriter != null) { dictionaryWriter.WriteStartElement(null, localName, namespaceUri); } else { writer.WriteStartElement(null, localName?.Value, namespaceUri?.Value); } } internal void WriteEndElementPrimitive() { writer.WriteEndElement(); } public void WriteNamespaceDecl(XmlDictionaryString ns) { WriteXmlnsAttribute(ns); } private Exception CreateInvalidPrimitiveTypeException(Type type) { return new InvalidDataContractException(SR.GetString("Type '{0}' is not a valid serializable type.", DataContract.GetClrTypeFullName(type))); } internal void WriteAnyType(object value) { WriteAnyType(value, value.GetType()); } internal void WriteAnyType(object value, Type valueType) { bool flag = true; switch (Type.GetTypeCode(valueType)) { case TypeCode.Boolean: WriteBoolean((bool)value); break; case TypeCode.Char: WriteChar((char)value); break; case TypeCode.Byte: WriteUnsignedByte((byte)value); break; case TypeCode.Int16: WriteShort((short)value); break; case TypeCode.Int32: WriteInt((int)value); break; case TypeCode.Int64: WriteLong((long)value); break; case TypeCode.Single: WriteFloat((float)value); break; case TypeCode.Double: WriteDouble((double)value); break; case TypeCode.Decimal: WriteDecimal((decimal)value); break; case TypeCode.DateTime: WriteDateTime((DateTime)value); break; case TypeCode.String: WriteString((string)value); break; case TypeCode.SByte: WriteSignedByte((sbyte)value); break; case TypeCode.UInt16: WriteUnsignedShort((ushort)value); break; case TypeCode.UInt32: WriteUnsignedInt((uint)value); break; case TypeCode.UInt64: WriteUnsignedLong((ulong)value); break; default: if (valueType == Globals.TypeOfByteArray) { WriteBase64((byte[])value); } else if (!(valueType == Globals.TypeOfObject)) { if (valueType == Globals.TypeOfTimeSpan) { WriteTimeSpan((TimeSpan)value); } else if (valueType == Globals.TypeOfGuid) { WriteGuid((Guid)value); } else if (valueType == Globals.TypeOfUri) { WriteUri((Uri)value); } else if (valueType == Globals.TypeOfXmlQualifiedName) { WriteQName((XmlQualifiedName)value); } else { flag = false; } } break; } if (!flag) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidPrimitiveTypeException(valueType)); } } internal void WriteExtensionData(IDataNode dataNode) { bool flag = true; Type dataType = dataNode.DataType; switch (Type.GetTypeCode(dataType)) { case TypeCode.Boolean: WriteBoolean(((DataNode)dataNode).GetValue()); break; case TypeCode.Char: WriteChar(((DataNode)dataNode).GetValue()); break; case TypeCode.Byte: WriteUnsignedByte(((DataNode)dataNode).GetValue()); break; case TypeCode.Int16: WriteShort(((DataNode)dataNode).GetValue()); break; case TypeCode.Int32: WriteInt(((DataNode)dataNode).GetValue()); break; case TypeCode.Int64: WriteLong(((DataNode)dataNode).GetValue()); break; case TypeCode.Single: WriteFloat(((DataNode)dataNode).GetValue()); break; case TypeCode.Double: WriteDouble(((DataNode)dataNode).GetValue()); break; case TypeCode.Decimal: WriteDecimal(((DataNode)dataNode).GetValue()); break; case TypeCode.DateTime: WriteDateTime(((DataNode)dataNode).GetValue()); break; case TypeCode.String: WriteString(((DataNode)dataNode).GetValue()); break; case TypeCode.SByte: WriteSignedByte(((DataNode)dataNode).GetValue()); break; case TypeCode.UInt16: WriteUnsignedShort(((DataNode)dataNode).GetValue()); break; case TypeCode.UInt32: WriteUnsignedInt(((DataNode)dataNode).GetValue()); break; case TypeCode.UInt64: WriteUnsignedLong(((DataNode)dataNode).GetValue()); break; default: if (dataType == Globals.TypeOfByteArray) { WriteBase64(((DataNode)dataNode).GetValue()); } else if (dataType == Globals.TypeOfObject) { object value = dataNode.Value; if (value != null) { WriteAnyType(value); } } else if (dataType == Globals.TypeOfTimeSpan) { WriteTimeSpan(((DataNode)dataNode).GetValue()); } else if (dataType == Globals.TypeOfGuid) { WriteGuid(((DataNode)dataNode).GetValue()); } else if (dataType == Globals.TypeOfUri) { WriteUri(((DataNode)dataNode).GetValue()); } else if (dataType == Globals.TypeOfXmlQualifiedName) { WriteQName(((DataNode)dataNode).GetValue()); } else { flag = false; } break; } if (!flag) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidPrimitiveTypeException(dataType)); } } internal void WriteString(string value) { writer.WriteValue(value); } internal virtual void WriteBoolean(bool value) { writer.WriteValue(value); } public void WriteBoolean(bool value, XmlDictionaryString name, XmlDictionaryString ns) { WriteStartElementPrimitive(name, ns); WriteBoolean(value); WriteEndElementPrimitive(); } internal virtual void WriteDateTime(DateTime value) { writer.WriteValue(value); } public void WriteDateTime(DateTime value, XmlDictionaryString name, XmlDictionaryString ns) { WriteStartElementPrimitive(name, ns); WriteDateTime(value); WriteEndElementPrimitive(); } internal virtual void WriteDecimal(decimal value) { writer.WriteValue(value); } public void WriteDecimal(decimal value, XmlDictionaryString name, XmlDictionaryString ns) { WriteStartElementPrimitive(name, ns); WriteDecimal(value); WriteEndElementPrimitive(); } internal virtual void WriteDouble(double value) { writer.WriteValue(value); } public void WriteDouble(double value, XmlDictionaryString name, XmlDictionaryString ns) { WriteStartElementPrimitive(name, ns); WriteDouble(value); WriteEndElementPrimitive(); } internal virtual void WriteInt(int value) { writer.WriteValue(value); } public void WriteInt(int value, XmlDictionaryString name, XmlDictionaryString ns) { WriteStartElementPrimitive(name, ns); WriteInt(value); WriteEndElementPrimitive(); } internal virtual void WriteLong(long value) { writer.WriteValue(value); } public void WriteLong(long value, XmlDictionaryString name, XmlDictionaryString ns) { WriteStartElementPrimitive(name, ns); WriteLong(value); WriteEndElementPrimitive(); } internal virtual void WriteFloat(float value) { writer.WriteValue(value); } public void WriteFloat(float value, XmlDictionaryString name, XmlDictionaryString ns) { WriteStartElementPrimitive(name, ns); WriteFloat(value); WriteEndElementPrimitive(); } internal virtual void WriteBase64(byte[] bytes) { if (bytes != null) { writer.WriteBase64(bytes, 0, bytes.Length); } } internal virtual void WriteShort(short value) { writer.WriteValue(value); } public void WriteShort(short value, XmlDictionaryString name, XmlDictionaryString ns) { WriteStartElementPrimitive(name, ns); WriteShort(value); WriteEndElementPrimitive(); } internal virtual void WriteUnsignedByte(byte value) { writer.WriteValue(value); } public void WriteUnsignedByte(byte value, XmlDictionaryString name, XmlDictionaryString ns) { WriteStartElementPrimitive(name, ns); WriteUnsignedByte(value); WriteEndElementPrimitive(); } internal virtual void WriteSignedByte(sbyte value) { writer.WriteValue(value); } public void WriteSignedByte(sbyte value, XmlDictionaryString name, XmlDictionaryString ns) { WriteStartElementPrimitive(name, ns); WriteSignedByte(value); WriteEndElementPrimitive(); } internal virtual void WriteUnsignedInt(uint value) { writer.WriteValue(value); } public void WriteUnsignedInt(uint value, XmlDictionaryString name, XmlDictionaryString ns) { WriteStartElementPrimitive(name, ns); WriteUnsignedInt(value); WriteEndElementPrimitive(); } internal virtual void WriteUnsignedLong(ulong value) { writer.WriteRaw(XmlConvert.ToString(value)); } public void WriteUnsignedLong(ulong value, XmlDictionaryString name, XmlDictionaryString ns) { WriteStartElementPrimitive(name, ns); WriteUnsignedLong(value); WriteEndElementPrimitive(); } internal virtual void WriteUnsignedShort(ushort value) { writer.WriteValue(value); } public void WriteUnsignedShort(ushort value, XmlDictionaryString name, XmlDictionaryString ns) { WriteStartElementPrimitive(name, ns); WriteUnsignedShort(value); WriteEndElementPrimitive(); } internal virtual void WriteChar(char value) { writer.WriteValue(value); } public void WriteChar(char value, XmlDictionaryString name, XmlDictionaryString ns) { WriteStartElementPrimitive(name, ns); WriteChar(value); WriteEndElementPrimitive(); } internal void WriteTimeSpan(TimeSpan value) { writer.WriteRaw(XmlConvert.ToString(value)); } public void WriteTimeSpan(TimeSpan value, XmlDictionaryString name, XmlDictionaryString ns) { WriteStartElementPrimitive(name, ns); WriteTimeSpan(value); WriteEndElementPrimitive(); } internal void WriteGuid(Guid value) { writer.WriteRaw(value.ToString()); } public void WriteGuid(Guid value, XmlDictionaryString name, XmlDictionaryString ns) { WriteStartElementPrimitive(name, ns); WriteGuid(value); WriteEndElementPrimitive(); } internal void WriteUri(Uri value) { writer.WriteString(value.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped)); } internal virtual void WriteQName(XmlQualifiedName value) { if (value != XmlQualifiedName.Empty) { WriteXmlnsAttribute(value.Namespace); WriteQualifiedName(value.Name, value.Namespace); } } internal void WriteQualifiedName(string localName, string ns) { writer.WriteQualifiedName(localName, ns); } internal void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString ns) { if (dictionaryWriter == null) { writer.WriteQualifiedName(localName.Value, ns.Value); } else { dictionaryWriter.WriteQualifiedName(localName, ns); } } public void WriteBooleanArray(bool[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { if (dictionaryWriter == null) { for (int i = 0; i < value.Length; i++) { WriteBoolean(value[i], itemName, itemNamespace); } } else { dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length); } } public void WriteDateTimeArray(DateTime[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { if (dictionaryWriter == null) { for (int i = 0; i < value.Length; i++) { WriteDateTime(value[i], itemName, itemNamespace); } } else { dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length); } } public void WriteDecimalArray(decimal[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { if (dictionaryWriter == null) { for (int i = 0; i < value.Length; i++) { WriteDecimal(value[i], itemName, itemNamespace); } } else { dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length); } } public void WriteInt32Array(int[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { if (dictionaryWriter == null) { for (int i = 0; i < value.Length; i++) { WriteInt(value[i], itemName, itemNamespace); } } else { dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length); } } public void WriteInt64Array(long[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { if (dictionaryWriter == null) { for (int i = 0; i < value.Length; i++) { WriteLong(value[i], itemName, itemNamespace); } } else { dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length); } } public void WriteSingleArray(float[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { if (dictionaryWriter == null) { for (int i = 0; i < value.Length; i++) { WriteFloat(value[i], itemName, itemNamespace); } } else { dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length); } } public void WriteDoubleArray(double[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { if (dictionaryWriter == null) { for (int i = 0; i < value.Length; i++) { WriteDouble(value[i], itemName, itemNamespace); } } else { dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length); } } } internal class BitFlagsGenerator { private int bitCount; private byte[] locals; public BitFlagsGenerator(int bitCount) { this.bitCount = bitCount; int num = (bitCount + 7) / 8; locals = new byte[num]; } public void Store(int bitIndex, bool value) { if (value) { locals[GetByteIndex(bitIndex)] |= GetBitValue(bitIndex); } else { locals[GetByteIndex(bitIndex)] &= (byte)(~GetBitValue(bitIndex)); } } public bool Load(int bitIndex) { byte num = locals[GetByteIndex(bitIndex)]; byte bitValue = GetBitValue(bitIndex); return (num & bitValue) == bitValue; } public byte[] LoadArray() { return (byte[])locals.Clone(); } public int GetLocalCount() { return locals.Length; } public int GetBitCount() { return bitCount; } public byte GetLocal(int i) { return locals[i]; } public static bool IsBitSet(byte[] bytes, int bitIndex) { int byteIndex = GetByteIndex(bitIndex); byte bitValue = GetBitValue(bitIndex); return (bytes[byteIndex] & bitValue) == bitValue; } public static void SetBit(byte[] bytes, int bitIndex) { int byteIndex = GetByteIndex(bitIndex); byte bitValue = GetBitValue(bitIndex); bytes[byteIndex] |= bitValue; } private static int GetByteIndex(int bitIndex) { return bitIndex >> 3; } private static byte GetBitValue(int bitIndex) { return (byte)(1 << (bitIndex & 7)); } } internal static class CodeInterpreter { internal static object ConvertValue(object arg, Type source, Type target) { return InternalConvert(arg, source, target, isAddress: false); } private static bool CanConvert(TypeCode typeCode) { if ((uint)(typeCode - 3) <= 11u) { return true; } return false; } private static object InternalConvert(object arg, Type source, Type target, bool isAddress) { if (target == source) { return arg; } if (target.IsValueType) { if (source.IsValueType) { if (!CanConvert(Type.GetTypeCode(target))) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("An internal error has occurred. No conversion is possible to '{0}' - error generating code for serialization.", DataContract.GetClrTypeFullName(target)))); } return target; } if (source.IsAssignableFrom(target)) { return arg; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("An internal error has occurred. '{0}' is not assignable from '{1}' - error generating code for serialization.", DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source)))); } if (target.IsAssignableFrom(source)) { return arg; } if (source.IsAssignableFrom(target)) { return arg; } if (target.IsInterface || source.IsInterface) { return arg; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("An internal error has occurred. '{0}' is not assignable from '{1}' - error generating code for serialization.", DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source)))); } public static object GetMember(MemberInfo memberInfo, object instance) { PropertyInfo propertyInfo = memberInfo as PropertyInfo; if (propertyInfo != null) { return propertyInfo.GetValue(instance); } return ((FieldInfo)memberInfo).GetValue(instance); } public static void SetMember(MemberInfo memberInfo, object instance, object value) { PropertyInfo propertyInfo = memberInfo as PropertyInfo; if (propertyInfo != null) { propertyInfo.SetValue(instance, value); } else { ((FieldInfo)memberInfo).SetValue(instance, value); } } } internal static class DiagnosticUtility { internal static class DiagnosticTrace { internal static void TraceEvent(params object[] args) { } } internal static class ExceptionUtility { internal static Exception ThrowHelperError(Exception e) { return ThrowHelper(e, TraceEventType.Error); } internal static Exception ThrowHelperCallback(string msg, Exception e) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown return (Exception)new CallbackException(msg, e); } internal static Exception ThrowHelperCallback(Exception e) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown return (Exception)new CallbackException("Callback exception", e); } internal static Exception ThrowHelper(Exception e, TraceEventType type) { return e; } internal static Exception ThrowHelperArgument(string arg) { return new ArgumentException(arg); } internal static Exception ThrowHelperArgument(string arg, string message) { return new ArgumentException(message, arg); } internal static Exception ThrowHelperArgumentNull(string arg) { return new ArgumentNullException(arg); } internal static Exception ThrowHelperFatal(string msg, Exception e) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown return (Exception)new FatalException(msg, e); } } internal static bool ShouldTraceError = true; internal static readonly bool ShouldTraceWarning = false; internal static readonly bool ShouldTraceInformation = false; internal static bool ShouldTraceVerbose = true; } internal static class FxTrace { public static bool ShouldTraceError = true; public static bool ShouldTraceVerbose = true; public static EtwDiagnosticTrace Trace => Fx.Trace; public static ExceptionTrace Exception => new ExceptionTrace("System.Runtime.Serialization", Trace); public static bool IsEventEnabled(int index) { return false; } public static void UpdateEventDefinitions(EventDescriptor[] ed, ushort[] events) { } } internal static class SR { public const string ArrayExceededSize = "Array length '{0}' provided by the get-only collection of type '{1}' is less than the number of array elements found in the input stream. Consider increasing the length of the array."; public const string ArrayExceededSizeAttribute = "Array length '{0}' provided by Size attribute is not equal to the number of array elements '{1}' from namespace '{2}' found."; public const string ArrayTypeIsNotSupported = "An internal error has occurred. '{0}[]' is not supported when generating code for serialization."; public const string CannotDeserializeRefAtTopLevel = "Cannot deserialize since root element references unrecognized object with id '{0}'."; public const string CannotLoadMemberType = "Cannot load member type '{0}'."; public const string CannotSerializeObjectWithCycles = "Object graph for type '{0}' contains cycles and cannot be serialized if references are not tracked. Consider using the DataContractAttribute with the IsReference property set to true."; public const string CanOnlyStoreIntoArgOrLocGot0 = "An internal error has occurred. Data can only be stored into ArgBuilder or LocalBuilder. Got: {0}."; public const string CharIsInvalidPrimitive = "An internal error has occurred. Char is not a valid schema primitive and should be treated as int in DataContract."; public const string CallbackMustReturnVoid = "Serialization Callback '{1}' in type '{0}' must return void."; public const string CallbackParameterInvalid = "Serialization Callback '{1}' in type '{0}' must have a single parameter of type '{2}'."; public const string CallbacksCannotBeVirtualMethods = "Virtual Method '{0}' of type '{1}' cannot be marked with '{2}' attribute."; public const string CollectionMustHaveAddMethod = "Collection type '{0}' does not have a valid Add method."; public const string CollectionMustHaveGetEnumeratorMethod = "Collection type '{0}' does not have a valid GetEnumerator method."; public const string CollectionMustHaveItemType = "Collection type '{0}' must have a non-null item type."; public const string CollectionTypeCannotBeBuiltIn = "{0} is a built-in type and cannot be a collection."; public const string CollectionTypeCannotHaveDataContract = "{0} has DataContractAttribute attribute."; public const string CollectionTypeDoesNotHaveAddMethod = "{0} does not have a valid Add method with parameter of type '{1}'."; public const string CollectionTypeDoesNotHaveDefaultCtor = "{0} does not have a default constructor."; public const string CollectionTypeHasMultipleDefinitionsOfInterface = "{0} has multiple definitions of interface '{1}'."; public const string CollectionTypeIsNotIEnumerable = "{0} does not implement IEnumerable interface."; public const string DataContractCacheOverflow = "An internal error has occurred. DataContract cache overflow."; public const string DataContractNamespaceAlreadySet = "ContractNamespaceAttribute attribute maps CLR namespace '{2}' to multiple data contract namespaces '{0}' and '{1}'. You can map a CLR namespace to only one data contract namespace."; public const string DataContractNamespaceIsNotValid = "DataContract namespace '{0}' is not a valid URI."; public const string DataContractNamespaceReserved = "DataContract namespace '{0}' cannot be specified since it is reserved."; public const string DataMemberOnEnumField = "Member '{0}.{1}' has DataMemberAttribute attribute. Use EnumMemberAttribute attribute instead."; public const string DcTypeNotFoundOnDeserialize = "Element '{2}:{3}' contains data of the '{0}:{1}' data contract. The deserializer has no knowledge of any type that maps to this contract. Add the type corresponding to '{1}' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer."; public const string DcTypeNotFoundOnSerialize = "Type '{0}' with data contract name '{1}:{2}' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer."; public const string DcTypeNotResolvedOnDeserialize = "Element '{2}:{3}' contains data from a type that maps to the name '{0}:{1}'. The deserializer has no knowledge of any type that maps to this name. Consider changing the implementation of the ResolveName method on your DataContractResolver to return a non-null value for name '{1}' and namespace '{0}'."; public const string DeserializedObjectWithIdNotFound = "Deserialized object with reference id '{0}' not found in stream."; public const string DupContractInKnownTypes = "Type '{0}' cannot be added to list of known types since another type '{1}' with the same data contract name '{2}:{3}' is already present."; public const string DupKeyValueName = "The collection data contract type '{0}' specifies the same value '{1}' for both the KeyName and the ValueName properties. This is not allowed. Consider changing either the KeyName or the ValueName property."; public const string DupEnumMemberValue = "Type '{2}' contains two members '{0}' 'and '{1}' with the same name '{3}'. Multiple members with the same name in one type are not supported. Consider changing one of the member names using EnumMemberAttribute attribute."; public const string DupMemberName = "Type '{2}' contains two members '{0}' 'and '{1}' with the same data member name '{3}'. Multiple members with the same name in one type are not supported. Consider changing one of the member names using DataMemberAttribute attribute."; public const string DuplicateAttribute = "Invalid Callback. Method '{3}' in type '{2}' has both '{0}' and '{1}'."; public const string DuplicateCallback = "Invalid attribute. Both '{0}' and '{1}' in type '{2}' have '{3}'."; public const string EncounteredWithNameNamespace = "{0}. Encountered '{1}' with name '{2}', namespace '{3}'."; public const string EnumTypeCannotHaveIsReference = "Enum type '{0}' cannot have the IsReference setting of '{1}'. Either change the setting to '{2}', or remove it completely."; public const string ErrorDeserializing = "There was an error deserializing the object {0}. {1}"; public const string ErrorInLine = "Error in line {0} position {1}."; public const string ErrorIsStartObject = "There was an error checking start element of object {0}. {1}"; public const string ErrorSerializing = "There was an error serializing the object {0}. {1}"; public const string ErrorTypeInfo = "of type {0}"; public const string ErrorWriteEndObject = "There was an error writing end element of object {0}. {1}"; public const string ErrorWriteStartObject = "There was an error writing start element of object {0}. {1}"; public const string ExceededMaxItemsQuota = "Maximum number of items that can be serialized or deserialized in an object graph is '{0}'."; public const string ExpectingElement = "Expecting element '{1}' from namespace '{0}'."; public const string ExpectingElementAtDeserialize = "Expecting state '{0}' when ReadObject is called."; public const string ExpectingEnd = "Expecting End'{0}'."; public const string ExpectingState = "Expecting state '{0}'."; public const string GenericNameBraceMismatch = "The data contract name '{0}' for type '{1}' has a curly brace '{{' that is not matched with a closing curly brace. Curly braces have special meaning in data contract names - they are used to customize the naming of data contracts for generic types."; public const string GenericParameterNotValid = "In the data contract name for type '{1}', there are curly braces with '{0}' inside, which is an invalid value. Curly braces have special meaning in data contract names - they are used to customize the naming of data contracts for generic types. Based on the number of generic parameters this type has, the contents of the curly braces must either be a number between 0 and '{2}' to insert the name of the generic parameter at that index or the '#' symbol to insert a digest of the generic parameter namespaces."; public const string InconsistentIsReference = "The IsReference setting for type '{0}' is '{1}', but the same setting for its parent class '{2}' is '{3}'. Derived types must have the same value for IsReference as the base type. Change the setting on type '{0}' to '{3}', or on type '{2}' to '{1}', or do not set IsReference explicitly."; public const string IndexedPropertyCannotBeSerialized = "Property '{1}' in type '{0}' cannot be serialized because serialization of indexed properties is not supported."; public const string InterfaceTypeCannotBeCreated = "Interface type '{0}' cannot be created. Consider replacing with a non-interface serializable type."; public const string InvalidCollectionContractItemName = "Type '{0}' cannot have CollectionDataContractAttribute attribute ItemName set to null or empty string."; public const string InvalidCollectionContractKeyName = "Type '{0}' cannot have CollectionDataContractAttribute attribute KeyName set to null or empty string."; public const string InvalidCollectionContractKeyNoDictionary = "The collection data contract type '{0}' specifies '{1}' for the KeyName property. This is not allowed since the type is not IDictionary. Remove the setting for the KeyName property."; public const string InvalidCollectionContractName = "Type '{0}' cannot have CollectionDataContractAttribute attribute Name set to null or empty string."; public const string InvalidCollectionContractNamespace = "Type '{0}' cannot have CollectionDataContractAttribute attribute Namespace set to null."; public const string InvalidCollectionContractValueName = "Type '{0}' cannot have CollectionDataContractAttribute attribute ValueName set to null or empty string."; public const string InvalidCollectionContractValueNoDictionary = "The collection data contract type '{0}' specifies '{1}' for the ValueName property. This is not allowed since the type is not IDictionary. Remove the setting for the ValueName property."; public const string InvalidCollectionDataContract = "Type '{0}' with CollectionDataContractAttribute attribute is an invalid collection type since it"; public const string InvalidCollectionType = "Type '{0}' is an invalid collection type since it"; public const string InvalidDataContractName = "Type '{0}' cannot have DataContractAttribute attribute Name set to null or empty string."; public const string InvalidDataContractNamespace = "Type '{0}' cannot have DataContractAttribute attribute Namespace set to null."; public const string InvalidDataMemberName = "Member '{0}' in type '{1}' cannot have DataMemberAttribute attribute Name set to null or empty string."; public const string InvalidEnumMemberValue = "'{0}' in type '{1}' cannot have EnumMemberAttribute attribute Value set to null or empty string."; public const string InvalidEnumValueOnRead = "Invalid enum value '{0}' cannot be deserialized into type '{1}'. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attribute."; public const string InvalidEnumValueOnWrite = "Enum value '{0}' is invalid for type '{1}' and cannot be serialized. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attribute."; public const string InvalidGetSchemaMethod = "Type '{0}' cannot have MethodName on XmlSchemaProviderAttribute attribute set to null or empty string."; public const string InvalidGlobalDataContractNamespace = "CLR namespace '{0}' cannot have ContractNamespace set to null."; public const string InvalidMember = "Member '{0}.{1}' cannot be serialized since it is neither a field nor a property, and therefore cannot be marked with the DataMemberAttribute attribute. Remove the DataMemberAttribute attribute from the '{1}' member."; public const string InvalidNonNullReturnValueByIsAny = "Method '{0}.{1}()' returns a non-null value. The return value must be null since IsAny=true."; public const string InvalidPrimitiveType = "Type '{0}' is not a valid serializable type."; public const string InvalidReturnTypeOnGetSchemaMethod = "Method '{0}.{1}()' returns '{2}'. The return type must be compatible with '{3}'."; public const string InvalidSizeDefinition = "Invalid Size '{0}'. Must be non-negative integer."; public const string InvalidXmlDataContractName = "XML data contract Name for type '{0}' cannot be set to null or empty string."; public const string InvalidXsIdDefinition = "Invalid Id '{0}'. Must not be null or empty."; public const string InvalidXsRefDefinition = "Invalid Ref '{0}'. Must not be null or empty."; public const string IsAnyCannotBeNull = "A null value cannot be serialized at the top level for IXmlSerializable root type '{0}' since its IsAny setting is 'true'. This type must write all its contents including the root element. Verify that the IXmlSerializable implementation is correct."; public const string IsAnyCannotBeSerializedAsDerivedType = "An object of type '{0}' cannot be serialized at the top level for IXmlSerializable root type '{1}' since its IsAny setting is 'true'. This type must write all its contents including the root element. Verify that the IXmlSerializable implementation is correct."; public const string IsAnyCannotHaveXmlRoot = "Type '{0}' cannot specify an XmlRootAttribute attribute because its IsAny setting is 'true'. This type must write all its contents including the root element. Verify that the IXmlSerializable implementation is correct."; public const string IsNotAssignableFrom = "An internal error has occurred. '{0}' is not assignable from '{1}' - error generating code for serialization."; public const string IsRequiredDataMemberOnIsReferenceDataContractType = "'{0}.{1}' has the IsRequired setting of '{2}. However, '{0}' has the IsReference setting of '{2}', because either it is set explicitly, or it is derived from a base class. Set IsRequired on '{0}.{1}' to false, or disable IsReference on '{0}'."; public const string IXmlSerializableCannotHaveCollectionDataContract = "Type '{0}' cannot be IXmlSerializable and have CollectionDataContractAttribute attribute."; public const string IXmlSerializableCannotHaveDataContract = "Type '{0}' cannot be IXmlSerializable and have DataContractAttribute attribute."; public const string IXmlSerializableIllegalOperation = "This method cannot be called from IXmlSerializable implementations."; public const string IXmlSerializableMissingEndElements = "IXmlSerializable.WriteXml method of type '{0}' did not close all open tags. Verify that the IXmlSerializable implementation is correct."; public const string IXmlSerializableMustHaveDefaultConstructor = "IXmlSerializable Type '{0}' must have default constructor."; public const string IXmlSerializableWritePastSubTree = "IXmlSerializable.WriteXml method of type '{0}' attempted to close too many tags. Verify that the IXmlSerializable implementation is correct."; public const string KnownTypeAttributeEmptyString = "Method name specified by KnownTypeAttribute attribute on type '{0}' cannot be the empty string."; public const string KnownTypeAttributeUnknownMethod = "KnownTypeAttribute attribute on type '{1}' specifies a method named '{0}' to provide known types. Static method '{0}()' was not found on this type. Ensure that the method exists and is marked as static."; public const string KnownTypeAttributeReturnType = "KnownTypeAttribute attribute on type '{0}' specifies a method named '{1}' to provide known types. The return type of this method is invalid because it is not assignable to IEnumerable. Ensure that the method exists and has a valid signature."; public const string KnownTypeAttributeOneScheme = "Type '{0}': If a KnownTypeAttribute attribute specifies a method it must be the only KnownTypeAttribute attribute on that type."; public const string KnownTypeAttributeNoType = "KnownTypeAttribute attribute on type '{0}' contains no Type."; public const string KnownTypeConfigClosedGenericDeclared = "Declared type '{0}' in config cannot be a closed or partial generic type."; public const string KnownTypeAttributeValidMethodTypes = "Method specified by KnownTypeAttribute attribute on type '{0}' does not expose valid types."; public const string KnownTypeAttributeNoData = "KnownTypeAttribute attribute on type '{0}' contains no data."; public const string KnownTypeAttributeMethodNull = "Method specified by KnownTypeAttribute attribute on type '{0}' returned null."; public const string MaxArrayLengthExceeded = "The maximum array length ({0}) has been exceeded while reading XML data for array of type '{1}'."; public const string MissingGetSchemaMethod = "Type '{0}' does not have a static method '{1}' that takes a parameter of type 'System.Xml.Schema.XmlSchemaSet' as specified by the XmlSchemaProviderAttribute attribute."; public const string MultipleIdDefinition = "Invalid XML encountered. The same Id value '{0}' is defined more than once. Multiple objects cannot be deserialized using the same Id."; public const string NoConversionPossibleTo = "An internal error has occurred. No conversion is possible to '{0}' - error generating code for serialization."; public const string NoGetMethodForProperty = "No get method for property '{1}' in type '{0}'."; public const string NoSetMethodForProperty = "No set method for property '{1}' in type '{0}'."; public const string NullKnownType = "One of the known types provided to the serializer via '{0}' argument was invalid because it was null. All known types specified must be non-null values."; public const string NullValueReturnedForGetOnlyCollection = "The get-only collection of type '{0}' returned a null value. The input stream contains collection items which cannot be added if the instance is null. Consider initializing the collection either in the constructor of the the object or in the getter."; public const string ObjectTableOverflow = "An internal error has occurred. Object table overflow. This could be caused by serializing or deserializing extremely large object graphs."; public const string OrderCannotBeNegative = "Property 'Order' in DataMemberAttribute attribute cannot be a negative number."; public const string ParameterCountMismatch = "Invalid number of parameters to call method '{0}'. Expected '{1}' parameters, but '{2}' were provided."; public const string PartialTrustCollectionContractAddMethodNotPublic = "The collection data contract type '{0}' cannot be deserialized because the method '{1}' is not public. Making the method public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications."; public const string PartialTrustCollectionContractNoPublicConstructor = "The collection data contract type '{0}' cannot be deserialized because it does not have a public parameterless constructor. Adding a public parameterless constructor will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications."; public const string PartialTrustCollectionContractTypeNotPublic = "The collection data contract type '{0}' cannot be deserialized because it does not have a public parameterless constructor. Adding a public parameterless constructor will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications."; public const string PartialTrustDataContractOnSerializingNotPublic = "The data contract type '{0}' cannot be serialized because the OnSerializing method '{1}' is not public. Making the method public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications."; public const string PartialTrustDataContractOnSerializedNotPublic = "The data contract type '{0}' cannot be serialized because the OnSerialized method '{1}' is not public. Making the method public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications."; public const string PartialTrustDataContractOnDeserializingNotPublic = "The data contract type '{0}' cannot be deserialized because the OnDeserializing method '{1}' is not public. Making the method public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications."; public const string PartialTrustDataContractOnDeserializedNotPublic = "The data contract type '{0}' cannot be deserialized because the OnDeserialized method '{1}' is not public. Making the method public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications."; public const string PartialTrustDataContractFieldGetNotPublic = "The data contract type '{0}' cannot be serialized because the member '{1}' is not public. Making the member public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications."; public const string PartialTrustDataContractFieldSetNotPublic = "The data contract type '{0}' cannot be deserialized because the member '{1}' is not public. Making the member public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications."; public const string PartialTrustDataContractPropertyGetNotPublic = "The data contract type '{0}' cannot be serialized because the property '{1}' does not have a public getter. Adding a public getter will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications."; public const string PartialTrustDataContractPropertySetNotPublic = "The data contract type '{0}' cannot be deserialized because the property '{1}' does not have a public setter. Adding a public setter will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications."; public const string PartialTrustDataContractTypeNotPublic = "The data contract type '{0}' is not serializable because it is not public. Making the type public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications."; public const string PartialTrustNonAttributedSerializableTypeNoPublicConstructor = "The type '{0}' cannot be deserialized because it does not have a public parameterless constructor. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications."; public const string PartialTrustIXmlSerializableTypeNotPublic = "The IXmlSerializable type '{0}' is not serializable in partial trust because it is not public. Adding a public parameterless constructor will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications."; public const string PartialTrustIXmlSerialzableNoPublicConstructor = "The IXmlSerializable type '{0}' cannot be deserialized because it does not have a public parameterless constructor. Adding a public parameterless constructor will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications."; public const string NonAttributedSerializableTypesMustHaveDefaultConstructor = "The Type '{0}' must have a parameterless constructor."; public const string AttributedTypesCannotInheritFromNonAttributedSerializableTypes = "Type '{0}' cannot inherit from a type that is not marked with DataContractAttribute or SerializableAttribute. Consider marking the base type '{1}' with DataContractAttribute or SerializableAttribute, or removing them from the derived type."; public const string GetOnlyCollectionsNotSupported = "Get-only collection properties are not supported. Consider adding a public setter to property '{0}.{1}' or marking the it with the IgnoreDataMemberAttribute."; public const string QuotaMustBePositive = "Quota must be a positive value."; public const string QuotaIsReadOnly = "The '{0}' quota is readonly."; public const string QuotaCopyReadOnly = "Cannot copy XmlDictionaryReaderQuotas. Target is readonly."; public const string RequiredMemberMustBeEmitted = "Member {0} in type {1} cannot be serialized. This exception is usually caused by trying to use a null value where a null value is not allowed. The '{0}' member is set to its default value (usually null or zero). The member's EmitDefault setting is 'false', indicating that the member should not be serialized. However, the member's IsRequired setting is 'true', indicating that it must be serialized. This conflict cannot be resolved. Consider setting '{0}' to a non-default value. Alternatively, you can change the EmitDefaultValue property on the DataMemberAttribute attribute to true, or changing the IsRequired property to false."; public const string ResolveTypeReturnedFalse = "An object of type '{0}' which derives from DataContractResolver returned false from its TryResolveType method when attempting to resolve the name for an object of type '{1}', indicating that the resolution failed. Change the TryResolveType implementation to return true."; public const string ResolveTypeReturnedNull = "An object of type '{0}' which derives from DataContractResolver returned a null typeName or typeNamespace but not both from its TryResolveType method when attempting to resolve the name for an object of type '{1}'. Change the TryResolveType implementation to return non-null values, or to return null values for both typeName and typeNamespace in order to serialize as the declared type."; public const string SupportForMultidimensionalArraysNotPresent = "Multi-dimensional arrays are not supported."; public const string TooManyCollectionContracts = "Type '{0}' has more than one CollectionDataContractAttribute attribute."; public const string TooManyDataContracts = "Type '{0}' has more than one DataContractAttribute attribute."; public const string TooManyDataMembers = "Member '{0}.{1}' has more than one DataMemberAttribute attribute."; public const string TooManyEnumMembers = "Member '{0}.{1}' has more than one EnumMemberAttribute attribute."; public const string TooManyIgnoreDataMemberAttributes = "Member '{0}.{1}' has more than one IgnoreDataMemberAttribute attribute."; public const string TypeMustBeConcrete = "Error while getting known types for Type '{0}'. The type must not be an open or partial generic class."; public const string TypeNotSerializable = "Type '{0}' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required."; public const string UnexpectedContractType = "An internal error has occurred. Unexpected contract type '{0}' for type '{1}' encountered."; public const string UnexpectedElementExpectingElements = "'{0}' '{1}' from namespace '{2}' is not expected. Expecting element '{3}'."; public const string UnexpectedEndOfFile = "Unexpected end of file."; public const string UnknownConstantType = "Unrecognized constant type '{0}'."; public const string UnsupportedIDictionaryAsDataMemberType = "Cannot deserialize one of the DataMember because it is an IDictionary. Use IDictionary instead."; public const string ValueMustBeNonNegative = "The value of this argument must be non-negative."; public const string ValueTypeCannotBeNull = "ValueType '{0}' cannot be null."; public const string ValueTypeCannotHaveBaseType = "Data contract '{0}' from namespace '{1}' is a value type and cannot have base contract '{2}' from namespace '{3}'."; public const string ValueTypeCannotHaveId = "ValueType '{0}' cannot have id."; public const string ValueTypeCannotHaveIsReference = "Value type '{0}' cannot have the IsReference setting of '{1}'. Either change the setting to '{2}', or remove it completely."; public const string ValueTypeCannotHaveRef = "ValueType '{0}' cannot have ref to another object."; public const string XmlElementAttributes = "Only Element nodes have attributes."; public const string XmlForObjectCannotHaveContent = "Element {0} from namespace {1} cannot have child contents to be deserialized as an object. Please use XElement to deserialize this pattern of XML."; public const string XmlInvalidConversion = "The value '{0}' cannot be parsed as the type '{1}'."; public const string XmlInvalidConversionWithoutValue = "The value cannot be parsed as the type '{0}'."; public const string XmlStartElementExpected = "Start element expected. Found {0}."; public const string XmlWriterMustBeInElement = "WriteState '{0}' not valid. Caller must write start element before serializing in contentOnly mode."; public const string OffsetExceedsBufferSize = "The specified offset exceeds the buffer size ({0} bytes)."; public const string SizeExceedsRemainingBufferSpace = "The specified size exceeds the remaining buffer space ({0} bytes)."; public const string ValueMustBeInRange = "The value of this argument must fall within the range {0} to {1}."; public const string XmlArrayTooSmallOutput = "Array too small. Must be able to hold at least {0}."; public const string XmlInvalidBase64Length = "Base64 sequence length ({0}) not valid. Must be a multiple of 4."; public const string XmlInvalidBase64Sequence = "The characters '{0}' at offset {1} are not a valid Base64 sequence."; public const string XmlInvalidBinHexLength = "BinHex sequence length ({0}) not valid. Must be a multiple of 2."; public const string XmlInvalidBinHexSequence = "The characters '{0}' at offset {1} are not a valid BinHex sequence."; public const string XmlInvalidHighSurrogate = "High surrogate char '0x{0}' not valid. High surrogate chars range from 0xD800 to 0xDBFF."; public const string XmlInvalidLowSurrogate = "Low surrogate char '0x{0}' not valid. Low surrogate chars range from 0xDC00 to 0xDFFF."; public const string XmlInvalidSurrogate = "Surrogate char '0x{0}' not valid. Surrogate chars range from 0x10000 to 0x10FFFF."; public const string CombinedPrefixNSLength = "The combined length of the prefix and namespace must not be greater than {0}."; public const string InvalidInclusivePrefixListCollection = "The inclusive namespace prefix collection cannot contain null as one of the items."; public const string InvalidLocalNameEmpty = "The empty string is not a valid local name."; public const string XmlArrayTooSmall = "Array too small."; public const string XmlArrayTooSmallInput = "Array too small. Length of available data must be at least {0}."; public const string XmlBadBOM = "Unrecognized Byte Order Mark."; public const string XmlBase64DataExpected = "Base64 encoded data expected. Found {0}."; public const string XmlCDATAInvalidAtTopLevel = "CData elements not valid at top level of an XML document."; public const string XmlCloseCData = "']]>' not valid in text node content."; public const string XmlConversionOverflow = "The value '{0}' cannot be represented with the type '{1}'."; public const string XmlDeclarationRequired = "An XML declaration with an encoding is required for all non-UTF8 documents."; public const string XmlDeclMissingVersion = "Version not found in XML declaration."; public const string XmlDeclMissing = "An XML declaration is required for all non-UTF8 documents."; public const string XmlDeclNotFirst = "No characters can appear before the XML declaration."; public const string XmlDictionaryStringIDRange = "XmlDictionaryString IDs must be in the range from {0} to {1}."; public const string XmlDictionaryStringIDUndefinedSession = "XmlDictionaryString ID {0} not defined in the XmlBinaryReaderSession."; public const string XmlDictionaryStringIDUndefinedStatic = "XmlDictionaryString ID {0} not defined in the static dictionary."; public const string XmlDuplicateAttribute = "Duplicate attribute found. Both '{0}' and '{1}' are from the namespace '{2}'."; public const string XmlEmptyNamespaceRequiresNullPrefix = "The empty namespace requires a null or empty prefix."; public const string XmlEncodingMismatch = "The encoding in the declaration '{0}' does not match the encoding of the document '{1}'."; public const string XmlEncodingNotSupported = "XML encoding not supported."; public const string XmlEndElementExpected = "End element '{0}' from namespace '{1}' expected. Found {2}."; public const string XmlEndElementNoOpenNodes = "No corresponding start element is open."; public const string XmlExpectedEncoding = "The expected encoding '{0}' does not match the actual encoding '{1}'."; public const string XmlFoundCData = "cdata '{0}'"; public const string XmlFoundComment = "comment '{0}'"; public const string XmlFoundElement = "element '{0}' from namespace '{1}'"; public const string XmlFoundEndElement = "end element '{0}' from namespace '{1}'"; public const string XmlFoundEndOfFile = "end of file"; public const string XmlFoundNodeType = "node {0}"; public const string XmlFoundText = "text '{0}'"; public const string XmlFullStartElementExpected = "Non-empty start element expected. Found {0}."; public const string XmlFullStartElementLocalNameNsExpected = "Non-empty start element '{0}' from namespace '{1}' expected. Found {2}."; public const string XmlFullStartElementNameExpected = "Non-empty start element '{0}' expected. Found {1}."; public const string XmlIDDefined = "ID already defined."; public const string XmlKeyAlreadyExists = "The specified key already exists in the dictionary."; public const string XmlIllegalOutsideRoot = "Text cannot be written outside the root element."; public const string XmlInvalidBytes = "Invalid byte encoding."; public const string XmlInvalidCharRef = "Character reference not valid."; public const string XmlInvalidCommentChars = "XML comments cannot contain '--' or end with '-'."; public const string XmlInvalidDeclaration = "XML declaration can only be written at the beginning of the document."; public const string XmlInvalidDepth = "Cannot call '{0}' while Depth is '{1}'."; public const string XmlInvalidEncoding = "XML encoding must be 'UTF-8'."; public const string XmlInvalidFFFE = "Characters with hexadecimal values 0xFFFE and 0xFFFF are not valid."; public const string XmlInvalidFormat = "The input source is not correctly formatted."; public const string XmlInvalidID = "ID must be >= 0."; public const string XmlInvalidOperation = "The reader cannot be advanced."; public const string XmlInvalidPrefixState = "A prefix cannot be defined while WriteState is '{0}'."; public const string XmlInvalidQualifiedName = "Expected XML qualified name. Found '{0}'."; public const string XmlInvalidRootData = "The data at the root level is invalid."; public const string XmlInvalidStandalone = "'standalone' value in declaration must be 'yes' or 'no'."; public const string XmlInvalidStream = "Stream returned by IStreamProvider cannot be null."; public const string XmlInvalidUniqueId = "UniqueId cannot be zero length."; public const string XmlInvalidUTF8Bytes = "'{0}' contains invalid UTF8 bytes."; public const string XmlInvalidVersion = "XML version must be '1.0'."; public const string XmlInvalidWriteState = "'{0}' cannot be called while WriteState is '{1}'."; public const string XmlInvalidXmlByte = "The byte 0x{0} is not valid at this location."; public const string XmlInvalidXmlSpace = "'{0}' is not a valid xml:space value. Valid values are 'default' and 'preserve'."; public const string XmlLineInfo = "Line {0}, position {1}."; public const string XmlMalformedDecl = "Malformed XML declaration."; public const string XmlMaxArrayLengthExceeded = "The maximum array length quota ({0}) has been exceeded while reading XML data. This quota may be increased by changing the MaxArrayLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader."; public const string XmlMaxNameTableCharCountExceeded = "The maximum nametable character count quota ({0}) has been exceeded while reading XML data. The nametable is a data structure used to store strings encountered during XML processing - long XML documents with non-repeating element names, attribute names and attribute values may trigger this quota. This quota may be increased by changing the MaxNameTableCharCount property on the XmlDictionaryReaderQuotas object used when creating the XML reader."; public const string XmlMethodNotSupported = "This XmlWriter implementation does not support the '{0}' method."; public const string XmlMissingLowSurrogate = "The surrogate pair is invalid. Missing a low surrogate character."; public const string XmlMultipleRootElements = "There are multiple root elements."; public const string XmlNamespaceNotFound = "The namespace '{0}' is not defined."; public const string XmlNestedArraysNotSupported = "Nested arrays are not supported."; public const string XmlNoRootElement = "The document does not have a root element."; public const string XmlOnlyOneRoot = "Only one root element is permitted per document."; public const string XmlOnlyWhitespace = "Only white space characters can be written with this method."; public const string XmlOnlySingleValue = "Only a single typed value may be written inside an attribute or content."; public const string XmlPrefixBoundToNamespace = "The prefix '{0}' is bound to the namespace '{1}' and cannot be changed to '{2}'."; public const string XmlProcessingInstructionNotSupported = "Processing instructions (other than the XML declaration) and DTDs are not supported."; public const string XmlReservedPrefix = "Prefixes beginning with \"xml\" (regardless of casing) are reserved for use by XML."; public const string XmlSpaceBetweenAttributes = "Whitespace must appear between attributes."; public const string XmlSpecificBindingNamespace = "The namespace '{1}' can only be bound to the prefix '{0}'."; public const string XmlSpecificBindingPrefix = "The prefix '{0}' can only be bound to the namespace '{1}'."; public const string XmlStartElementLocalNameNsExpected = "Start element '{0}' from namespace '{1}' expected. Found {2}."; public const string XmlStartElementNameExpected = "Start element '{0}' expected. Found {1}."; public const string XmlTagMismatch = "Start element '{0}' does not match end element '{1}'."; public const string XmlTokenExpected = "The token '{0}' was expected but found '{1}'."; public const string XmlUndefinedPrefix = "The prefix '{0}' is not defined."; public const string XmlUnexpectedEndElement = "No matching start tag for end element."; public const string XmlUnexpectedEndOfFile = "Unexpected end of file. Following elements are not closed: {0}."; public const string XmlWriterClosed = "The XmlWriter is closed."; public const string Xml_InvalidNmToken = "Invalid NmToken value '{0}'."; public const string AbstractElementNotSupported = "Abstract element '{0}' is not supported."; public const string AbstractTypeNotSupported = "Abstract type is not supported"; public const string AmbiguousReferencedCollectionTypes1 = "Ambiguous collection types were referenced: {0}"; public const string AmbiguousReferencedCollectionTypes3 = "In '{0}' element in '{1}' namespace, ambiguous collection types were referenced: {2}"; public const string AmbiguousReferencedTypes1 = "Ambiguous types were referenced: {0}"; public const string AmbiguousReferencedTypes3 = "In '{0}' element in '{1}' namespace, ambiguous types were referenced: {2}"; public const string AnnotationAttributeNotFound = "Annotation attribute was not found: default value annotation is '{0}', type is '{1}' in '{2}' namespace, emit default value is {3}."; public const string AnonymousTypeNotSupported = "Anonymous type is not supported. Type is '{0}' in '{1}' namespace."; public const string AnyAttributeNotSupported = "XML Schema 'any' attribute is not supported"; public const string ArrayItemFormMustBe = "For array item, element 'form' must be {0}."; public const string ArraySizeAttributeIncorrect = "Array size attribute is incorrect; must be between {0} and {1}."; public const string ArrayTypeCannotBeImported = "Array type cannot be imported for '{0}' in '{1}' namespace: {2}."; public const string AssemblyNotFound = "Assembly '{0}' was not found."; public const string AttributeNotFound = "Attribute was not found for CLR type '{1}' in namespace '{0}'. XML reader node is on {2}, '{4}' node in '{3}' namespace."; public const string BaseTypeNotISerializable = "Base type '{0}' in '{1}' namespace is not ISerializable."; public const string CannotComputeUniqueName = "Cannot compute unique name for '{0}'."; public const string CannotDeriveFromSealedReferenceType = "Cannod drive from sealed reference type '{2}', for '{0}' element in '{1}' namespace."; public const string CannotDeserializeForwardedType = "Cannot deserialize forwarded type '{0}'."; public const string CannotExportNullAssembly = "Cannot export null assembly."; public const string CannotExportNullKnownType = "Cannot export null known type."; public const string CannotExportNullType = "Cannot export null type."; public const string CannotHaveDuplicateAttributeNames = "Cannot have duplicate attribute names '{0}'."; public const string CannotHaveDuplicateElementNames = "Cannot have duplicate element names '{0}'."; public const string CannotImportInvalidSchemas = "Cannot import invalid schemas."; public const string CannotImportNullDataContractName = "Cannot import data contract with null name."; public const string CannotImportNullSchema = "Cannot import from schema list that contains null."; public const string CannotSetMembersForReferencedType = "Cannot set members for already referenced type. Base type is '{0}'."; public const string CannotSetNamespaceForReferencedType = "Cannot set namespace for already referenced type. Base type is '{0}'."; public const string CannotUseGenericTypeAsBase = "For '{0}' in '{1}' namespace, generic type cannot be referenced as the base type."; public const string ChangingFullTypeNameNotSupported = "Changing full type name is not supported. Serialization type name: '{0}', data contract type name: '{1}'."; public const string CircularTypeReference = "Circular type reference was found for '{0}' in '{1}' namespace."; public const string ClassDataContractReturnedForGetOnlyCollection = "For '{0}' type, class data contract was returned for get-only collection."; public const string CLRNamespaceMappedMultipleTimes = "CLR namespace is mapped multiple times. Current data contract namespace is '{0}', found '{1}' for CLR namespace '{2}'."; public const string ClrTypeNotFound = "CLR type '{1}' in assembly '{0}' is not found."; public const string CollectionAssignedToIncompatibleInterface = "Collection of type '{0}' is assigned to an incompatible interface '{1}'"; public const string ComplexTypeRestrictionNotSupported = "XML schema complexType restriction is not supported."; public const string ConfigDataContractSerializerSectionLoadError = "Failed to load configuration section for dataContractSerializer."; public const string ConfigIndexOutOfRange = "For type '{0}', configuration index is out of range."; public const string ConfigMustOnlyAddParamsWithType = "Configuration parameter element must only add params with type."; public const string ConfigMustOnlySetTypeOrIndex = "Configuration parameter element can set only one of either type or index."; public const string ConfigMustSetTypeOrIndex = "Configuration parameter element must set either type or index."; public const string CouldNotReadSerializationSchema = "Could not read serialization schema for '{0}' namespace."; public const string DefaultOnElementNotSupported = "On element '{0}', default value is not supported."; public const string DerivedTypeNotISerializable = "On type '{0}' in '{1}' namespace, derived type is not ISerializable."; public const string DupContractInDataContractSet = "Duplicate contract in data contract set was found, for '{0}' in '{1}' namespace."; public const string DuplicateExtensionDataSetMethod = "Duplicate extension data set method was found, for method '{0}', existing method is '{1}', on data contract type '{2}'."; public const string DupTypeContractInDataContractSet = "Duplicate type contract in data contract set. Type name '{0}', for data contract '{1}' in '{2}' namespace."; public const string ElementMaxOccursMustBe = "On element '{0}', schema element maxOccurs must be 1."; public const string ElementMinOccursMustBe = "On element '{0}', schema element minOccurs must be less or equal to 1."; public const string ElementRefOnLocalElementNotSupported = "For local element, ref is not supported. The referenced name is '{0}' in '{1}' namespace."; public const string EnumEnumerationFacetsMustHaveValue = "Schema enumeration facet must have values."; public const string EnumListInAnonymousTypeNotSupported = "Enum list in anonymous type is not supported."; public const string EnumListMustContainAnonymousType = "Enum list must contain an anonymous type."; public const string EnumOnlyEnumerationFacetsSupported = "For schema facets, only enumeration is supported."; public const string EnumRestrictionInvalid = "For simpleType restriction, only enum is supported and this type could not be convert to enum."; public const string EnumTypeCannotBeImported = "For '{0}' in '{1}' namespace, enum type cannot be imported: {2}"; public const string EnumTypeNotSupportedByDataContractJsonSerializer = "Enum type is not supported by DataContractJsonSerializer. The underlying type is '{0}'."; public const string EnumUnionInAnonymousTypeNotSupported = "Enum union in anonymous type is not supported."; public const string ExtensionDataSetMustReturnVoid = "For type '{0}' method '{1}', extension data set method must return void."; public const string ExtensionDataSetParameterInvalid = "For type '{0}' method '{1}', extension data set method has invalid type of parameter '{2}'."; public const string FactoryObjectContainsSelfReference = "Factory object contains a reference to self. Old object is '{0}', new object is '{1}'."; public const string FactoryTypeNotISerializable = "For data contract '{1}', factory type '{0}' is not ISerializable."; public const string FixedOnElementNotSupported = "On schema element '{0}', fixed value is not supported."; public const string FlushBufferAlreadyInUse = "Flush buffer is already in use."; public const string FormMustBeQualified = "On schema element '{0}', form must be qualified."; public const string GenericAnnotationAttributeNotFound = "On type '{0}' Generic annotation attribute '{1}' was not found."; public const string GenericAnnotationForNestedLevelMustBeIncreasing = "On type '{2}', generic annotation for nested level must be increasing. Argument element is '{0}' in '{1}' namespace."; public const string GenericAnnotationHasInvalidAttributeValue = "On type '{2}', generic annotation has invalid attribute value '{3}'. Argument element is '{0}' in '{1}' namespace. Nested level attribute attribute name is '{4}'. Type is '{5}'."; public const string GenericAnnotationHasInvalidElement = "On type '{2}', generic annotation has invalid element. Argument element is '{0}' in '{1}' namespace."; public const string GenericTypeNameMismatch = "Generic type name mismatch. Expected '{0}' in '{1}' namespace, got '{2}' in '{3}' namespace instead."; public const string GenericTypeNotExportable = "Generic type '{0}' is not exportable."; public const string GetOnlyCollectionMustHaveAddMethod = "On type '{0}', get-only collection must have an Add method."; public const string GetRealObjectReturnedNull = "On the surrogate data contract for '{0}', GetRealObject method returned null."; public const string InvalidAnnotationExpectingText = "For annotation element '{0}' in namespace '{1}', expected text but got element '{2}' in '{3}' namespace."; public const string InvalidAssemblyFormat = "'{0}': invalid assembly format."; public const string InvalidCharacterEncountered = "Encountered an invalid character '{0}'."; public const string InvalidClassDerivation = "Invalid class derivation from '{0}' in '{1}' namespace."; public const string InvalidClrNameGeneratedForISerializable = "Invalid CLR name '{2}' is generated for ISerializable type '{0}' in '{1}' namespace."; public const string InvalidClrNamespaceGeneratedForISerializable = "Invalid CLR namespace '{3}' is generated for ISerializable type '{0}' in '{1}' namespace. Data contract namespace from the URI would be generated as '{2}'."; public const string InvalidDataNode = "Invalid data node for '{0}' type."; public const string InvalidEmitDefaultAnnotation = "Invalid EmilDefault annotation for '{0}' in type '{1}' in '{2}' namespace."; public const string InvalidEnumBaseType = "Invalid enum base type is specified for type '{0}' in '{1}' namespace, element name is '{2}' in '{3}' namespace."; public const string InvalidISerializableDerivation = "Invalid ISerializable derivation from '{0}' in '{1}' namespace."; public const string InvalidKeyValueType = "'{0}' is an invalid key value type."; public const string InvalidKeyValueTypeNamespace = "'{0}' in '{1}' namespace is an invalid key value type."; public const string InvalidReturnSchemaOnGetSchemaMethod = "On type '{0}', the return value from GetSchema method was invalid."; public const string InvalidStateInExtensionDataReader = "Invalid state in extension data reader."; public const string InvalidXmlDeserializingExtensionData = "Invalid XML while deserializing extension data."; public const string IsAnyNotSupportedByNetDataContractSerializer = "For type '{0}', IsAny is not supported by NetDataContractSerializer."; public const string IsDictionaryFormattedIncorrectly = "IsDictionary formatted value '{0}' is incorrect: {1}"; public const string ISerializableAssemblyNameSetToZero = "ISerializable AssemblyName is set to \"0\" for type '{0}'."; public const string ISerializableCannotHaveDataContract = "ISerializable type '{0}' cannot have DataContract."; public const string ISerializableContainsMoreThanOneItems = "ISerializable cannot contain more than one item."; public const string ISerializableDerivedContainsOneOrMoreItems = "Type derived from ISerializable cannot contain more than one item."; public const string ISerializableDoesNotContainAny = "ISerializable does not contain any element."; public const string ISerializableMustRefFactoryTypeAttribute = "ISerializable must have ref attribute that points to its factory type."; public const string ISerializableTypeCannotBeImported = "ISerializable type '{0}' in '{1}' namespace cannot be imported: {2}"; public const string ISerializableWildcardMaxOccursMustBe = "ISerializable wildcard maxOccurs must be '{0}'."; public const string ISerializableWildcardMinOccursMustBe = "ISerializable wildcard maxOccurs must be '{0}'."; public const string ISerializableWildcardNamespaceInvalid = "ISerializable wildcard namespace is invalid: '{0}'."; public const string ISerializableWildcardProcessContentsInvalid = "ISerializable wildcard processContents is invalid: '{0}'."; public const string IsReferenceGetOnlyCollectionsNotSupported = "On type '{1}', attribute '{0}' points to get-only collection, which is not supported."; public const string IsValueTypeFormattedIncorrectly = "IsValueType is formatted incorrectly as '{0}': {1}"; public const string JsonAttributeAlreadyWritten = "JSON attribute '{0}' is already written."; public const string JsonAttributeMustHaveElement = "JSON attribute must have an owner element."; public const string JsonCannotWriteStandaloneTextAfterQuotedText = "JSON writer cannot write standalone text after quoted text."; public const string JsonCannotWriteTextAfterNonTextAttribute = "JSON writer cannot write text after non-text attribute. Data type is '{0}'."; public const string JsonDateTimeOutOfRange = "JSON DateTime is out of range."; public const string JsonDuplicateMemberInInput = "Duplicate member '{0}' is found in JSON input."; public const string JsonDuplicateMemberNames = "Duplicate member, including '{1}', is found in JSON input, in type '{0}'."; public const string JsonEncodingNotSupported = "JSON Encoding is not supported."; public const string JsonEncounteredUnexpectedCharacter = "Encountered an unexpected character '{0}' in JSON."; public const string JsonEndElementNoOpenNodes = "Encountered an end element while there was no open element in JSON writer."; public const string JsonExpectedEncoding = "Expected encoding '{0}', got '{1}' instead."; public const string JsonInvalidBytes = "Invalid bytes in JSON."; public const string JsonInvalidDataTypeSpecifiedForServerType = "The specified data type is invalid for server type. Type: '{0}', specified data type: '{1}', server type: '{2}', object '{3}'."; public const string JsonInvalidDateTimeString = "Invalid JSON dateTime string is specified: original value '{0}', start guide writer: {1}, end guard writer: {2}."; public const string JsonInvalidFFFE = "FFFE in JSON is invalid."; public const string JsonInvalidItemNameForArrayElement = "Invalid JSON item name '{0}' for array element (item element is '{1}' in JSON)."; public const string JsonInvalidLocalNameEmpty = "Empty string is invalid as a local name."; public const string JsonInvalidMethodBetweenStartEndAttribute = "Invalid method call state between start and end attribute."; public const string JsonInvalidRootElementName = "Invalid root element name '{0}' (root element is '{1}' in JSON)."; public const string JsonInvalidStartElementCall = "Invalid call to JSON WriteStartElement method."; public const string JsonInvalidWriteState = "Invalid write state {1} for '{0}' method."; public const string JsonMethodNotSupported = "Method {0} is not supported in JSON."; public const string JsonMultipleRootElementsNotAllowedOnWriter = "Multiple root element is not allowed on JSON writer."; public const string JsonMustSpecifyDataType = "On JSON writer data type '{0}' must be specified. Object string is '{1}', server type string is '{2}'."; public const string JsonMustUseWriteStringForWritingAttributeValues = "On JSON writer WriteString must be used for writing attribute values."; public const string JsonNamespaceMustBeEmpty = "JSON namespace is specified as '{0}' but it must be empty."; public const string JsonNestedArraysNotSupported = "Nested array is not supported in JSON: '{0}'"; public const string JsonNodeTypeArrayOrObjectNotSpecified = "Either Object or Array of JSON node type must be specified."; public const string JsonNoMatchingStartAttribute = "WriteEndAttribute was called while there is no open attribute."; public const string JsonOffsetExceedsBufferSize = "On JSON writer, offset exceeded buffer size {0}."; public const string JsonOneRequiredMemberNotFound = "Required member {1} in type '{0}' is not found."; public const string JsonOnlyWhitespace = "Only whitespace characters are allowed for {1} method. The specified value is '{0}'"; public const string JsonOpenAttributeMustBeClosedFirst = "JSON attribute must be closed first before calling {0} method."; public const string JsonPrefixMustBeNullOrEmpty = "JSON prefix must be null or empty. '{0}' is specified instead."; public const string JsonRequiredMembersNotFound = "Required members {0} in type '{1}' are not found."; public const string JsonServerTypeSpecifiedForInvalidDataType = "Server type is specified for invalid data type in JSON. Server type: '{0}', type: '{1}', dataType: '{2}', object: '{3}'."; public const string JsonSizeExceedsRemainingBufferSpace = "JSON size exceeded remaining buffer space, by {0} byte(s)."; public const string JsonTypeNotSupportedByDataContractJsonSerializer = "Type '{0}' is not suppotred by DataContractJsonSerializer."; public const string JsonUnexpectedAttributeLocalName = "Unexpected attribute local name '{0}'."; public const string JsonUnexpectedAttributeValue = "Unexpected attribute value '{0}'."; public const string JsonUnexpectedEndOfFile = "Unexpected end of file in JSON."; public const string JsonUnsupportedForIsReference = "Unsupported value for IsReference for type '{0}', IsReference value is {1}."; public const string JsonWriteArrayNotSupported = "JSON WriteArray is not supported."; public const string JsonWriterClosed = "JSON writer is already closed."; public const string JsonXmlInvalidDeclaration = "Attempt to write invalid XML declration."; public const string JsonXmlProcessingInstructionNotSupported = "processing instruction is not supported in JSON writer."; public const string KeyTypeCannotBeParsedInSimpleDictionary = "Key type '{1}' for collection type '{0}' cannot be parsed in simple dictionary."; public const string KnownTypeConfigGenericParamMismatch = "Generic parameter count do not match between known type and configuration. Type is '{0}', known type has {1} parameters, configuration has {2} parameters."; public const string KnownTypeConfigIndexOutOfBounds = "For known type configuration, index is out of bound. Root type: '{0}' has {1} type arguments, and index was {2}."; public const string KnownTypeConfigIndexOutOfBoundsZero = "For known type configuration, index is out of bound. Root type: '{0}' has {1} type arguments, and index was {2}."; public const string KnownTypeConfigObject = "Known type configuration specifies System.Object."; public const string MaxMimePartsExceeded = "MIME parts number exceeded the maximum settings. Must be less than {0}. Specified as '{1}'."; public const string MimeContentTypeHeaderInvalid = "MIME content type header is invalid."; public const string MimeHeaderInvalidCharacter = "MIME header has an invalid character ('{0}', {1} in hexadecimal value)."; public const string MimeMessageGetContentStreamCalledAlready = "On MimeMessage, GetContentStream method is already called."; public const string MimeReaderHeaderAlreadyExists = "MIME header '{0}' already exists."; public const string MimeReaderMalformedHeader = "Malformed MIME header."; public const string MimeReaderResetCalledBeforeEOF = "On MimeReader, Reset method is called before EOF."; public const string MimeReaderTruncated = "MIME parts are truncated."; public const string MimeVersionHeaderInvalid = "MIME version header is invalid."; public const string MimeWriterInvalidStateForClose = "MIME writer is at invalid state for closing."; public const string MimeWriterInvalidStateForContent = "MIME writer is at invalid state for content."; public const string MimeWriterInvalidStateForHeader = "MIME writer is at invalid state for header."; public const string MimeWriterInvalidStateForStartPart = "MIME writer is at invalid state for starting a part."; public const string MimeWriterInvalidStateForStartPreface = "MIME writer is at invalid state for starting preface."; public const string MissingSchemaType = "Schema type '{0}' is missing and required for '{1}' type."; public const string MixedContentNotSupported = "Mixed content is not supported."; public const string MtomBoundaryInvalid = "MIME boundary is invalid: '{0}'."; public const string MtomBufferQuotaExceeded = "MTOM buffer quota exceeded. The maximum size is {0}."; public const string MtomContentTransferEncodingNotPresent = "MTOM content transfer encoding is not present. ContentTransferEncoding header is '{0}'."; public const string MtomContentTransferEncodingNotSupported = "MTOM content transfer encoding value is not supported. Raw value is '{0}', '{1}' in 7bit encoding, '{2}' in 8bit encoding, and '{3}' in binary."; public const string MtomContentTypeInvalid = "MTOM content type is invalid."; public const string MtomDataMustNotContainXopInclude = "MTOM data must not contain xop:Include element. '{0}' element in '{1}' namespace."; public const string MtomExceededMaxSizeInBytes = "MTOM exceeded max size in bytes. The maximum size is {0}."; public const string MtomInvalidCIDUri = "Invalid MTOM CID URI: '{0}'."; public const string MtomInvalidEmptyURI = "empty URI is invalid for MTOM MIME part."; public const string MtomInvalidStartUri = "Invalid MTOM start URI: '{0}'."; public const string MtomInvalidTransferEncodingForMimePart = "Invalid transfer encoding for MIME part: '{0}', in binary: '{1}'."; public const string MtomMessageContentTypeNotFound = "MTOM message content type was not found."; public const string MtomMessageInvalidContent = "MTOM message content is invalid."; public const string MtomMessageInvalidContentInMimePart = "MTOM message content in MIME part is invalid."; public const string MtomMessageInvalidMimeVersion = "MTOM message has invalid MIME version. Expected '{1}', got '{0}' instead."; public const string MtomMessageNotApplicationXopXml = "MTOM msssage type is not '{0}'."; public const string MtomMessageNotMultipart = "MTOM message is not multipart: media type should be '{0}', media subtype should be '{1}'."; public const string MtomMessageRequiredParamNotSpecified = "Required MTOM parameter '{0}' is not specified."; public const string MtomMimePartReferencedMoreThanOnce = "Specified MIME part '{0}' is referenced more than once."; public const string MtomPartNotFound = "MTOM part with URI '{0}' is not found."; public const string MtomRootContentTypeNotFound = "MTOM root content type is not found."; public const string MtomRootNotApplicationXopXml = "MTOM root should have media type '{0}' and subtype '{1}'."; public const string MtomRootPartNotFound = "MTOM root part is not found."; public const string MtomRootRequiredParamNotSpecified = "Required MTOM root parameter '{0}' is not specified."; public const string MtomRootUnexpectedCharset = "Unexpected charset on MTOM root. Expected '{1}', got '{0}' instead."; public const string MtomRootUnexpectedType = "Unexpected type on MTOM root. Expected '{1}', got '{0}' instead."; public const string MtomXopIncludeHrefNotSpecified = "xop Include element did not specify '{0}' attribute."; public const string MtomXopIncludeInvalidXopAttributes = "xop Include element has invalid attribute: '{0}' in '{1}' namespace."; public const string MtomXopIncludeInvalidXopElement = "xop Include element has invalid element: '{0}' in '{1}' namespace."; public const string MustContainOnlyLocalElements = "Only local elements can be imported."; public const string NoAsyncWritePending = "No async write operation is pending."; public const string NonOptionalFieldMemberOnIsReferenceSerializableType = "For type '{0}', non-optional field member '{1}' is on the Serializable type that has IsReference as {2}."; public const string OnlyDataContractTypesCanHaveExtensionData = "On '{0}' type, only DataContract types can have extension data."; public const string PartialTrustISerializableNoPublicConstructor = "Partial trust access required for the constructor on the ISerializable type '{0}'"; public const string QueryGeneratorPathToMemberNotFound = "The path to member was not found for XPath query generator."; public const string ReadNotSupportedOnStream = "Read operation is not supported on the Stream."; public const string ReadOnlyClassDeserialization = "Error on deserializing read-only members in the class: {0}"; public const string ReadOnlyCollectionDeserialization = "Error on deserializing read-only collection: {0}"; public const string RecursiveCollectionType = "Type '{0}' involves recursive collection."; public const string RedefineNotSupported = "XML Schema 'redefine' is not supported."; public const string ReferencedBaseTypeDoesNotExist = "Referenced base type does not exist. Data contract name: '{0}' in '{1}' namespace, expected type: '{2}' in '{3}' namespace. Collection can be '{4}' or '{5}'."; public const string ReferencedCollectionTypesCannotContainNull = "Referenced collection types cannot contain null."; public const string ReferencedTypeDoesNotMatch = "Referenced type '{0}' does not match the expected type '{1}' in '{2}' namespace."; public const string ReferencedTypeMatchingMessage = "Reference type matches."; public const string ReferencedTypeNotMatchingMessage = "Reference type does not match."; public const string ReferencedTypesCannotContainNull = "Referenced types cannot contain null."; public const string RequiresClassDataContractToSetIsISerializable = "To set IsISerializable, class data cotnract is required."; public const string RootParticleMustBeSequence = "Root particle must be sequence to be imported."; public const string RootSequenceMaxOccursMustBe = "On root sequence, maxOccurs must be 1."; public const string RootSequenceMustBeRequired = "Root sequence must have an item and minOccurs must be 1."; public const string SeekNotSupportedOnStream = "Seek operation is not supported on this Stream."; public const string SerializationInfo_ConstructorNotFound = "Constructor that takes SerializationInfo and StreamingContext is not found for '{0}'."; public const string SimpleContentNotSupported = "Simple content is not supported."; public const string SimpleTypeRestrictionDoesNotSpecifyBase = "This simpleType restriction does not specify the base type."; public const string SimpleTypeUnionNotSupported = "simpleType union is not supported."; public const string SpecifiedTypeNotFoundInSchema = "Specified type '{0}' in '{1}' namespace is not found in the schemas."; public const string SubstitutionGroupOnElementNotSupported = "substitutionGroups on elements are not supported."; public const string SurrogatesWithGetOnlyCollectionsNotSupported = "Surrogates with get-only collections are not supported. Type '{1}' contains '{2}' which is of '{0}' type."; public const string SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser = "Surrogates with get-only collections are not supported. Found on type '{0}'."; public const string TopLevelElementRepresentsDifferentType = "Top-level element represents a different type. Expected '{0}' type in '{1}' namespace."; public const string TraceCodeElementIgnored = "Element ignored"; public const string TraceCodeFactoryTypeNotFound = "Factory type not found"; public const string TraceCodeObjectWithLargeDepth = "Object with large depth"; public const string TraceCodeReadObjectBegin = "ReadObject begins"; public const string TraceCodeReadObjectEnd = "ReadObject ends"; public const string TraceCodeWriteObjectBegin = "WriteObject begins"; public const string TraceCodeWriteObjectContentBegin = "WriteObjectContent begins"; public const string TraceCodeWriteObjectContentEnd = "WriteObjectContent ends"; public const string TraceCodeWriteObjectEnd = "WriteObject ends"; public const string TraceCodeXsdExportAnnotationFailed = "XSD export annotation failed"; public const string TraceCodeXsdExportBegin = "XSD export begins"; public const string TraceCodeXsdExportDupItems = "XSD export duplicate items"; public const string TraceCodeXsdExportEnd = "XSD export ends"; public const string TraceCodeXsdExportError = "XSD export error"; public const string TraceCodeXsdImportAnnotationFailed = "XSD import annotation failed"; public const string TraceCodeXsdImportBegin = "XSD import begins"; public const string TraceCodeXsdImportEnd = "XSD import ends"; public const string TraceCodeXsdImportError = "XSD import error"; public const string TypeCannotBeForwardedFrom = "Type '{0}' in assembly '{1}' cannot be forwarded from assembly '{2}'."; public const string TypeCannotBeImported = "Type '{0}' in '{1}' namespace cannot be imported: {2}"; public const string TypeCannotBeImportedHowToFix = "Type cannot be imported: {0}"; public const string TypeHasNotBeenImported = "Type '{0}' in '{1}' namespace has not been imported."; public const string TypeMustBeIXmlSerializable = "Type '{0}' must be IXmlSerializable. Contract type: '{1}', contract name: '{2}' in '{3}' namespace."; public const string TypeShouldNotContainAttributes = "Type should not contain attributes. Serialization namespace: '{0}'."; public const string UnknownXmlType = "Unknown XML type: '{0}'."; public const string WriteBufferOverflow = "Write buffer overflow."; public const string WriteNotSupportedOnStream = "Write operation is not supported on this '{0}' Stream."; public const string XmlCanonicalizationNotStarted = "XML canonicalization was not started."; public const string XmlCanonicalizationStarted = "XML canonicalization started"; public const string XmlMaxArrayLengthOrMaxItemsQuotaExceeded = "XML max array length or max items quota exceeded. It must be less than {0}."; public const string XmlMaxBytesPerReadExceeded = "XML max bytes per read exceeded. It must be less than {0}."; public const string XmlMaxDepthExceeded = "XML max depth exceeded. It must be less than {0}."; public const string XmlMaxStringContentLengthExceeded = "XML max string content length exceeded. It must be less than {0}."; public const string XmlObjectAssignedToIncompatibleInterface = "Object of type '{0}' is assigned to an incompatible interface '{1}'."; internal static string GetString(string name, params object[] args) { return GetString(CultureInfo.InvariantCulture, name, args); } internal static string GetString(CultureInfo culture, string name, params object[] args) { return string.Format(culture, name, args); } internal static string GetString(string name) { return name; } internal static string GetString(CultureInfo culture, string name) { return name; } } internal class SchemaExporter { private static XmlQualifiedName actualTypeAnnotationName; internal static XmlQualifiedName ActualTypeAnnotationName { get { if (actualTypeAnnotationName == null) { actualTypeAnnotationName = new XmlQualifiedName("ActualType", "http://schemas.microsoft.com/2003/10/Serialization/"); } return actualTypeAnnotationName; } } internal static void GetXmlTypeInfo(Type type, out XmlQualifiedName stableName, out XmlSchemaType xsdType, out bool hasRoot) { if (!IsSpecialXmlType(type, out stableName, out xsdType, out hasRoot)) { XmlSchemaSet xmlSchemaSet = new XmlSchemaSet(); xmlSchemaSet.XmlResolver = null; InvokeSchemaProviderMethod(type, xmlSchemaSet, out stableName, out xsdType, out hasRoot); if (stableName.Name == null || stableName.Name.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("XML data contract Name for type '{0}' cannot be set to null or empty string.", DataContract.GetClrTypeFullName(type)))); } } } internal static bool IsSpecialXmlType(Type type, out XmlQualifiedName typeName, out XmlSchemaType xsdType, out bool hasRoot) { xsdType = null; hasRoot = true; if (type == Globals.TypeOfXmlElement || type == Globals.TypeOfXmlNodeArray) { string text = null; if (type == Globals.TypeOfXmlElement) { xsdType = CreateAnyElementType(); text = "XmlElement"; hasRoot = false; } else { xsdType = CreateAnyType(); text = "ArrayOfXmlNode"; hasRoot = true; } typeName = new XmlQualifiedName(text, DataContract.GetDefaultStableNamespace(type)); return true; } typeName = null; return false; } internal static void AddDefaultXmlType(XmlSchemaSet schemas, string localName, string ns) { throw new NotImplementedException(); } private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schemas, out XmlQualifiedName stableName, out XmlSchemaType xsdType, out bool hasRoot) { xsdType = null; hasRoot = true; object[] customAttributes = clrType.GetCustomAttributes(Globals.TypeOfXmlSchemaProviderAttribute, inherit: false); if (customAttributes == null || customAttributes.Length == 0) { stableName = DataContract.GetDefaultStableName(clrType); return false; } XmlSchemaProviderAttribute xmlSchemaProviderAttribute = (XmlSchemaProviderAttribute)customAttributes[0]; if (xmlSchemaProviderAttribute.IsAny) { xsdType = CreateAnyElementType(); hasRoot = false; } string methodName = xmlSchemaProviderAttribute.MethodName; if (methodName == null || methodName.Length == 0) { if (!xmlSchemaProviderAttribute.IsAny) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Type '{0}' cannot have MethodName on XmlSchemaProviderAttribute attribute set to null or empty string.", DataContract.GetClrTypeFullName(clrType)))); } stableName = DataContract.GetDefaultStableName(clrType); } else { MethodInfo method = clrType.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(XmlSchemaSet) }, null); if (method == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Type '{0}' does not have a static method '{1}' that takes a parameter of type 'System.Xml.Schema.XmlSchemaSet' as specified by the XmlSchemaProviderAttribute attribute.", DataContract.GetClrTypeFullName(clrType), methodName))); } if (!Globals.TypeOfXmlQualifiedName.IsAssignableFrom(method.ReturnType) && !Globals.TypeOfXmlSchemaType.IsAssignableFrom(method.ReturnType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Method '{0}.{1}()' returns '{2}'. The return type must be compatible with '{3}'.", DataContract.GetClrTypeFullName(clrType), methodName, DataContract.GetClrTypeFullName(method.ReturnType), DataContract.GetClrTypeFullName(Globals.TypeOfXmlQualifiedName), typeof(XmlSchemaType)))); } object obj = method.Invoke(null, new object[1] { schemas }); if (xmlSchemaProviderAttribute.IsAny) { if (obj != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Method '{0}.{1}()' returns a non-null value. The return value must be null since IsAny=true.", DataContract.GetClrTypeFullName(clrType), methodName))); } stableName = DataContract.GetDefaultStableName(clrType); } else if (obj == null) { xsdType = CreateAnyElementType(); hasRoot = false; stableName = DataContract.GetDefaultStableName(clrType); } else if (obj is XmlSchemaType xmlSchemaType) { string localName = xmlSchemaType.Name; string ns = null; if (localName == null || localName.Length == 0) { DataContract.GetDefaultStableName(DataContract.GetClrTypeFullName(clrType), out localName, out ns); stableName = new XmlQualifiedName(localName, ns); xmlSchemaType.Annotation = GetSchemaAnnotation(ExportActualType(stableName, new XmlDocument())); xsdType = xmlSchemaType; } else { foreach (XmlSchema item in schemas.Schemas()) { foreach (XmlSchemaObject item2 in item.Items) { if (item2 == xmlSchemaType) { ns = item.TargetNamespace; if (ns == null) { ns = string.Empty; } break; } } if (ns != null) { break; } } if (ns == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("Schema type '{0}' is missing and required for '{1}' type.", localName, DataContract.GetClrTypeFullName(clrType)))); } stableName = new XmlQualifiedName(localName, ns); } } else { stableName = (XmlQualifiedName)obj; } } return true; } private static XmlSchemaComplexType CreateAnyElementType() { XmlSchemaComplexType obj = new XmlSchemaComplexType { IsMixed = false, Particle = new XmlSchemaSequence() }; XmlSchemaAny item = new XmlSchemaAny { MinOccurs = 0m, ProcessContents = XmlSchemaContentProcessing.Lax }; ((XmlSchemaSequence)obj.Particle).Items.Add(item); return obj; } private static XmlSchemaAnnotation GetSchemaAnnotation(params XmlNode[] nodes) { if (nodes == null || nodes.Length == 0) { return null; } bool flag = false; for (int i = 0; i < nodes.Length; i++) { if (nodes[i] != null) { flag = true; break; } } if (!flag) { return null; } XmlSchemaAnnotation xmlSchemaAnnotation = new XmlSchemaAnnotation(); XmlSchemaAppInfo xmlSchemaAppInfo = new XmlSchemaAppInfo(); xmlSchemaAnnotation.Items.Add(xmlSchemaAppInfo); xmlSchemaAppInfo.Markup = nodes; return xmlSchemaAnnotation; } private static XmlSchemaComplexType CreateAnyType() { XmlSchemaComplexType obj = new XmlSchemaComplexType { IsMixed = true, Particle = new XmlSchemaSequence() }; XmlSchemaAny item = new XmlSchemaAny { MinOccurs = 0m, MaxOccurs = decimal.MaxValue, ProcessContents = XmlSchemaContentProcessing.Lax }; ((XmlSchemaSequence)obj.Particle).Items.Add(item); obj.AnyAttribute = new XmlSchemaAnyAttribute(); return obj; } private static XmlElement ExportActualType(XmlQualifiedName typeName, XmlDocument xmlDoc) { XmlElement xmlElement = xmlDoc.CreateElement(ActualTypeAnnotationName.Name, ActualTypeAnnotationName.Namespace); XmlAttribute xmlAttribute = xmlDoc.CreateAttribute("Name"); xmlAttribute.Value = typeName.Name; xmlElement.Attributes.Append(xmlAttribute); XmlAttribute xmlAttribute2 = xmlDoc.CreateAttribute("Namespace"); xmlAttribute2.Value = typeName.Namespace; xmlElement.Attributes.Append(xmlAttribute2); return xmlElement; } } internal enum CodeTypeReferenceOptions { GlobalReference = 1, GenericTypeParameter } internal class CodeTypeReference { private string baseType; [OptionalField] private bool isInterface; private int arrayRank; private CodeTypeReference arrayElementType; [OptionalField] private List typeArguments; [OptionalField] private CodeTypeReferenceOptions referenceOptions; [OptionalField] private bool needsFixup; public CodeTypeReference ArrayElementType { get { return arrayElementType; } set { arrayElementType = value; } } public int ArrayRank { get { return arrayRank; } set { arrayRank = value; } } internal int NestedArrayDepth { get { if (arrayElementType == null) { return 0; } return 1 + arrayElementType.NestedArrayDepth; } } public string BaseType { get { if (arrayRank > 0 && arrayElementType != null) { return arrayElementType.BaseType; } if (string.IsNullOrEmpty(baseType)) { return string.Empty; } string text = baseType; if (needsFixup && TypeArguments.Count > 0) { text = text + "`" + TypeArguments.Count.ToString(CultureInfo.InvariantCulture); } return text; } set { baseType = value; Initialize(baseType); } } [ComVisible(false)] public CodeTypeReferenceOptions Options { get { return referenceOptions; } set { referenceOptions = value; } } [ComVisible(false)] public List TypeArguments { get { if (arrayRank > 0 && arrayElementType != null) { return arrayElementType.TypeArguments; } if (typeArguments == null) { typeArguments = new List(); } return typeArguments; } } internal bool IsInterface => isInterface; public CodeTypeReference() { baseType = string.Empty; arrayRank = 0; arrayElementType = null; } public CodeTypeReference(Type type) { if (type == null) { throw new ArgumentNullException("type"); } if (type.IsArray) { arrayRank = type.GetArrayRank(); arrayElementType = new CodeTypeReference(type.GetElementType()); baseType = null; } else { InitializeFromType(type); arrayRank = 0; arrayElementType = null; } isInterface = type.IsInterface; } public CodeTypeReference(Type type, CodeTypeReferenceOptions codeTypeReferenceOption) : this(type) { referenceOptions = codeTypeReferenceOption; } public CodeTypeReference(string typeName, CodeTypeReferenceOptions codeTypeReferenceOption) { Initialize(typeName, codeTypeReferenceOption); } public CodeTypeReference(string typeName) { Initialize(typeName); } private void InitializeFromType(Type type) { baseType = type.Name; if (!type.IsGenericParameter) { Type type2 = type; while (type2.IsNested) { type2 = type2.DeclaringType; baseType = type2.Name + "+" + baseType; } if (!string.IsNullOrEmpty(type.Namespace)) { baseType = type.Namespace + "." + baseType; } } if (type.IsGenericType && !type.ContainsGenericParameters) { Type[] genericArguments = type.GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { TypeArguments.Add(new CodeTypeReference(genericArguments[i])); } } else if (!type.IsGenericTypeDefinition) { needsFixup = true; } } private void Initialize(string typeName) { Initialize(typeName, referenceOptions); } private void Initialize(string typeName, CodeTypeReferenceOptions options) { Options = options; if (typeName == null || typeName.Length == 0) { typeName = typeof(void).FullName; baseType = typeName; arrayRank = 0; arrayElementType = null; return; } typeName = RipOffAssemblyInformationFromTypeName(typeName); int num = typeName.Length - 1; int num2 = num; needsFixup = true; Queue queue = new Queue(); while (num2 >= 0) { int num3 = 1; if (typeName[num2--] != ']') { break; } while (num2 >= 0 && typeName[num2] == ',') { num3++; num2--; } if (num2 < 0 || typeName[num2] != '[') { break; } queue.Enqueue(num3); num2--; num = num2; } num2 = num; ArrayList arrayList = new ArrayList(); Stack stack = new Stack(); if (num2 > 0 && typeName[num2--] == ']') { needsFixup = false; int num4 = 1; int num5 = num; while (num2 >= 0) { if (typeName[num2] == '[') { if (--num4 == 0) { break; } } else if (typeName[num2] == ']') { num4++; } else if (typeName[num2] == ',' && num4 == 1) { if (num2 + 1 < num5) { stack.Push(typeName.Substring(num2 + 1, num5 - num2 - 1)); } num5 = num2; } num2--; } if (num2 > 0 && num - num2 - 1 > 0) { if (num2 + 1 < num5) { stack.Push(typeName.Substring(num2 + 1, num5 - num2 - 1)); } while (stack.Count > 0) { string typeName2 = RipOffAssemblyInformationFromTypeName((string)stack.Pop()); arrayList.Add(new CodeTypeReference(typeName2)); } num = num2 - 1; } } if (num < 0) { baseType = typeName; return; } if (queue.Count > 0) { CodeTypeReference codeTypeReference = new CodeTypeReference(typeName.Substring(0, num + 1), Options); for (int i = 0; i < arrayList.Count; i++) { codeTypeReference.TypeArguments.Add((CodeTypeReference)arrayList[i]); } while (queue.Count > 1) { codeTypeReference = new CodeTypeReference(codeTypeReference, (int)queue.Dequeue()); } baseType = null; arrayRank = (int)queue.Dequeue(); arrayElementType = codeTypeReference; } else if (arrayList.Count > 0) { for (int j = 0; j < arrayList.Count; j++) { TypeArguments.Add((CodeTypeReference)arrayList[j]); } baseType = typeName.Substring(0, num + 1); } else { baseType = typeName; } if (baseType != null && baseType.IndexOf('`') != -1) { needsFixup = false; } } public CodeTypeReference(string typeName, params CodeTypeReference[] typeArguments) : this(typeName) { if (typeArguments != null && typeArguments.Length != 0) { TypeArguments.AddRange(typeArguments); } } public CodeTypeReference(string baseType, int rank) { this.baseType = null; arrayRank = rank; arrayElementType = new CodeTypeReference(baseType); } public CodeTypeReference(CodeTypeReference arrayType, int rank) { baseType = null; arrayRank = rank; arrayElementType = arrayType; } private string RipOffAssemblyInformationFromTypeName(string typeName) { int i = 0; int num = typeName.Length - 1; string result = typeName; for (; i < typeName.Length && char.IsWhiteSpace(typeName[i]); i++) { } while (num >= 0 && char.IsWhiteSpace(typeName[num])) { num--; } if (i < num) { if (typeName[i] == '[' && typeName[num] == ']') { i++; num--; } if (typeName[num] != ']') { int num2 = 0; for (int num3 = num; num3 >= i; num3--) { if (typeName[num3] == ',') { num2++; if (num2 == 4) { result = typeName.Substring(i, num3 - i); break; } } } } } return result; } } internal class XmlDataContractInterpreter { private XmlDataContract contract; public XmlDataContractInterpreter(XmlDataContract contract) { this.contract = contract; } public IXmlSerializable CreateXmlSerializable() { Type underlyingType = contract.UnderlyingType; object obj = null; obj = ((!underlyingType.IsValueType) ? GetConstructor().Invoke(new object[0]) : FormatterServices.GetUninitializedObject(underlyingType)); return (IXmlSerializable)obj; } private ConstructorInfo GetConstructor() { Type underlyingType = contract.UnderlyingType; if (underlyingType.IsValueType) { return null; } ConstructorInfo constructor = underlyingType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Globals.EmptyTypeArray, null); if (constructor == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("IXmlSerializable Type '{0}' must have default constructor.", DataContract.GetClrTypeFullName(underlyingType)))); } return constructor; } } internal class XmlFormatReaderInterpreter { private bool is_get_only_collection; private ClassDataContract classContract; private CollectionDataContract collectionContract; private object objectLocal; private Type objectType; private XmlReaderDelegator xmlReader; private XmlObjectSerializerReadContext context; private XmlDictionaryString[] memberNames; private XmlDictionaryString[] memberNamespaces; private XmlDictionaryString itemName; private XmlDictionaryString itemNamespace; public XmlFormatReaderInterpreter(ClassDataContract classContract) { this.classContract = classContract; } public XmlFormatReaderInterpreter(CollectionDataContract collectionContract, bool isGetOnly) { this.collectionContract = collectionContract; is_get_only_collection = isGetOnly; } public object ReadFromXml(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces) { this.xmlReader = xmlReader; this.context = context; this.memberNames = memberNames; this.memberNamespaces = memberNamespaces; CreateObject(classContract); context.AddNewObject(objectLocal); InvokeOnDeserializing(classContract); string text = null; if (HasFactoryMethod(classContract)) { text = context.GetObjectId(); } if (classContract.IsISerializable) { ReadISerializable(classContract); } else { ReadClass(classContract); } bool flag = InvokeFactoryMethod(classContract, text); if (Globals.TypeOfIDeserializationCallback.IsAssignableFrom(classContract.UnderlyingType)) { ((IDeserializationCallback)objectLocal).OnDeserialization(null); } InvokeOnDeserialized(classContract); if ((text == null || !flag) && classContract.UnderlyingType == Globals.TypeOfDateTimeOffsetAdapter) { objectLocal = DateTimeOffsetAdapter.GetDateTimeOffset((DateTimeOffsetAdapter)objectLocal); } return objectLocal; } public object ReadCollectionFromXml(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract) { this.xmlReader = xmlReader; this.context = context; this.itemName = itemName; this.itemNamespace = itemNamespace; this.collectionContract = collectionContract; ReadCollection(collectionContract); return objectLocal; } public void ReadGetOnlyCollectionFromXml(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract) { this.xmlReader = xmlReader; this.context = context; this.itemName = itemName; this.itemNamespace = itemNamespace; this.collectionContract = collectionContract; ReadGetOnlyCollection(collectionContract); } private void CreateObject(ClassDataContract classContract) { Type type = (objectType = classContract.UnderlyingType); if (type.IsValueType && !classContract.IsNonAttributedType) { type = Globals.TypeOfValueType; } if (classContract.UnderlyingType == Globals.TypeOfDBNull) { objectLocal = DBNull.Value; } else if (classContract.IsNonAttributedType) { if (type.IsValueType) { objectLocal = FormatterServices.GetUninitializedObject(type); } else { objectLocal = classContract.GetNonAttributedTypeConstructor().Invoke(new object[0]); } } else { objectLocal = CodeInterpreter.ConvertValue(XmlFormatReaderGenerator.UnsafeGetUninitializedObject(DataContract.GetIdForInitialization(classContract)), Globals.TypeOfObject, type); } } private void InvokeOnDeserializing(ClassDataContract classContract) { if (classContract.BaseContract != null) { InvokeOnDeserializing(classContract.BaseContract); } if (classContract.OnDeserializing != null) { classContract.OnDeserializing.Invoke(objectLocal, new object[1] { context.GetStreamingContext() }); } } private void InvokeOnDeserialized(ClassDataContract classContract) { if (classContract.BaseContract != null) { InvokeOnDeserialized(classContract.BaseContract); } if (classContract.OnDeserialized != null) { classContract.OnDeserialized.Invoke(objectLocal, new object[1] { context.GetStreamingContext() }); } } private bool HasFactoryMethod(ClassDataContract classContract) { return Globals.TypeOfIObjectReference.IsAssignableFrom(classContract.UnderlyingType); } private bool InvokeFactoryMethod(ClassDataContract classContract, string objectId) { if (HasFactoryMethod(classContract)) { objectLocal = CodeInterpreter.ConvertValue(context.GetRealObject((IObjectReference)objectLocal, objectId), Globals.TypeOfObject, classContract.UnderlyingType); return true; } return false; } private void ReadISerializable(ClassDataContract classContract) { ConstructorInfo iSerializableConstructor = classContract.GetISerializableConstructor(); SerializationInfo serializationInfo = context.ReadSerializationInfo(xmlReader, classContract.UnderlyingType); iSerializableConstructor.Invoke(objectLocal, new object[2] { serializationInfo, context.GetStreamingContext() }); } private void ReadClass(ClassDataContract classContract) { if (classContract.HasExtensionData) { ExtensionDataObject extensionDataObject = new ExtensionDataObject(); ReadMembers(classContract, extensionDataObject); for (ClassDataContract classDataContract = classContract; classDataContract != null; classDataContract = classDataContract.BaseContract) { MethodInfo extensionDataSetMethod = classDataContract.ExtensionDataSetMethod; if (extensionDataSetMethod != null) { extensionDataSetMethod.Invoke(objectLocal, new object[1] { extensionDataObject }); } } } else { ReadMembers(classContract, null); } } private void ReadMembers(ClassDataContract classContract, ExtensionDataObject extensionData) { int num = classContract.MemberNames.Length; context.IncrementItemCount(num); int memberIndex = -1; int firstRequiredMember; bool[] requiredMembers = GetRequiredMembers(classContract, out firstRequiredMember); bool flag = firstRequiredMember < num; int requiredIndex = (flag ? firstRequiredMember : num); while (XmlObjectSerializerReadContext.MoveToNextElement(xmlReader)) { int index = ((!flag) ? context.GetMemberIndex(xmlReader, memberNames, memberNamespaces, memberIndex, extensionData) : context.GetMemberIndexWithRequiredMembers(xmlReader, memberNames, memberNamespaces, memberIndex, requiredIndex, extensionData)); if (num > 0) { ReadMembers(index, classContract, requiredMembers, ref memberIndex, ref requiredIndex); } } if (flag && requiredIndex < num) { XmlObjectSerializerReadContext.ThrowRequiredMemberMissingException(xmlReader, memberIndex, requiredIndex, memberNames); } } private int ReadMembers(int index, ClassDataContract classContract, bool[] requiredMembers, ref int memberIndex, ref int requiredIndex) { int num = ((classContract.BaseContract != null) ? ReadMembers(index, classContract.BaseContract, requiredMembers, ref memberIndex, ref requiredIndex) : 0); if (num <= index && index < num + classContract.Members.Count) { DataMember dataMember = classContract.Members[index - num]; Type memberType = dataMember.MemberType; if (dataMember.IsRequired) { int i; for (i = index + 1; i < requiredMembers.Length && !requiredMembers[i]; i++) { } requiredIndex = i; } if (dataMember.IsGetOnlyCollection) { object member = CodeInterpreter.GetMember(dataMember.MemberInfo, objectLocal); context.StoreCollectionMemberInfo(member); ReadValue(memberType, dataMember.Name, classContract.StableName.Namespace); } else { object value = ReadValue(memberType, dataMember.Name, classContract.StableName.Namespace); CodeInterpreter.SetMember(dataMember.MemberInfo, objectLocal, value); } memberIndex = index; } return num + classContract.Members.Count; } private bool[] GetRequiredMembers(ClassDataContract contract, out int firstRequiredMember) { int num = contract.MemberNames.Length; bool[] array = new bool[num]; GetRequiredMembers(contract, array); firstRequiredMember = 0; while (firstRequiredMember < num && !array[firstRequiredMember]) { firstRequiredMember++; } return array; } private int GetRequiredMembers(ClassDataContract contract, bool[] requiredMembers) { int num = ((contract.BaseContract != null) ? GetRequiredMembers(contract.BaseContract, requiredMembers) : 0); List members = contract.Members; int num2 = 0; while (num2 < members.Count) { requiredMembers[num] = members[num2].IsRequired; num2++; num++; } return num; } private object ReadValue(Type type, string name, string ns) { Type type2 = type; object obj = null; bool flag = false; int num = 0; while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) { num++; type = type.GetGenericArguments()[0]; } PrimitiveDataContract primitiveDataContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if ((primitiveDataContract != null && primitiveDataContract.UnderlyingType != Globals.TypeOfObject) || num != 0 || type.IsValueType) { context.ReadAttributes(xmlReader); string text = context.ReadIfNullOrRef(xmlReader, type, DataContract.IsTypeSerializable(type)); if (text == null) { if (num != 0) { obj = Activator.CreateInstance(type2); } else { if (type.IsValueType) { throw new SerializationException(SR.GetString("ValueType '{0}' cannot be null.", DataContract.GetClrTypeFullName(type))); } obj = null; } } else if (text == string.Empty) { text = context.GetObjectId(); if (type.IsValueType && !string.IsNullOrEmpty(text)) { throw new SerializationException(SR.GetString("ValueType '{0}' cannot have id.", DataContract.GetClrTypeFullName(type))); } if (num != 0) { flag = true; } if (primitiveDataContract != null && primitiveDataContract.UnderlyingType != Globals.TypeOfObject) { obj = primitiveDataContract.XmlFormatReaderMethod.Invoke(xmlReader, new object[0]); if (!type.IsValueType) { context.AddNewObject(obj); } } else { obj = InternalDeserialize(type, name, ns); } } else { if (type.IsValueType) { throw new SerializationException(SR.GetString("ValueType '{0}' cannot have ref to another object.", DataContract.GetClrTypeFullName(type))); } obj = CodeInterpreter.ConvertValue(context.GetExistingObject(text, type, name, ns), Globals.TypeOfObject, type); } if (flag && text != null) { obj = WrapNullableObject(type, obj, type2, num); } } else { obj = InternalDeserialize(type, name, ns); } return obj; } private object InternalDeserialize(Type type, string name, string ns) { Type type2 = (type.IsPointer ? Globals.TypeOfReflectionPointer : type); object obj = context.InternalDeserialize(xmlReader, DataContract.GetId(type2.TypeHandle), type2.TypeHandle, name, ns); if (type.IsPointer) { return XmlFormatGeneratorStatics.UnboxPointer.Invoke(null, new object[1] { obj }); } return CodeInterpreter.ConvertValue(obj, Globals.TypeOfObject, type); } private object WrapNullableObject(Type innerType, object innerValue, Type outerType, int nullables) { object obj = innerValue; for (int i = 1; i < nullables; i++) { Type type = Globals.TypeOfNullable.MakeGenericType(innerType); obj = Activator.CreateInstance(type, obj); innerType = type; } return Activator.CreateInstance(outerType, obj); } private void ReadCollection(CollectionDataContract collectionContract) { Type type = collectionContract.UnderlyingType; Type itemType = collectionContract.ItemType; bool flag = collectionContract.Kind == CollectionKind.Array; ConstructorInfo constructorInfo = collectionContract.Constructor; if (type.IsInterface) { switch (collectionContract.Kind) { case CollectionKind.GenericDictionary: type = Globals.TypeOfDictionaryGeneric.MakeGenericType(itemType.GetGenericArguments()); constructorInfo = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null); break; case CollectionKind.Dictionary: type = Globals.TypeOfHashtable; constructorInfo = XmlFormatGeneratorStatics.HashtableCtor; break; case CollectionKind.GenericList: case CollectionKind.GenericCollection: case CollectionKind.List: case CollectionKind.GenericEnumerable: case CollectionKind.Collection: case CollectionKind.Enumerable: type = itemType.MakeArrayType(); flag = true; break; } } string text = collectionContract.ItemName; string @namespace = collectionContract.StableName.Namespace; if (!flag) { if (type.IsValueType) { objectLocal = FormatterServices.GetUninitializedObject(type); } else { objectLocal = constructorInfo.Invoke(new object[0]); context.AddNewObject(objectLocal); } } int arraySize = context.GetArraySize(); string objectId = context.GetObjectId(); bool flag2 = false; bool readResult = false; if (flag && TryReadPrimitiveArray(type, itemType, arraySize, out readResult)) { flag2 = true; } if (!readResult) { if (arraySize == -1) { object obj = null; if (flag) { obj = Array.CreateInstance(itemType, 32); } int i; for (i = 0; i < int.MaxValue; i++) { if (IsStartElement(itemName, itemNamespace)) { context.IncrementItemCount(1); object value = ReadCollectionItem(collectionContract, itemType, text, @namespace); if (flag) { obj = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod(itemType).Invoke(null, new object[2] { obj, i }); ((Array)obj).SetValue(value, i); } else { StoreCollectionValue(objectLocal, itemType, value, collectionContract); } } else { if (IsEndElement()) { break; } HandleUnexpectedItemInCollection(ref i); } } if (flag) { MethodInfo methodInfo = XmlFormatGeneratorStatics.TrimArraySizeMethod.MakeGenericMethod(itemType); objectLocal = methodInfo.Invoke(null, new object[2] { obj, i }); context.AddNewObjectWithId(objectId, objectLocal); } } else { context.IncrementItemCount(arraySize); if (flag) { objectLocal = Array.CreateInstance(itemType, arraySize); context.AddNewObject(objectLocal); } for (int j = 0; j < arraySize; j++) { if (IsStartElement(itemName, itemNamespace)) { object value2 = ReadCollectionItem(collectionContract, itemType, text, @namespace); if (flag) { ((Array)objectLocal).SetValue(value2, j); } else { StoreCollectionValue(objectLocal, itemType, value2, collectionContract); } } else { HandleUnexpectedItemInCollection(ref j); } } context.CheckEndOfArray(xmlReader, arraySize, itemName, itemNamespace); } } if (flag2) { context.AddNewObjectWithId(objectId, objectLocal); } } private void ReadGetOnlyCollection(CollectionDataContract collectionContract) { Type underlyingType = collectionContract.UnderlyingType; Type itemType = collectionContract.ItemType; bool flag = collectionContract.Kind == CollectionKind.Array; string text = collectionContract.ItemName; string @namespace = collectionContract.StableName.Namespace; objectLocal = context.GetCollectionMember(); if (!IsStartElement(itemName, itemNamespace)) { return; } if (objectLocal == null) { XmlObjectSerializerReadContext.ThrowNullValueReturnedForGetOnlyCollectionException(underlyingType); return; } int num = 0; if (flag) { num = ((Array)objectLocal).Length; } context.AddNewObject(objectLocal); int iterator = 0; while (iterator < int.MaxValue) { if (IsStartElement(itemName, itemNamespace)) { context.IncrementItemCount(1); object value = ReadCollectionItem(collectionContract, itemType, text, @namespace); if (flag) { if (num == iterator) { XmlObjectSerializerReadContext.ThrowArrayExceededSizeException(num, underlyingType); } else { ((Array)objectLocal).SetValue(value, iterator); } } else { StoreCollectionValue(objectLocal, itemType, value, collectionContract); } } else { if (IsEndElement()) { break; } HandleUnexpectedItemInCollection(ref iterator); } } context.CheckEndOfArray(xmlReader, num, itemName, itemNamespace); } private bool TryReadPrimitiveArray(Type type, Type itemType, int size, out bool readResult) { readResult = false; if (PrimitiveDataContract.GetPrimitiveDataContract(itemType) == null) { return false; } string text = null; switch (Type.GetTypeCode(itemType)) { case TypeCode.Boolean: text = "TryReadBooleanArray"; break; case TypeCode.DateTime: text = "TryReadDateTimeArray"; break; case TypeCode.Decimal: text = "TryReadDecimalArray"; break; case TypeCode.Int32: text = "TryReadInt32Array"; break; case TypeCode.Int64: text = "TryReadInt64Array"; break; case TypeCode.Single: text = "TryReadSingleArray"; break; case TypeCode.Double: text = "TryReadDoubleArray"; break; } if (text != null) { MethodInfo method = typeof(XmlReaderDelegator).GetMethod(text, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); object[] array = new object[5] { context, itemName, itemNamespace, size, objectLocal }; readResult = (bool)method.Invoke(xmlReader, array); objectLocal = array.Last(); return true; } return false; } private object ReadCollectionItem(CollectionDataContract collectionContract, Type itemType, string itemName, string itemNs) { if (collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary) { context.ResetAttributes(); return CodeInterpreter.ConvertValue(collectionContract.ItemContract.ReadXmlValue(xmlReader, context), Globals.TypeOfObject, itemType); } return ReadValue(itemType, itemName, itemNs); } private void StoreCollectionValue(object collection, Type valueType, object value, CollectionDataContract collectionContract) { if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary) { ClassDataContract obj = DataContract.GetDataContract(valueType) as ClassDataContract; DataMember dataMember = obj.Members[0]; DataMember dataMember2 = obj.Members[1]; object member = CodeInterpreter.GetMember(dataMember.MemberInfo, value); object member2 = CodeInterpreter.GetMember(dataMember2.MemberInfo, value); collectionContract.AddMethod.Invoke(collection, new object[2] { member, member2 }); } else { collectionContract.AddMethod.Invoke(collection, new object[1] { value }); } } private void HandleUnexpectedItemInCollection(ref int iterator) { if (IsStartElement()) { context.SkipUnknownElement(xmlReader); iterator--; return; } throw XmlObjectSerializerReadContext.CreateUnexpectedStateException(XmlNodeType.Element, xmlReader); } private bool IsStartElement(XmlDictionaryString name, XmlDictionaryString ns) { return xmlReader.IsStartElement(name, ns); } private bool IsStartElement() { return xmlReader.IsStartElement(); } private bool IsEndElement() { return xmlReader.NodeType == XmlNodeType.EndElement; } } internal class XmlFormatWriterInterpreter { private ClassDataContract classContract; private CollectionDataContract collectionContract; private XmlWriterDelegator writer; private object obj; private XmlObjectSerializerWriteContext ctx; private DataContract dataContract; private object objLocal; private XmlDictionaryString[] contractNamespaces; private XmlDictionaryString[] memberNames; private XmlDictionaryString[] childElementNamespaces; private int typeIndex = 1; private int childElementIndex; private ClassDataContract classDataContract => (ClassDataContract)dataContract; private CollectionDataContract collectionDataContract => (CollectionDataContract)dataContract; public XmlFormatWriterInterpreter(ClassDataContract classContract) { this.classContract = classContract; } public XmlFormatWriterInterpreter(CollectionDataContract collectionContract) { this.collectionContract = collectionContract; } public void WriteToXml(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract dataContract) { writer = xmlWriter; this.obj = obj; ctx = context; this.dataContract = dataContract; InitArgs(classContract.UnderlyingType); if (classContract.IsReadOnlyContract) { DataContract.ThrowInvalidDataContractException(classContract.SerializationExceptionMessage, null); } WriteClass(classContract); } public void WriteCollectionToXml(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract collectionContract) { writer = xmlWriter; this.obj = obj; ctx = context; dataContract = collectionContract; InitArgs(collectionContract.UnderlyingType); if (collectionContract.IsReadOnlyContract) { DataContract.ThrowInvalidDataContractException(collectionContract.SerializationExceptionMessage, null); } WriteCollection(collectionContract); } private void InitArgs(Type objType) { if (objType == Globals.TypeOfDateTimeOffsetAdapter) { objLocal = DateTimeOffsetAdapter.GetDateTimeOffsetAdapter((DateTimeOffset)obj); } else { objLocal = CodeInterpreter.ConvertValue(obj, typeof(object), objType); } } private void InvokeOnSerializing(ClassDataContract classContract, object objSerialized, XmlObjectSerializerWriteContext ctx) { if (classContract.BaseContract != null) { InvokeOnSerializing(classContract.BaseContract, objSerialized, ctx); } if (classContract.OnSerializing != null) { classContract.OnSerializing.Invoke(objSerialized, new object[1] { ctx.GetStreamingContext() }); } } private void InvokeOnSerialized(ClassDataContract classContract, object objSerialized, XmlObjectSerializerWriteContext ctx) { if (classContract.BaseContract != null) { InvokeOnSerialized(classContract.BaseContract, objSerialized, ctx); } if (classContract.OnSerialized != null) { classContract.OnSerialized.Invoke(objSerialized, new object[1] { ctx.GetStreamingContext() }); } } private void WriteClass(ClassDataContract classContract) { InvokeOnSerializing(classContract, objLocal, ctx); if (classContract.IsISerializable) { ctx.WriteISerializable(writer, (ISerializable)objLocal); } else { if (classContract.ContractNamespaces.Length > 1) { contractNamespaces = classDataContract.ContractNamespaces; } memberNames = classDataContract.MemberNames; for (int i = 0; i < classContract.ChildElementNamespaces.Length; i++) { if (classContract.ChildElementNamespaces[i] != null) { childElementNamespaces = classDataContract.ChildElementNamespaces; } } if (classContract.HasExtensionData) { ExtensionDataObject extensionData = ((IExtensibleDataObject)objLocal).ExtensionData; ctx.WriteExtensionData(writer, extensionData, -1); WriteMembers(classContract, extensionData, classContract); } else { WriteMembers(classContract, null, classContract); } } InvokeOnSerialized(classContract, objLocal, ctx); } private void WriteCollection(CollectionDataContract collectionContract) { XmlDictionaryString @namespace = dataContract.Namespace; XmlDictionaryString collectionItemName = collectionDataContract.CollectionItemName; if (collectionContract.ChildElementNamespace != null) { writer.WriteNamespaceDecl(collectionDataContract.ChildElementNamespace); } if (collectionContract.Kind == CollectionKind.Array) { Type itemType = collectionContract.ItemType; if (objLocal.GetType().GetElementType() != itemType) { throw new InvalidCastException($"Cannot cast array of {objLocal.GetType().GetElementType()} to array of {itemType}"); } ctx.IncrementArrayCount(writer, (Array)objLocal); if (TryWritePrimitiveArray(collectionContract.UnderlyingType, itemType, () => objLocal, collectionItemName, @namespace)) { return; } Array array = (Array)objLocal; int[] array2 = new int[1]; for (int i = 0; i < array.Length; i++) { if (!TryWritePrimitive(itemType, null, null, i, @namespace, collectionItemName, 0)) { WriteStartElement(itemType, collectionContract.Namespace, @namespace, collectionItemName, 0); array2[0] = i; object value = array.GetValue(array2); WriteValue(itemType, value, writeXsiType: false); WriteEndElement(); } } return; } if (!collectionContract.UnderlyingType.IsAssignableFrom(objLocal.GetType())) { throw new InvalidCastException($"Cannot cast {objLocal.GetType()} to {collectionContract.UnderlyingType}"); } MethodInfo methodInfo = null; switch (collectionContract.Kind) { case CollectionKind.Dictionary: case CollectionKind.List: case CollectionKind.Collection: methodInfo = XmlFormatGeneratorStatics.IncrementCollectionCountMethod; break; case CollectionKind.GenericList: case CollectionKind.GenericCollection: methodInfo = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(collectionContract.ItemType); break; case CollectionKind.GenericDictionary: methodInfo = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments())); break; } if (methodInfo != null) { methodInfo.Invoke(ctx, new object[2] { writer, objLocal }); } bool flag = false; bool flag2 = false; Type type = null; Type[] typeArguments = null; if (collectionContract.Kind == CollectionKind.GenericDictionary) { flag2 = true; typeArguments = collectionContract.ItemType.GetGenericArguments(); type = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType(typeArguments); } else if (collectionContract.Kind == CollectionKind.Dictionary) { flag = true; typeArguments = new Type[2] { Globals.TypeOfObject, Globals.TypeOfObject }; type = Globals.TypeOfDictionaryEnumerator; } else { type = collectionContract.GetEnumeratorMethod.ReturnType; } MethodInfo method = type.GetMethod("MoveNext", BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null); MethodInfo methodInfo2 = type.GetMethod("get_Current", BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null); if (method == null || methodInfo2 == null) { if (type.IsInterface) { if (method == null) { method = XmlFormatGeneratorStatics.MoveNextMethod; } if (methodInfo2 == null) { methodInfo2 = XmlFormatGeneratorStatics.GetCurrentMethod; } } else { Type interfaceType = Globals.TypeOfIEnumerator; CollectionKind kind = collectionContract.Kind; if (kind == CollectionKind.GenericDictionary || kind == CollectionKind.GenericCollection || kind == CollectionKind.GenericEnumerable) { Type[] interfaces = type.GetInterfaces(); foreach (Type type2 in interfaces) { if (type2.IsGenericType && type2.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric && type2.GetGenericArguments()[0] == collectionContract.ItemType) { interfaceType = type2; break; } } } if (method == null) { method = CollectionDataContract.GetTargetMethodWithName("MoveNext", type, interfaceType); } if (methodInfo2 == null) { methodInfo2 = CollectionDataContract.GetTargetMethodWithName("get_Current", type, interfaceType); } } } Type returnType = methodInfo2.ReturnType; object currentValue = null; IEnumerator enumerator = (IEnumerator)collectionContract.GetEnumeratorMethod.Invoke(objLocal, new object[0]); if (flag) { enumerator = new CollectionDataContract.DictionaryEnumerator((IDictionaryEnumerator)enumerator); } else if (flag2) { Type type3 = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(typeArguments)); type.GetConstructor(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { type3 }, null); enumerator = (IEnumerator)Activator.CreateInstance(type, enumerator); } object[] parameters = new object[0]; while (enumerator != null && enumerator.MoveNext()) { currentValue = methodInfo2.Invoke(enumerator, parameters); if (methodInfo == null) { XmlFormatGeneratorStatics.IncrementItemCountMethod.Invoke(ctx, new object[1] { 1 }); } if (!TryWritePrimitive(returnType, () => currentValue, null, null, @namespace, collectionItemName, 0)) { WriteStartElement(returnType, collectionContract.Namespace, @namespace, collectionItemName, 0); if (flag2 || flag) { collectionDataContract.ItemContract.WriteXmlValue(writer, currentValue, ctx); } else { WriteValue(returnType, currentValue, writeXsiType: false); } WriteEndElement(); } } } private int WriteMembers(ClassDataContract classContract, ExtensionDataObject extensionData, ClassDataContract derivedMostClassContract) { int num = ((classContract.BaseContract != null) ? WriteMembers(classContract.BaseContract, extensionData, derivedMostClassContract) : 0); XmlDictionaryString xmlDictionaryString = ((contractNamespaces == null) ? dataContract.Namespace : contractNamespaces[typeIndex - 1]); ctx.IncrementItemCount(classContract.Members.Count); int num2 = 0; while (num2 < classContract.Members.Count) { DataMember dataMember = classContract.Members[num2]; Type memberType = dataMember.MemberType; object memberValue = null; if (dataMember.IsGetOnlyCollection) { ctx.StoreIsGetOnlyCollection(); } bool flag = true; bool flag2 = false; if (!dataMember.EmitDefaultValue) { flag2 = true; memberValue = LoadMemberValue(dataMember); flag = !IsDefaultValue(memberType, memberValue); } if (flag) { bool flag3 = CheckIfMemberHasConflict(dataMember, classContract, derivedMostClassContract); if (flag3 || !TryWritePrimitive(memberType, flag2 ? ((Func)(() => memberValue)) : null, dataMember.MemberInfo, null, xmlDictionaryString, null, num2 + childElementIndex)) { WriteStartElement(memberType, classContract.Namespace, xmlDictionaryString, null, num2 + childElementIndex); if (classContract.ChildElementNamespaces[num2 + childElementIndex] != null) { writer.WriteNamespaceDecl(childElementNamespaces[num2 + childElementIndex]); } if (memberValue == null) { memberValue = LoadMemberValue(dataMember); } WriteValue(memberType, memberValue, flag3); WriteEndElement(); } if (classContract.HasExtensionData) { ctx.WriteExtensionData(writer, extensionData, num); } } else if (!dataMember.EmitDefaultValue && dataMember.IsRequired) { XmlObjectSerializerWriteContext.ThrowRequiredMemberMustBeEmitted(dataMember.Name, classContract.UnderlyingType); } num2++; num++; } typeIndex++; childElementIndex += classContract.Members.Count; return num; } internal bool IsDefaultValue(Type type, object value) { return GetDefaultValue(type)?.Equals(value) ?? (value == null); } internal object GetDefaultValue(Type type) { if (type.IsValueType) { switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: return false; case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: return 0; case TypeCode.Int64: case TypeCode.UInt64: return 0L; case TypeCode.Single: return 0f; case TypeCode.Double: return 0.0; case TypeCode.Decimal: return 0m; case TypeCode.DateTime: return default(DateTime); } } return null; } private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract classContract, ClassDataContract derivedMostClassContract) { if (CheckIfConflictingMembersHaveDifferentTypes(member)) { return true; } string name = member.Name; string @namespace = classContract.StableName.Namespace; ClassDataContract classDataContract = derivedMostClassContract; while (classDataContract != null && classDataContract != classContract) { if (@namespace == classDataContract.StableName.Namespace) { List members = classDataContract.Members; for (int i = 0; i < members.Count; i++) { if (name == members[i].Name) { return CheckIfConflictingMembersHaveDifferentTypes(members[i]); } } } classDataContract = classDataContract.BaseContract; } return false; } private bool CheckIfConflictingMembersHaveDifferentTypes(DataMember member) { while (member.ConflictingMember != null) { if (member.MemberType != member.ConflictingMember.MemberType) { return true; } member = member.ConflictingMember; } return false; } private bool NeedsPrefix(Type type, XmlDictionaryString ns) { if (type == Globals.TypeOfXmlQualifiedName) { if (ns != null && ns.Value != null) { return ns.Value.Length > 0; } return false; } return false; } private void WriteStartElement(Type type, XmlDictionaryString ns, XmlDictionaryString namespaceLocal, XmlDictionaryString nameLocal, int nameIndex) { bool num = NeedsPrefix(type, ns); nameLocal = nameLocal ?? memberNames[nameIndex]; if (num) { writer.WriteStartElement("q", nameLocal, namespaceLocal); } else { writer.WriteStartElement(nameLocal, namespaceLocal); } } private void WriteEndElement() { writer.WriteEndElement(); } private void WriteValue(Type memberType, object memberValue, bool writeXsiType) { if (memberType.IsPointer) { _ = (Pointer)XmlFormatGeneratorStatics.BoxPointer.Invoke(null, new object[2] { memberValue, memberType }); } bool flag = memberType.IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable; if (memberType.IsValueType && !flag) { PrimitiveDataContract primitiveDataContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); if (primitiveDataContract != null && !writeXsiType) { primitiveDataContract.XmlFormatContentWriterMethod.Invoke(writer, new object[1] { memberValue }); } else { bool isDeclaredType = Type.GetTypeHandle(memberValue).Equals(CodeInterpreter.ConvertValue(memberValue, memberType, Globals.TypeOfObject)); ctx.InternalSerialize(writer, memberValue, isDeclaredType, writeXsiType, DataContract.GetId(memberType.TypeHandle), memberType.TypeHandle); } return; } bool isNull; if (flag) { memberValue = UnwrapNullableObject(() => memberValue, ref memberType, out isNull); } else { isNull = memberValue == null; } if (isNull) { XmlFormatGeneratorStatics.WriteNullMethod.Invoke(ctx, new object[3] { writer, memberType, DataContract.IsTypeSerializable(memberType) }); return; } PrimitiveDataContract primitiveDataContract2 = PrimitiveDataContract.GetPrimitiveDataContract(memberType); if (primitiveDataContract2 != null && primitiveDataContract2.UnderlyingType != Globals.TypeOfObject && !writeXsiType) { if (flag) { primitiveDataContract2.XmlFormatContentWriterMethod.Invoke(writer, new object[1] { memberValue }); } else { primitiveDataContract2.XmlFormatContentWriterMethod.Invoke(ctx, new object[2] { writer, memberValue }); } return; } bool flag2 = false; if (memberType == Globals.TypeOfObject || memberType == Globals.TypeOfValueType || ((IList)Globals.TypeOfNullable.GetInterfaces()).Contains((object?)memberType)) { object obj = CodeInterpreter.ConvertValue(memberValue, memberType.GetType(), Globals.TypeOfObject); memberValue = obj; flag2 = memberValue == null; } if (flag2) { XmlFormatGeneratorStatics.WriteNullMethod.Invoke(ctx, new object[3] { writer, memberType, DataContract.IsTypeSerializable(memberType) }); return; } RuntimeTypeHandle typeHandle = Type.GetTypeHandle(memberValue); bool isDeclaredType2 = typeHandle.Equals(CodeInterpreter.ConvertValue(memberValue, memberType, Globals.TypeOfObject)); if (flag) { ctx.InternalSerialize(writer, memberValue, isDeclaredType2, writeXsiType, DataContract.GetId(memberType.TypeHandle), memberType.TypeHandle); } else if (memberType == Globals.TypeOfObject) { DataContract dataContract = DataContract.GetDataContract(memberValue.GetType()); writer.WriteAttributeQualifiedName("i", DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContract.Name, dataContract.Namespace); ctx.InternalSerializeReference(writer, memberValue, isDeclaredType: false, writeXsiType: false, -1, typeHandle); } else { ctx.InternalSerializeReference(writer, memberValue, isDeclaredType2, writeXsiType, DataContract.GetId(memberType.TypeHandle), memberType.TypeHandle); } } private object UnwrapNullableObject(Func memberValue, ref Type memberType, out bool isNull) { object obj = memberValue(); isNull = false; while (memberType.IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable) { Type type = memberType.GetGenericArguments()[0]; if ((bool)XmlFormatGeneratorStatics.GetHasValueMethod.MakeGenericMethod(type).Invoke(null, new object[1] { obj })) { obj = XmlFormatGeneratorStatics.GetNullableValueMethod.MakeGenericMethod(type).Invoke(null, new object[1] { obj }); } else { isNull = true; obj = XmlFormatGeneratorStatics.GetDefaultValueMethod.MakeGenericMethod(memberType).Invoke(null, new object[0]); } memberType = type; } return obj; } private bool TryWritePrimitive(Type type, Func value, MemberInfo memberInfo, int? arrayItemIndex, XmlDictionaryString ns, XmlDictionaryString name, int nameIndex) { PrimitiveDataContract primitiveDataContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if (primitiveDataContract == null || primitiveDataContract.UnderlyingType == Globals.TypeOfObject) { return false; } object obj = null; List list = new List(); if (type.IsValueType) { obj = writer; } else { obj = ctx; list.Add(writer); } if (value != null) { list.Add(value()); } else if (memberInfo != null) { list.Add(CodeInterpreter.GetMember(memberInfo, objLocal)); } else { list.Add(((Array)objLocal).GetValue(new int[1] { arrayItemIndex.Value })); } if (name != null) { list.Add(name); } else { list.Add(memberNames[nameIndex]); } list.Add(ns); primitiveDataContract.XmlFormatWriterMethod.Invoke(obj, list.ToArray()); return true; } private bool TryWritePrimitiveArray(Type type, Type itemType, Func value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { if (PrimitiveDataContract.GetPrimitiveDataContract(itemType) == null) { return false; } string text = null; switch (Type.GetTypeCode(itemType)) { case TypeCode.Boolean: text = "WriteBooleanArray"; break; case TypeCode.DateTime: text = "WriteDateTimeArray"; break; case TypeCode.Decimal: text = "WriteDecimalArray"; break; case TypeCode.Int32: text = "WriteInt32Array"; break; case TypeCode.Int64: text = "WriteInt64Array"; break; case TypeCode.Single: text = "WriteSingleArray"; break; case TypeCode.Double: text = "WriteDoubleArray"; break; } if (text != null) { typeof(XmlWriterDelegator).GetMethod(text, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[3] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) }, null).Invoke(writer, new object[3] { value(), itemName, itemNamespace }); return true; } return false; } private object LoadMemberValue(DataMember member) { return CodeInterpreter.GetMember(member.MemberInfo, objLocal); } } public class XsdDataContractExporter { public ExportOptions Options { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public XmlSchemaSet Schemas { get { throw new NotImplementedException(); } } public XsdDataContractExporter() { throw new NotImplementedException(); } public XsdDataContractExporter(XmlSchemaSet schemas) { throw new NotImplementedException(); } public bool CanExport(ICollection assemblies) { throw new NotImplementedException(); } public bool CanExport(ICollection types) { throw new NotImplementedException(); } public bool CanExport(Type type) { throw new NotImplementedException(); } public void Export(ICollection assemblies) { throw new NotImplementedException(); } public void Export(ICollection types) { throw new NotImplementedException(); } public void Export(Type type) { throw new NotImplementedException(); } public XmlQualifiedName GetRootElementName(Type type) { throw new NotImplementedException(); } public XmlSchemaType GetSchemaType(Type type) { throw new NotImplementedException(); } public XmlQualifiedName GetSchemaTypeName(Type type) { throw new NotImplementedException(); } } } namespace System.Runtime.Serialization.Json { internal class ByteArrayHelperWithString : ArrayHelper { public static readonly ByteArrayHelperWithString Instance = new ByteArrayHelperWithString(); internal void WriteArray(XmlWriter writer, byte[] array, int offset, int count) { XmlJsonReader.CheckArray(array, offset, count); writer.WriteAttributeString(string.Empty, "type", string.Empty, "array"); for (int i = 0; i < count; i++) { writer.WriteStartElement("item", string.Empty); writer.WriteAttributeString(string.Empty, "type", string.Empty, "number"); writer.WriteValue(array[offset + i]); writer.WriteEndElement(); } } protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, byte[] array, int offset, int count) { XmlJsonReader.CheckArray(array, offset, count); int i; for (i = 0; i < count; i++) { if (!reader.IsStartElement("item", string.Empty)) { break; } array[offset + i] = ToByte(reader.ReadElementContentAsInt()); } return i; } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, byte[] array, int offset, int count) { WriteArray(writer, array, offset, count); } private void ThrowConversionException(string value, string type) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("The value '{0}' cannot be parsed as the type '{1}'.", value, type))); } private byte ToByte(int value) { if (value < 0 || value > 255) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "Byte"); } return (byte)value; } } [TypeForwardedFrom("System.ServiceModel.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public sealed class DataContractJsonSerializer : XmlObjectSerializer { internal IList knownTypeList; internal Dictionary knownDataContracts; private EmitTypeInformation emitTypeInformation; private IDataContractSurrogate dataContractSurrogate; private bool ignoreExtensionDataObject; private ReadOnlyCollection knownTypeCollection; private int maxItemsInObjectGraph; private DataContract rootContract; private XmlDictionaryString rootName; private bool rootNameRequiresMapping; private Type rootType; private bool serializeReadOnlyTypes; private DateTimeFormat dateTimeFormat; private bool useSimpleDictionaryFormat; public IDataContractSurrogate DataContractSurrogate => dataContractSurrogate; public bool IgnoreExtensionDataObject => ignoreExtensionDataObject; public ReadOnlyCollection KnownTypes { get { if (knownTypeCollection == null) { if (knownTypeList != null) { knownTypeCollection = new ReadOnlyCollection(knownTypeList); } else { knownTypeCollection = new ReadOnlyCollection(Globals.EmptyTypeArray); } } return knownTypeCollection; } } internal override Dictionary KnownDataContracts { get { if (knownDataContracts == null && knownTypeList != null) { knownDataContracts = XmlObjectSerializerContext.GetDataContractsForKnownTypes(knownTypeList); } return knownDataContracts; } } public int MaxItemsInObjectGraph => maxItemsInObjectGraph; internal bool AlwaysEmitTypeInformation => emitTypeInformation == EmitTypeInformation.Always; public EmitTypeInformation EmitTypeInformation => emitTypeInformation; public bool SerializeReadOnlyTypes => serializeReadOnlyTypes; public DateTimeFormat DateTimeFormat => dateTimeFormat; public bool UseSimpleDictionaryFormat => useSimpleDictionaryFormat; private DataContract RootContract { get { if (rootContract == null) { rootContract = DataContract.GetDataContract((dataContractSurrogate == null) ? rootType : DataContractSerializer.GetSurrogatedType(dataContractSurrogate, rootType)); CheckIfTypeIsReference(rootContract); } return rootContract; } } private XmlDictionaryString RootName => rootName ?? JsonGlobals.rootDictionaryString; public DataContractJsonSerializer(Type type) : this(type, (IEnumerable)null) { } public DataContractJsonSerializer(Type type, string rootName) : this(type, rootName, null) { } public DataContractJsonSerializer(Type type, XmlDictionaryString rootName) : this(type, rootName, null) { } public DataContractJsonSerializer(Type type, IEnumerable knownTypes) : this(type, knownTypes, int.MaxValue, ignoreExtensionDataObject: false, null, alwaysEmitTypeInformation: false) { } public DataContractJsonSerializer(Type type, string rootName, IEnumerable knownTypes) : this(type, rootName, knownTypes, int.MaxValue, ignoreExtensionDataObject: false, null, alwaysEmitTypeInformation: false) { } public DataContractJsonSerializer(Type type, XmlDictionaryString rootName, IEnumerable knownTypes) : this(type, rootName, knownTypes, int.MaxValue, ignoreExtensionDataObject: false, null, alwaysEmitTypeInformation: false) { } public DataContractJsonSerializer(Type type, IEnumerable knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, IDataContractSurrogate dataContractSurrogate, bool alwaysEmitTypeInformation) { Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, dataContractSurrogate, alwaysEmitTypeInformation ? EmitTypeInformation.Always : EmitTypeInformation.AsNeeded, serializeReadOnlyTypes: false, null, useSimpleDictionaryFormat: false); } public DataContractJsonSerializer(Type type, string rootName, IEnumerable knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, IDataContractSurrogate dataContractSurrogate, bool alwaysEmitTypeInformation) { EmitTypeInformation emitTypeInformation = (alwaysEmitTypeInformation ? EmitTypeInformation.Always : EmitTypeInformation.AsNeeded); XmlDictionary xmlDictionary = new XmlDictionary(2); Initialize(type, xmlDictionary.Add(rootName), knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, dataContractSurrogate, emitTypeInformation, serializeReadOnlyTypes: false, null, useSimpleDictionaryFormat: false); } public DataContractJsonSerializer(Type type, XmlDictionaryString rootName, IEnumerable knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, IDataContractSurrogate dataContractSurrogate, bool alwaysEmitTypeInformation) { Initialize(type, rootName, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, dataContractSurrogate, alwaysEmitTypeInformation ? EmitTypeInformation.Always : EmitTypeInformation.AsNeeded, serializeReadOnlyTypes: false, null, useSimpleDictionaryFormat: false); } public DataContractJsonSerializer(Type type, DataContractJsonSerializerSettings settings) { if (settings == null) { settings = new DataContractJsonSerializerSettings(); } Initialize(type, (settings.RootName == null) ? null : new XmlDictionary(1).Add(settings.RootName), settings.KnownTypes, settings.MaxItemsInObjectGraph, settings.IgnoreExtensionDataObject, settings.DataContractSurrogate, settings.EmitTypeInformation, settings.SerializeReadOnlyTypes, settings.DateTimeFormat, settings.UseSimpleDictionaryFormat); } public override bool IsStartObject(XmlReader reader) { return IsStartObjectHandleExceptions(new JsonReaderDelegator(reader)); } public override bool IsStartObject(XmlDictionaryReader reader) { return IsStartObjectHandleExceptions(new JsonReaderDelegator(reader)); } public override object ReadObject(Stream stream) { XmlObjectSerializer.CheckNull(stream, "stream"); return ReadObject(JsonReaderWriterFactory.CreateJsonReader(stream, XmlDictionaryReaderQuotas.Max)); } public override object ReadObject(XmlReader reader) { return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, DateTimeFormat), verifyObjectName: true); } public override object ReadObject(XmlReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, DateTimeFormat), verifyObjectName); } public override object ReadObject(XmlDictionaryReader reader) { return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, DateTimeFormat), verifyObjectName: true); } public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, DateTimeFormat), verifyObjectName); } public override void WriteEndObject(XmlWriter writer) { WriteEndObjectHandleExceptions(new JsonWriterDelegator(writer)); } public override void WriteEndObject(XmlDictionaryWriter writer) { WriteEndObjectHandleExceptions(new JsonWriterDelegator(writer)); } public override void WriteObject(Stream stream, object graph) { XmlObjectSerializer.CheckNull(stream, "stream"); XmlDictionaryWriter xmlDictionaryWriter = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8, ownsStream: false); WriteObject(xmlDictionaryWriter, graph); xmlDictionaryWriter.Flush(); } public override void WriteObject(XmlWriter writer, object graph) { WriteObjectHandleExceptions(new JsonWriterDelegator(writer, DateTimeFormat), graph); } public override void WriteObject(XmlDictionaryWriter writer, object graph) { WriteObjectHandleExceptions(new JsonWriterDelegator(writer, DateTimeFormat), graph); } public override void WriteObjectContent(XmlWriter writer, object graph) { WriteObjectContentHandleExceptions(new JsonWriterDelegator(writer, DateTimeFormat), graph); } public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) { WriteObjectContentHandleExceptions(new JsonWriterDelegator(writer, DateTimeFormat), graph); } public override void WriteStartObject(XmlWriter writer, object graph) { WriteStartObjectHandleExceptions(new JsonWriterDelegator(writer), graph); } public override void WriteStartObject(XmlDictionaryWriter writer, object graph) { WriteStartObjectHandleExceptions(new JsonWriterDelegator(writer), graph); } internal static bool CheckIfJsonNameRequiresMapping(string jsonName) { if (jsonName != null) { if (!DataContract.IsValidNCName(jsonName)) { return true; } for (int i = 0; i < jsonName.Length; i++) { if (XmlJsonWriter.CharacterNeedsEscaping(jsonName[i])) { return true; } } } return false; } internal static bool CheckIfJsonNameRequiresMapping(XmlDictionaryString jsonName) { if (jsonName != null) { return CheckIfJsonNameRequiresMapping(jsonName.Value); } return false; } internal static bool CheckIfXmlNameRequiresMapping(string xmlName) { if (xmlName != null) { return CheckIfJsonNameRequiresMapping(ConvertXmlNameToJsonName(xmlName)); } return false; } internal static bool CheckIfXmlNameRequiresMapping(XmlDictionaryString xmlName) { if (xmlName != null) { return CheckIfXmlNameRequiresMapping(xmlName.Value); } return false; } internal static string ConvertXmlNameToJsonName(string xmlName) { return XmlConvert.DecodeName(xmlName); } internal static XmlDictionaryString ConvertXmlNameToJsonName(XmlDictionaryString xmlName) { if (xmlName != null) { return new XmlDictionary().Add(ConvertXmlNameToJsonName(xmlName.Value)); } return null; } internal static bool IsJsonLocalName(XmlReaderDelegator reader, string elementName) { if (XmlObjectSerializerReadContextComplexJson.TryGetJsonLocalName(reader, out var name)) { return elementName == name; } return false; } internal static object ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context) { return JsonDataContract.GetJsonDataContract(contract).ReadJsonValue(reader, context); } internal static void WriteJsonNull(XmlWriterDelegator writer) { writer.WriteAttributeString(null, "type", null, "null"); } internal static void WriteJsonValue(JsonDataContract contract, XmlWriterDelegator writer, object graph, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { contract.WriteJsonValue(writer, graph, context, declaredTypeHandle); } internal override Type GetDeserializeType() { return rootType; } internal override Type GetSerializeType(object graph) { if (graph != null) { return graph.GetType(); } return rootType; } internal override bool InternalIsStartObject(XmlReaderDelegator reader) { if (IsRootElement(reader, RootContract, RootName, XmlDictionaryString.Empty)) { return true; } return IsJsonLocalName(reader, RootName.Value); } internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName) { if (MaxItemsInObjectGraph == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Maximum number of items that can be serialized or deserialized in an object graph is '{0}'.", MaxItemsInObjectGraph))); } if (verifyObjectName) { if (!InternalIsStartObject(xmlReader)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.GetString("Expecting element '{1}' from namespace '{0}'.", XmlDictionaryString.Empty, RootName), xmlReader)); } } else if (!IsStartElement(xmlReader)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.GetString("Expecting state '{0}' when ReadObject is called.", XmlNodeType.Element), xmlReader)); } DataContract dataContract = RootContract; if (dataContract.IsPrimitive && (object)dataContract.UnderlyingType == rootType) { return ReadJsonValue(dataContract, xmlReader, null); } return XmlObjectSerializerReadContextComplexJson.CreateContext(this, dataContract).InternalDeserialize(xmlReader, rootType, dataContract, null, null); } internal override void InternalWriteEndObject(XmlWriterDelegator writer) { writer.WriteEndElement(); } internal override void InternalWriteObject(XmlWriterDelegator writer, object graph) { InternalWriteStartObject(writer, graph); InternalWriteObjectContent(writer, graph); InternalWriteEndObject(writer); } internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph) { if (MaxItemsInObjectGraph == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Maximum number of items that can be serialized or deserialized in an object graph is '{0}'.", MaxItemsInObjectGraph))); } DataContract dataContract = RootContract; Type underlyingType = dataContract.UnderlyingType; Type objType = ((graph == null) ? underlyingType : graph.GetType()); if (dataContractSurrogate != null) { graph = DataContractSerializer.SurrogateToDataContractType(dataContractSurrogate, graph, underlyingType, ref objType); } if (graph == null) { WriteJsonNull(writer); return; } if (underlyingType == objType) { if (dataContract.CanContainReferences) { XmlObjectSerializerWriteContextComplexJson xmlObjectSerializerWriteContextComplexJson = XmlObjectSerializerWriteContextComplexJson.CreateContext(this, dataContract); xmlObjectSerializerWriteContextComplexJson.OnHandleReference(writer, graph, canContainCyclicReference: true); xmlObjectSerializerWriteContextComplexJson.SerializeWithoutXsiType(dataContract, writer, graph, underlyingType.TypeHandle); } else { WriteJsonValue(JsonDataContract.GetJsonDataContract(dataContract), writer, graph, null, underlyingType.TypeHandle); } return; } XmlObjectSerializerWriteContextComplexJson xmlObjectSerializerWriteContextComplexJson2 = XmlObjectSerializerWriteContextComplexJson.CreateContext(this, RootContract); dataContract = GetDataContract(dataContract, underlyingType, objType); if (dataContract.CanContainReferences) { xmlObjectSerializerWriteContextComplexJson2.OnHandleReference(writer, graph, canContainCyclicReference: true); xmlObjectSerializerWriteContextComplexJson2.SerializeWithXsiTypeAtTopLevel(dataContract, writer, graph, underlyingType.TypeHandle, objType); } else { xmlObjectSerializerWriteContextComplexJson2.SerializeWithoutXsiType(dataContract, writer, graph, underlyingType.TypeHandle); } } internal override void InternalWriteStartObject(XmlWriterDelegator writer, object graph) { if (rootNameRequiresMapping) { writer.WriteStartElement("a", "item", "item"); writer.WriteAttributeString(null, "item", null, RootName.Value); } else { writer.WriteStartElement(RootName, XmlDictionaryString.Empty); } } private void AddCollectionItemTypeToKnownTypes(Type knownType) { Type type = knownType; Type itemType; while (CollectionDataContract.IsCollection(type, out itemType)) { if (itemType.IsGenericType && itemType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue) { itemType = Globals.TypeOfKeyValuePair.MakeGenericType(itemType.GetGenericArguments()); } knownTypeList.Add(itemType); type = itemType; } } private void Initialize(Type type, IEnumerable knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, IDataContractSurrogate dataContractSurrogate, EmitTypeInformation emitTypeInformation, bool serializeReadOnlyTypes, DateTimeFormat dateTimeFormat, bool useSimpleDictionaryFormat) { XmlObjectSerializer.CheckNull(type, "type"); rootType = type; if (knownTypes != null) { knownTypeList = new List(); foreach (Type knownType in knownTypes) { knownTypeList.Add(knownType); if (knownType != null) { AddCollectionItemTypeToKnownTypes(knownType); } } } if (maxItemsInObjectGraph < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxItemsInObjectGraph", SR.GetString("The value of this argument must be non-negative."))); } this.maxItemsInObjectGraph = maxItemsInObjectGraph; this.ignoreExtensionDataObject = ignoreExtensionDataObject; this.dataContractSurrogate = dataContractSurrogate; this.emitTypeInformation = emitTypeInformation; this.serializeReadOnlyTypes = serializeReadOnlyTypes; this.dateTimeFormat = dateTimeFormat; this.useSimpleDictionaryFormat = useSimpleDictionaryFormat; } private void Initialize(Type type, XmlDictionaryString rootName, IEnumerable knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, IDataContractSurrogate dataContractSurrogate, EmitTypeInformation emitTypeInformation, bool serializeReadOnlyTypes, DateTimeFormat dateTimeFormat, bool useSimpleDictionaryFormat) { Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, dataContractSurrogate, emitTypeInformation, serializeReadOnlyTypes, dateTimeFormat, useSimpleDictionaryFormat); this.rootName = ConvertXmlNameToJsonName(rootName); rootNameRequiresMapping = CheckIfJsonNameRequiresMapping(this.rootName); } internal static void CheckIfTypeIsReference(DataContract dataContract) { if (dataContract.IsReference) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Unsupported value for IsReference for type '{0}', IsReference value is {1}.", DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.IsReference))); } } internal static DataContract GetDataContract(DataContract declaredTypeContract, Type declaredType, Type objectType) { DataContract dataContract = DataContractSerializer.GetDataContract(declaredTypeContract, declaredType, objectType); CheckIfTypeIsReference(dataContract); return dataContract; } } public class DataContractJsonSerializerSettings { private int maxItemsInObjectGraph = int.MaxValue; public string RootName { get; set; } public IEnumerable KnownTypes { get; set; } public int MaxItemsInObjectGraph { get { return maxItemsInObjectGraph; } set { maxItemsInObjectGraph = value; } } public bool IgnoreExtensionDataObject { get; set; } public IDataContractSurrogate DataContractSurrogate { get; set; } public EmitTypeInformation EmitTypeInformation { get; set; } public DateTimeFormat DateTimeFormat { get; set; } public bool SerializeReadOnlyTypes { get; set; } public bool UseSimpleDictionaryFormat { get; set; } } [TypeForwardedFrom("System.ServiceModel.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public interface IXmlJsonReaderInitializer { void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose); void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose); } [TypeForwardedFrom("System.ServiceModel.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public interface IXmlJsonWriterInitializer { void SetOutput(Stream stream, Encoding encoding, bool ownsStream); } internal class JsonByteArrayDataContract : JsonDataContract { public JsonByteArrayDataContract(ByteArrayDataContract traditionalByteArrayDataContract) : base(traditionalByteArrayDataContract) { } public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { if (context == null) { if (!JsonDataContract.TryReadNullAtTopLevel(jsonReader)) { return jsonReader.ReadElementContentAsBase64(); } return null; } return JsonDataContract.HandleReadValue(jsonReader.ReadElementContentAsBase64(), context); } } internal class JsonClassDataContract : JsonDataContract { private class JsonClassDataContractCriticalHelper : JsonDataContractCriticalHelper { private JsonFormatClassReaderDelegate jsonFormatReaderDelegate; private JsonFormatClassWriterDelegate jsonFormatWriterDelegate; private XmlDictionaryString[] memberNames; private ClassDataContract traditionalClassDataContract; private string typeName; internal JsonFormatClassReaderDelegate JsonFormatReaderDelegate { get { return jsonFormatReaderDelegate; } set { jsonFormatReaderDelegate = value; } } internal JsonFormatClassWriterDelegate JsonFormatWriterDelegate { get { return jsonFormatWriterDelegate; } set { jsonFormatWriterDelegate = value; } } internal XmlDictionaryString[] MemberNames => memberNames; internal ClassDataContract TraditionalClassDataContract => traditionalClassDataContract; public JsonClassDataContractCriticalHelper(ClassDataContract traditionalDataContract) : base(traditionalDataContract) { typeName = (string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : (traditionalDataContract.Name.Value + ":" + XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value))); traditionalClassDataContract = traditionalDataContract; CopyMembersAndCheckDuplicateNames(); } private void CopyMembersAndCheckDuplicateNames() { if (traditionalClassDataContract.MemberNames == null) { return; } int num = traditionalClassDataContract.MemberNames.Length; Dictionary dictionary = new Dictionary(num); XmlDictionaryString[] array = new XmlDictionaryString[num]; for (int i = 0; i < num; i++) { if (dictionary.ContainsKey(traditionalClassDataContract.MemberNames[i].Value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString("Duplicate member, including '{1}', is found in JSON input, in type '{0}'.", DataContract.GetClrTypeFullName(traditionalClassDataContract.UnderlyingType), traditionalClassDataContract.MemberNames[i].Value))); } dictionary.Add(traditionalClassDataContract.MemberNames[i].Value, null); array[i] = DataContractJsonSerializer.ConvertXmlNameToJsonName(traditionalClassDataContract.MemberNames[i]); } memberNames = array; } } [SecurityCritical] private JsonClassDataContractCriticalHelper helper; internal JsonFormatClassReaderDelegate JsonFormatReaderDelegate { [SecuritySafeCritical] get { if (helper.JsonFormatReaderDelegate == null) { lock (this) { if (helper.JsonFormatReaderDelegate == null) { if (TraditionalClassDataContract.IsReadOnlyContract) { DataContract.ThrowInvalidDataContractException(TraditionalClassDataContract.DeserializationExceptionMessage, null); } JsonFormatClassReaderDelegate jsonFormatReaderDelegate = new JsonFormatReaderGenerator().GenerateClassReader(TraditionalClassDataContract); Thread.MemoryBarrier(); helper.JsonFormatReaderDelegate = jsonFormatReaderDelegate; } } } return helper.JsonFormatReaderDelegate; } } internal JsonFormatClassWriterDelegate JsonFormatWriterDelegate { [SecuritySafeCritical] get { if (helper.JsonFormatWriterDelegate == null) { lock (this) { if (helper.JsonFormatWriterDelegate == null) { JsonFormatClassWriterDelegate jsonFormatWriterDelegate = new JsonFormatWriterGenerator().GenerateClassWriter(TraditionalClassDataContract); Thread.MemoryBarrier(); helper.JsonFormatWriterDelegate = jsonFormatWriterDelegate; } } } return helper.JsonFormatWriterDelegate; } } internal XmlDictionaryString[] MemberNames { [SecuritySafeCritical] get { return helper.MemberNames; } } internal override string TypeName { [SecuritySafeCritical] get { return helper.TypeName; } } private ClassDataContract TraditionalClassDataContract { [SecuritySafeCritical] get { return helper.TraditionalClassDataContract; } } [SecuritySafeCritical] public JsonClassDataContract(ClassDataContract traditionalDataContract) : base(new JsonClassDataContractCriticalHelper(traditionalDataContract)) { helper = base.Helper as JsonClassDataContractCriticalHelper; } public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { jsonReader.Read(); object result = JsonFormatReaderDelegate(jsonReader, context, XmlDictionaryString.Empty, MemberNames); jsonReader.ReadEndElement(); return result; } public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { jsonWriter.WriteAttributeString(null, "type", null, "object"); JsonFormatWriterDelegate(jsonWriter, obj, context, TraditionalClassDataContract, MemberNames); } } internal class JsonCollectionDataContract : JsonDataContract { private class JsonCollectionDataContractCriticalHelper : JsonDataContractCriticalHelper { private JsonFormatCollectionReaderDelegate jsonFormatReaderDelegate; private JsonFormatGetOnlyCollectionReaderDelegate jsonFormatGetOnlyReaderDelegate; private JsonFormatCollectionWriterDelegate jsonFormatWriterDelegate; private CollectionDataContract traditionalCollectionDataContract; internal JsonFormatCollectionReaderDelegate JsonFormatReaderDelegate { get { return jsonFormatReaderDelegate; } set { jsonFormatReaderDelegate = value; } } internal JsonFormatGetOnlyCollectionReaderDelegate JsonFormatGetOnlyReaderDelegate { get { return jsonFormatGetOnlyReaderDelegate; } set { jsonFormatGetOnlyReaderDelegate = value; } } internal JsonFormatCollectionWriterDelegate JsonFormatWriterDelegate { get { return jsonFormatWriterDelegate; } set { jsonFormatWriterDelegate = value; } } internal CollectionDataContract TraditionalCollectionDataContract => traditionalCollectionDataContract; public JsonCollectionDataContractCriticalHelper(CollectionDataContract traditionalDataContract) : base(traditionalDataContract) { traditionalCollectionDataContract = traditionalDataContract; } } [SecurityCritical] private JsonCollectionDataContractCriticalHelper helper; internal JsonFormatCollectionReaderDelegate JsonFormatReaderDelegate { [SecuritySafeCritical] get { if (helper.JsonFormatReaderDelegate == null) { lock (this) { if (helper.JsonFormatReaderDelegate == null) { if (TraditionalCollectionDataContract.IsReadOnlyContract) { DataContract.ThrowInvalidDataContractException(TraditionalCollectionDataContract.DeserializationExceptionMessage, null); } JsonFormatCollectionReaderDelegate jsonFormatReaderDelegate = new JsonFormatReaderGenerator().GenerateCollectionReader(TraditionalCollectionDataContract); Thread.MemoryBarrier(); helper.JsonFormatReaderDelegate = jsonFormatReaderDelegate; } } } return helper.JsonFormatReaderDelegate; } } internal JsonFormatGetOnlyCollectionReaderDelegate JsonFormatGetOnlyReaderDelegate { [SecuritySafeCritical] get { if (helper.JsonFormatGetOnlyReaderDelegate == null) { lock (this) { if (helper.JsonFormatGetOnlyReaderDelegate == null) { CollectionKind kind = TraditionalCollectionDataContract.Kind; if (base.TraditionalDataContract.UnderlyingType.IsInterface && (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString("On type '{0}', get-only collection must have an Add method.", DataContract.GetClrTypeFullName(base.TraditionalDataContract.UnderlyingType)))); } if (TraditionalCollectionDataContract.IsReadOnlyContract) { DataContract.ThrowInvalidDataContractException(TraditionalCollectionDataContract.DeserializationExceptionMessage, null); } JsonFormatGetOnlyCollectionReaderDelegate jsonFormatGetOnlyReaderDelegate = new JsonFormatReaderGenerator().GenerateGetOnlyCollectionReader(TraditionalCollectionDataContract); Thread.MemoryBarrier(); helper.JsonFormatGetOnlyReaderDelegate = jsonFormatGetOnlyReaderDelegate; } } } return helper.JsonFormatGetOnlyReaderDelegate; } } internal JsonFormatCollectionWriterDelegate JsonFormatWriterDelegate { [SecuritySafeCritical] get { if (helper.JsonFormatWriterDelegate == null) { lock (this) { if (helper.JsonFormatWriterDelegate == null) { JsonFormatCollectionWriterDelegate jsonFormatWriterDelegate = new JsonFormatWriterGenerator().GenerateCollectionWriter(TraditionalCollectionDataContract); Thread.MemoryBarrier(); helper.JsonFormatWriterDelegate = jsonFormatWriterDelegate; } } } return helper.JsonFormatWriterDelegate; } } private CollectionDataContract TraditionalCollectionDataContract { [SecuritySafeCritical] get { return helper.TraditionalCollectionDataContract; } } [SecuritySafeCritical] public JsonCollectionDataContract(CollectionDataContract traditionalDataContract) : base(new JsonCollectionDataContractCriticalHelper(traditionalDataContract)) { helper = base.Helper as JsonCollectionDataContractCriticalHelper; } public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { jsonReader.Read(); object result = null; if (context.IsGetOnlyCollection) { context.IsGetOnlyCollection = false; JsonFormatGetOnlyReaderDelegate(jsonReader, context, XmlDictionaryString.Empty, JsonGlobals.itemDictionaryString, TraditionalCollectionDataContract); } else { result = JsonFormatReaderDelegate(jsonReader, context, XmlDictionaryString.Empty, JsonGlobals.itemDictionaryString, TraditionalCollectionDataContract); } jsonReader.ReadEndElement(); return result; } public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { context.IsGetOnlyCollection = false; JsonFormatWriterDelegate(jsonWriter, obj, context, TraditionalCollectionDataContract); } } internal class JsonDataContract { internal class JsonDataContractCriticalHelper { private static object cacheLock = new object(); private static object createDataContractLock = new object(); private static JsonDataContract[] dataContractCache = new JsonDataContract[32]; private static int dataContractID = 0; private static TypeHandleRef typeHandleRef = new TypeHandleRef(); private static Dictionary typeToIDCache = new Dictionary(new TypeHandleRefEqualityComparer()); private Dictionary knownDataContracts; private DataContract traditionalDataContract; private string typeName; internal Dictionary KnownDataContracts => knownDataContracts; internal DataContract TraditionalDataContract => traditionalDataContract; internal virtual string TypeName => typeName; internal JsonDataContractCriticalHelper(DataContract traditionalDataContract) { this.traditionalDataContract = traditionalDataContract; AddCollectionItemContractsToKnownDataContracts(); typeName = (string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : (traditionalDataContract.Name.Value + ":" + XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value))); } public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract) { int id = GetId(traditionalDataContract.UnderlyingType.TypeHandle); JsonDataContract jsonDataContract = dataContractCache[id]; if (jsonDataContract == null) { jsonDataContract = CreateJsonDataContract(id, traditionalDataContract); dataContractCache[id] = jsonDataContract; } return jsonDataContract; } internal static int GetId(RuntimeTypeHandle typeHandle) { lock (cacheLock) { typeHandleRef.Value = typeHandle; if (!typeToIDCache.TryGetValue(typeHandleRef, out var value)) { int num = dataContractID++; if (num >= dataContractCache.Length) { int num2 = ((num < 1073741823) ? (num * 2) : int.MaxValue); if (num2 <= num) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString("An internal error has occurred. DataContract cache overflow."))); } Array.Resize(ref dataContractCache, num2); } value = new IntRef(num); try { typeToIDCache.Add(new TypeHandleRef(typeHandle), value); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } } return value.Value; } } private static JsonDataContract CreateJsonDataContract(int id, DataContract traditionalDataContract) { lock (createDataContractLock) { JsonDataContract jsonDataContract = dataContractCache[id]; if (jsonDataContract == null) { Type type = traditionalDataContract.GetType(); if (type == typeof(ObjectDataContract)) { jsonDataContract = new JsonObjectDataContract(traditionalDataContract); } else if (type == typeof(StringDataContract)) { jsonDataContract = new JsonStringDataContract((StringDataContract)traditionalDataContract); } else if (type == typeof(UriDataContract)) { jsonDataContract = new JsonUriDataContract((UriDataContract)traditionalDataContract); } else if (type == typeof(QNameDataContract)) { jsonDataContract = new JsonQNameDataContract((QNameDataContract)traditionalDataContract); } else if (type == typeof(ByteArrayDataContract)) { jsonDataContract = new JsonByteArrayDataContract((ByteArrayDataContract)traditionalDataContract); } else if (traditionalDataContract.IsPrimitive || traditionalDataContract.UnderlyingType == Globals.TypeOfXmlQualifiedName) { jsonDataContract = new JsonDataContract(traditionalDataContract); } else if (type == typeof(ClassDataContract)) { jsonDataContract = new JsonClassDataContract((ClassDataContract)traditionalDataContract); } else if (type == typeof(EnumDataContract)) { jsonDataContract = new JsonEnumDataContract((EnumDataContract)traditionalDataContract); } else if (type == typeof(GenericParameterDataContract) || type == typeof(SpecialTypeDataContract)) { jsonDataContract = new JsonDataContract(traditionalDataContract); } else if (type == typeof(CollectionDataContract)) { jsonDataContract = new JsonCollectionDataContract((CollectionDataContract)traditionalDataContract); } else { if (!(type == typeof(XmlDataContract))) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("traditionalDataContract", SR.GetString("Type '{0}' is not suppotred by DataContractJsonSerializer.", traditionalDataContract.UnderlyingType)); } jsonDataContract = new JsonXmlDataContract((XmlDataContract)traditionalDataContract); } } return jsonDataContract; } } private void AddCollectionItemContractsToKnownDataContracts() { if (traditionalDataContract.KnownDataContracts == null) { return; } foreach (KeyValuePair knownDataContract in traditionalDataContract.KnownDataContracts) { if ((object)knownDataContract == null) { continue; } CollectionDataContract collectionDataContract = knownDataContract.Value as CollectionDataContract; while (collectionDataContract != null) { DataContract itemContract = collectionDataContract.ItemContract; if (knownDataContracts == null) { knownDataContracts = new Dictionary(); } if (!knownDataContracts.ContainsKey(itemContract.StableName)) { knownDataContracts.Add(itemContract.StableName, itemContract); } if (collectionDataContract.ItemType.IsGenericType && collectionDataContract.ItemType.GetGenericTypeDefinition() == typeof(KeyValue<, >)) { DataContract dataContract = DataContract.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionDataContract.ItemType.GetGenericArguments())); if (!knownDataContracts.ContainsKey(dataContract.StableName)) { knownDataContracts.Add(dataContract.StableName, dataContract); } } if (!(itemContract is CollectionDataContract)) { break; } collectionDataContract = itemContract as CollectionDataContract; } } } } [SecurityCritical] private JsonDataContractCriticalHelper helper; internal virtual string TypeName => null; protected JsonDataContractCriticalHelper Helper { [SecurityCritical] get { return helper; } } protected DataContract TraditionalDataContract { [SecuritySafeCritical] get { return helper.TraditionalDataContract; } } private Dictionary KnownDataContracts { [SecuritySafeCritical] get { return helper.KnownDataContracts; } } [SecuritySafeCritical] protected JsonDataContract(DataContract traditionalDataContract) { helper = new JsonDataContractCriticalHelper(traditionalDataContract); } [SecuritySafeCritical] protected JsonDataContract(JsonDataContractCriticalHelper helper) { this.helper = helper; } [SecuritySafeCritical] public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract) { return JsonDataContractCriticalHelper.GetJsonDataContract(traditionalDataContract); } public object ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { PushKnownDataContracts(context); object result = ReadJsonValueCore(jsonReader, context); PopKnownDataContracts(context); return result; } public virtual object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { return TraditionalDataContract.ReadXmlValue(jsonReader, context); } public void WriteJsonValue(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { PushKnownDataContracts(context); WriteJsonValueCore(jsonWriter, obj, context, declaredTypeHandle); PopKnownDataContracts(context); } public virtual void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { TraditionalDataContract.WriteXmlValue(jsonWriter, obj, context); } protected static object HandleReadValue(object obj, XmlObjectSerializerReadContext context) { context.AddNewObject(obj); return obj; } protected static bool TryReadNullAtTopLevel(XmlReaderDelegator reader) { if (reader.MoveToAttribute("type") && reader.Value == "null") { reader.Skip(); reader.MoveToElement(); return true; } reader.MoveToElement(); return false; } protected void PopKnownDataContracts(XmlObjectSerializerContext context) { if (KnownDataContracts != null) { context.scopedKnownTypes.Pop(); } } protected void PushKnownDataContracts(XmlObjectSerializerContext context) { if (KnownDataContracts != null) { context.scopedKnownTypes.Push(KnownDataContracts); } } } internal class JsonEncodingStreamWrapper : Stream { private enum SupportedEncoding { UTF8, UTF16LE, UTF16BE, None } private static readonly UnicodeEncoding SafeBEUTF16 = new UnicodeEncoding(bigEndian: true, byteOrderMark: false, throwOnInvalidBytes: false); private static readonly UnicodeEncoding SafeUTF16 = new UnicodeEncoding(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: false); private static readonly UTF8Encoding SafeUTF8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false); private static readonly UnicodeEncoding ValidatingBEUTF16 = new UnicodeEncoding(bigEndian: true, byteOrderMark: false, throwOnInvalidBytes: true); private static readonly UnicodeEncoding ValidatingUTF16 = new UnicodeEncoding(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: true); private static readonly UTF8Encoding ValidatingUTF8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); private const int BufferLength = 128; private byte[] byteBuffer = new byte[1]; private int byteCount; private int byteOffset; private byte[] bytes; private char[] chars; private Decoder dec; private Encoder enc; private Encoding encoding; private SupportedEncoding encodingCode; private bool isReading; private Stream stream; public override bool CanRead { get { if (!isReading) { return false; } return stream.CanRead; } } public override bool CanSeek => false; public override bool CanTimeout => stream.CanTimeout; public override bool CanWrite { get { if (isReading) { return false; } return stream.CanWrite; } } public override long Length => stream.Length; public override long Position { get { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } set { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } } public override int ReadTimeout { get { return stream.ReadTimeout; } set { stream.ReadTimeout = value; } } public override int WriteTimeout { get { return stream.WriteTimeout; } set { stream.WriteTimeout = value; } } public JsonEncodingStreamWrapper(Stream stream, Encoding encoding, bool isReader) { isReading = isReader; if (isReader) { InitForReading(stream, encoding); return; } if (encoding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encoding"); } InitForWriting(stream, encoding); } public static ArraySegment ProcessBuffer(byte[] buffer, int offset, int count, Encoding encoding) { try { SupportedEncoding supportedEncoding = GetSupportedEncoding(encoding); SupportedEncoding supportedEncoding2 = ((count >= 2) ? ReadEncoding(buffer[offset], buffer[offset + 1]) : SupportedEncoding.UTF8); if (supportedEncoding != SupportedEncoding.None && supportedEncoding != supportedEncoding2) { ThrowExpectedEncodingMismatch(supportedEncoding, supportedEncoding2); } if (supportedEncoding2 == SupportedEncoding.UTF8) { return new ArraySegment(buffer, offset, count); } return new ArraySegment(ValidatingUTF8.GetBytes(GetEncoding(supportedEncoding2).GetChars(buffer, offset, count))); } catch (DecoderFallbackException innerException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Invalid bytes in JSON."), innerException)); } } public override void Close() { Flush(); base.Close(); stream.Close(); } public override void Flush() { stream.Flush(); } public override int Read(byte[] buffer, int offset, int count) { try { if (byteCount == 0) { if (encodingCode == SupportedEncoding.UTF8) { return stream.Read(buffer, offset, count); } byteOffset = 0; byteCount = stream.Read(bytes, byteCount, (chars.Length - 1) * 2); if (byteCount == 0) { return 0; } CleanupCharBreak(); int charCount = encoding.GetChars(bytes, 0, byteCount, chars, 0); byteCount = Encoding.UTF8.GetBytes(chars, 0, charCount, bytes, 0); } if (byteCount < count) { count = byteCount; } Buffer.BlockCopy(bytes, byteOffset, buffer, offset, count); byteOffset += count; byteCount -= count; return count; } catch (DecoderFallbackException innerException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Invalid bytes in JSON."), innerException)); } } public override int ReadByte() { if (byteCount == 0 && encodingCode == SupportedEncoding.UTF8) { return stream.ReadByte(); } if (Read(byteBuffer, 0, 1) == 0) { return -1; } return byteBuffer[0]; } public override long Seek(long offset, SeekOrigin origin) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } public override void SetLength(long value) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } public override void Write(byte[] buffer, int offset, int count) { if (encodingCode == SupportedEncoding.UTF8) { stream.Write(buffer, offset, count); return; } while (count > 0) { int num = ((chars.Length < count) ? chars.Length : count); int charCount = dec.GetChars(buffer, offset, num, chars, 0, flush: false); byteCount = enc.GetBytes(chars, 0, charCount, bytes, 0, flush: false); stream.Write(bytes, 0, byteCount); offset += num; count -= num; } } public override void WriteByte(byte b) { if (encodingCode == SupportedEncoding.UTF8) { stream.WriteByte(b); return; } byteBuffer[0] = b; Write(byteBuffer, 0, 1); } private static Encoding GetEncoding(SupportedEncoding e) { return e switch { SupportedEncoding.UTF8 => ValidatingUTF8, SupportedEncoding.UTF16LE => ValidatingUTF16, SupportedEncoding.UTF16BE => ValidatingBEUTF16, _ => throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("JSON Encoding is not supported."))), }; } private static string GetEncodingName(SupportedEncoding enc) { return enc switch { SupportedEncoding.UTF8 => "utf-8", SupportedEncoding.UTF16LE => "utf-16LE", SupportedEncoding.UTF16BE => "utf-16BE", _ => throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("JSON Encoding is not supported."))), }; } private static SupportedEncoding GetSupportedEncoding(Encoding encoding) { if (encoding == null) { return SupportedEncoding.None; } if (encoding.WebName == ValidatingUTF8.WebName) { return SupportedEncoding.UTF8; } if (encoding.WebName == ValidatingUTF16.WebName) { return SupportedEncoding.UTF16LE; } if (encoding.WebName == ValidatingBEUTF16.WebName) { return SupportedEncoding.UTF16BE; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("JSON Encoding is not supported."))); } private static SupportedEncoding ReadEncoding(byte b1, byte b2) { if (b1 == 0 && b2 != 0) { return SupportedEncoding.UTF16BE; } if (b1 != 0 && b2 == 0) { return SupportedEncoding.UTF16LE; } if (b1 == 0 && b2 == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Invalid bytes in JSON."))); } return SupportedEncoding.UTF8; } private static void ThrowExpectedEncodingMismatch(SupportedEncoding expEnc, SupportedEncoding actualEnc) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Expected encoding '{0}', got '{1}' instead.", GetEncodingName(expEnc), GetEncodingName(actualEnc)))); } private void CleanupCharBreak() { int num = byteOffset + byteCount; if (byteCount % 2 != 0) { int num2 = stream.ReadByte(); if (num2 < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Unexpected end of file in JSON."))); } bytes[num++] = (byte)num2; byteCount++; } int num3 = ((encodingCode != SupportedEncoding.UTF16LE) ? (bytes[num - 1] + (bytes[num - 2] << 8)) : (bytes[num - 2] + (bytes[num - 1] << 8))); if ((num3 & 0xDC00) != 56320 && num3 >= 55296 && num3 <= 56319) { int num4 = stream.ReadByte(); int num5 = stream.ReadByte(); if (num5 < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Unexpected end of file in JSON."))); } bytes[num++] = (byte)num4; bytes[num++] = (byte)num5; byteCount += 2; } } private void EnsureBuffers() { EnsureByteBuffer(); if (chars == null) { chars = new char[128]; } } private void EnsureByteBuffer() { if (bytes == null) { bytes = new byte[512]; byteOffset = 0; byteCount = 0; } } private void FillBuffer(int count) { count -= byteCount; while (count > 0) { int num = stream.Read(bytes, byteOffset + byteCount, count); if (num != 0) { byteCount += num; count -= num; continue; } break; } } private void InitForReading(Stream inputStream, Encoding expectedEncoding) { try { stream = new BufferedStream(inputStream); SupportedEncoding supportedEncoding = GetSupportedEncoding(expectedEncoding); SupportedEncoding supportedEncoding2 = ReadEncoding(); if (supportedEncoding != SupportedEncoding.None && supportedEncoding != supportedEncoding2) { ThrowExpectedEncodingMismatch(supportedEncoding, supportedEncoding2); } if (supportedEncoding2 != 0) { EnsureBuffers(); FillBuffer(254); encodingCode = supportedEncoding2; encoding = GetEncoding(supportedEncoding2); CleanupCharBreak(); int charCount = encoding.GetChars(bytes, byteOffset, byteCount, chars, 0); byteOffset = 0; byteCount = ValidatingUTF8.GetBytes(chars, 0, charCount, bytes, 0); } } catch (DecoderFallbackException innerException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Invalid bytes in JSON."), innerException)); } } private void InitForWriting(Stream outputStream, Encoding writeEncoding) { encoding = writeEncoding; stream = new BufferedStream(outputStream); encodingCode = GetSupportedEncoding(writeEncoding); if (encodingCode != 0) { EnsureBuffers(); dec = ValidatingUTF8.GetDecoder(); enc = encoding.GetEncoder(); } } private SupportedEncoding ReadEncoding() { int num = stream.ReadByte(); int num2 = stream.ReadByte(); EnsureByteBuffer(); SupportedEncoding result; if (num == -1) { result = SupportedEncoding.UTF8; byteCount = 0; } else if (num2 == -1) { result = SupportedEncoding.UTF8; bytes[0] = (byte)num; byteCount = 1; } else { result = ReadEncoding((byte)num, (byte)num2); bytes[0] = (byte)num; bytes[1] = (byte)num2; byteCount = 2; } return result; } } internal class JsonEnumDataContract : JsonDataContract { private class JsonEnumDataContractCriticalHelper : JsonDataContractCriticalHelper { private bool isULong; public bool IsULong => isULong; public JsonEnumDataContractCriticalHelper(EnumDataContract traditionalEnumDataContract) : base(traditionalEnumDataContract) { isULong = traditionalEnumDataContract.IsULong; } } [SecurityCritical] private JsonEnumDataContractCriticalHelper helper; public bool IsULong { [SecuritySafeCritical] get { return helper.IsULong; } } [SecuritySafeCritical] public JsonEnumDataContract(EnumDataContract traditionalDataContract) : base(new JsonEnumDataContractCriticalHelper(traditionalDataContract)) { helper = base.Helper as JsonEnumDataContractCriticalHelper; } public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { object obj = ((!IsULong) ? Enum.ToObject(base.TraditionalDataContract.UnderlyingType, jsonReader.ReadElementContentAsLong()) : Enum.ToObject(base.TraditionalDataContract.UnderlyingType, jsonReader.ReadElementContentAsUnsignedLong())); context?.AddNewObject(obj); return obj; } public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { if (IsULong) { jsonWriter.WriteUnsignedLong(((IConvertible)obj).ToUInt64(null)); } else { jsonWriter.WriteLong(((IConvertible)obj).ToInt64(null)); } } } internal delegate object JsonFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[] memberNames); internal delegate object JsonFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract); internal delegate void JsonFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract); internal sealed class JsonFormatReaderGenerator { private class CriticalHelper { internal JsonFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract) { return (XmlReaderDelegator xr, XmlObjectSerializerReadContextComplexJson ctx, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[] memberNames) => new JsonFormatReaderInterpreter(classContract).ReadFromJson(xr, ctx, emptyDictionaryString, memberNames); } internal JsonFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract) { return (XmlReaderDelegator xr, XmlObjectSerializerReadContextComplexJson ctx, XmlDictionaryString emptyDS, XmlDictionaryString inm, CollectionDataContract cc) => new JsonFormatReaderInterpreter(collectionContract, isGetOnly: false).ReadCollectionFromJson(xr, ctx, emptyDS, inm, cc); } internal JsonFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract) { return delegate(XmlReaderDelegator xr, XmlObjectSerializerReadContextComplexJson ctx, XmlDictionaryString emptyDS, XmlDictionaryString inm, CollectionDataContract cc) { new JsonFormatReaderInterpreter(collectionContract, isGetOnly: true).ReadGetOnlyCollectionFromJson(xr, ctx, emptyDS, inm, cc); }; } } [SecurityCritical] private CriticalHelper helper; [SecurityCritical] public JsonFormatReaderGenerator() { helper = new CriticalHelper(); } [SecurityCritical] public JsonFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract) { try { if (TD.DCJsonGenReaderStartIsEnabled()) { TD.DCJsonGenReaderStart("Class", classContract.UnderlyingType.FullName); } return helper.GenerateClassReader(classContract); } finally { if (TD.DCJsonGenReaderStopIsEnabled()) { TD.DCJsonGenReaderStop(); } } } [SecurityCritical] public JsonFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract) { try { if (TD.DCJsonGenReaderStartIsEnabled()) { TD.DCJsonGenReaderStart("Collection", collectionContract.StableName.Name); } return helper.GenerateCollectionReader(collectionContract); } finally { if (TD.DCJsonGenReaderStopIsEnabled()) { TD.DCJsonGenReaderStop(); } } } [SecurityCritical] public JsonFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract) { try { if (TD.DCJsonGenReaderStartIsEnabled()) { TD.DCJsonGenReaderStart("GetOnlyCollection", collectionContract.UnderlyingType.FullName); } return helper.GenerateGetOnlyCollectionReader(collectionContract); } finally { if (TD.DCJsonGenReaderStopIsEnabled()) { TD.DCJsonGenReaderStop(); } } } } internal delegate void JsonFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract dataContract, XmlDictionaryString[] memberNames); internal delegate void JsonFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract dataContract); internal class JsonFormatWriterGenerator { private class CriticalHelper { internal JsonFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract) { return delegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract dataContract, XmlDictionaryString[] memberNames) { new JsonFormatWriterInterpreter(classContract).WriteToJson(xmlWriter, obj, context, dataContract, memberNames); }; } internal JsonFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract) { return delegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract dataContract) { new JsonFormatWriterInterpreter(collectionContract).WriteCollectionToJson(xmlWriter, obj, context, dataContract); }; } } [SecurityCritical] private CriticalHelper helper; [SecurityCritical] public JsonFormatWriterGenerator() { helper = new CriticalHelper(); } [SecurityCritical] internal JsonFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract) { try { if (TD.DCJsonGenWriterStartIsEnabled()) { TD.DCJsonGenWriterStart("Class", classContract.UnderlyingType.FullName); } return helper.GenerateClassWriter(classContract); } finally { if (TD.DCJsonGenWriterStopIsEnabled()) { TD.DCJsonGenWriterStop(); } } } [SecurityCritical] internal JsonFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract) { try { if (TD.DCJsonGenWriterStartIsEnabled()) { TD.DCJsonGenWriterStart("Collection", collectionContract.UnderlyingType.FullName); } return helper.GenerateCollectionWriter(collectionContract); } finally { if (TD.DCJsonGenWriterStopIsEnabled()) { TD.DCJsonGenWriterStop(); } } } } internal static class JsonGlobals { public static readonly int DataContractXsdBaseNamespaceLength = "http://schemas.datacontract.org/2004/07/".Length; public static readonly XmlDictionaryString dDictionaryString = new XmlDictionary().Add("d"); public static readonly char[] floatingPointCharacters = new char[2] { '.', 'e' }; public static readonly XmlDictionaryString itemDictionaryString = new XmlDictionary().Add("item"); public static readonly XmlDictionaryString rootDictionaryString = new XmlDictionary().Add("root"); public static readonly long unixEpochTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks; public const string applicationJsonMediaType = "application/json"; public const string arrayString = "array"; public const string booleanString = "boolean"; public const string CacheControlString = "Cache-Control"; public const byte CollectionByte = 91; public const char CollectionChar = '['; public const string DateTimeEndGuardReader = ")/"; public const string DateTimeEndGuardWriter = ")\\/"; public const string DateTimeStartGuardReader = "/Date("; public const string DateTimeStartGuardWriter = "\\/Date("; public const string dString = "d"; public const byte EndCollectionByte = 93; public const char EndCollectionChar = ']'; public const byte EndObjectByte = 125; public const char EndObjectChar = '}'; public const string ExpiresString = "Expires"; public const string IfModifiedSinceString = "If-Modified-Since"; public const string itemString = "item"; public const string jsonerrorString = "jsonerror"; public const string KeyString = "Key"; public const string LastModifiedString = "Last-Modified"; public const int maxScopeSize = 25; public const byte MemberSeparatorByte = 44; public const char MemberSeparatorChar = ','; public const byte NameValueSeparatorByte = 58; public const char NameValueSeparatorChar = ':'; public const string NameValueSeparatorString = ":"; public const string nullString = "null"; public const string numberString = "number"; public const byte ObjectByte = 123; public const char ObjectChar = '{'; public const string objectString = "object"; public const string publicString = "public"; public const byte QuoteByte = 34; public const char QuoteChar = '"'; public const string rootString = "root"; public const string serverTypeString = "__type"; public const string stringString = "string"; public const string textJsonMediaType = "text/json"; public const string trueString = "true"; public const string typeString = "type"; public const string ValueString = "Value"; public const char WhitespaceChar = ' '; public const string xmlnsPrefix = "xmlns"; public const string xmlPrefix = "xml"; } internal enum JsonNodeType { None, Object, Element, EndElement, QuotedText, StandaloneText, Collection } internal class JsonObjectDataContract : JsonDataContract { public JsonObjectDataContract(DataContract traditionalDataContract) : base(traditionalDataContract) { } public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { string attribute = jsonReader.GetAttribute("type"); object obj; switch (attribute) { case "null": jsonReader.Skip(); obj = null; break; case "boolean": obj = jsonReader.ReadElementContentAsBoolean(); break; case "string": case null: obj = jsonReader.ReadElementContentAsString(); break; case "number": obj = ParseJsonNumber(jsonReader.ReadElementContentAsString()); break; case "object": jsonReader.Skip(); obj = new object(); break; case "array": return DataContractJsonSerializer.ReadJsonValue(DataContract.GetDataContract(Globals.TypeOfObjectArray), jsonReader, context); default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Unexpected attribute value '{0}'.", attribute))); } context?.AddNewObject(obj); return obj; } public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { jsonWriter.WriteAttributeString(null, "type", null, "object"); } internal static object ParseJsonNumber(string value, out TypeCode objectTypeCode) { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("The value '{0}' cannot be parsed as the type '{1}'.", value, Globals.TypeOfInt))); } if (value.IndexOfAny(JsonGlobals.floatingPointCharacters) == -1) { if (int.TryParse(value, NumberStyles.Float, NumberFormatInfo.InvariantInfo, out var result)) { objectTypeCode = TypeCode.Int32; return result; } if (long.TryParse(value, NumberStyles.Float, NumberFormatInfo.InvariantInfo, out var result2)) { objectTypeCode = TypeCode.Int64; return result2; } } if (decimal.TryParse(value, NumberStyles.Float, NumberFormatInfo.InvariantInfo, out var result3)) { objectTypeCode = TypeCode.Decimal; if (result3 == 0m) { double num = XmlConverter.ToDouble(value); if (num != 0.0) { objectTypeCode = TypeCode.Double; return num; } } return result3; } objectTypeCode = TypeCode.Double; return XmlConverter.ToDouble(value); } private static object ParseJsonNumber(string value) { TypeCode objectTypeCode; return ParseJsonNumber(value, out objectTypeCode); } } internal class JsonQNameDataContract : JsonDataContract { public JsonQNameDataContract(QNameDataContract traditionalQNameDataContract) : base(traditionalQNameDataContract) { } public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { if (context == null) { if (!JsonDataContract.TryReadNullAtTopLevel(jsonReader)) { return jsonReader.ReadElementContentAsQName(); } return null; } return JsonDataContract.HandleReadValue(jsonReader.ReadElementContentAsQName(), context); } } internal class JsonReaderDelegator : XmlReaderDelegator { private class DateTimeArrayJsonHelperWithString : ArrayHelper { private DateTimeFormat dateTimeFormat; public DateTimeArrayJsonHelperWithString(DateTimeFormat dateTimeFormat) { this.dateTimeFormat = dateTimeFormat; } protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, DateTime[] array, int offset, int count) { XmlJsonReader.CheckArray(array, offset, count); int i; for (i = 0; i < count; i++) { if (!reader.IsStartElement("item", string.Empty)) { break; } array[offset + i] = ParseJsonDate(reader.ReadElementContentAsString(), dateTimeFormat); } return i; } protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException()); } } private DateTimeFormat dateTimeFormat; private DateTimeArrayJsonHelperWithString dateTimeArrayHelper; internal XmlDictionaryReaderQuotas ReaderQuotas { get { if (dictionaryReader == null) { return null; } return dictionaryReader.Quotas; } } private DateTimeArrayJsonHelperWithString DateTimeArrayHelper { get { if (dateTimeArrayHelper == null) { dateTimeArrayHelper = new DateTimeArrayJsonHelperWithString(dateTimeFormat); } return dateTimeArrayHelper; } } public JsonReaderDelegator(XmlReader reader) : base(reader) { } public JsonReaderDelegator(XmlReader reader, DateTimeFormat dateTimeFormat) : this(reader) { this.dateTimeFormat = dateTimeFormat; } internal static XmlQualifiedName ParseQualifiedName(string qname) { string name; string ns; if (string.IsNullOrEmpty(qname)) { name = (ns = string.Empty); } else { qname = qname.Trim(); int num = qname.IndexOf(':'); if (num >= 0) { name = qname.Substring(0, num); ns = qname.Substring(num + 1); } else { name = qname; ns = string.Empty; } } return new XmlQualifiedName(name, ns); } internal override char ReadContentAsChar() { return XmlConvert.ToChar(ReadContentAsString()); } internal override XmlQualifiedName ReadContentAsQName() { return ParseQualifiedName(ReadContentAsString()); } internal override char ReadElementContentAsChar() { return XmlConvert.ToChar(ReadElementContentAsString()); } internal override byte[] ReadContentAsBase64() { if (isEndOfEmptyElement) { return new byte[0]; } if (dictionaryReader == null) { XmlDictionaryReader xmlDictionaryReader = XmlDictionaryReader.CreateDictionaryReader(reader); return ByteArrayHelperWithString.Instance.ReadArray(xmlDictionaryReader, "item", string.Empty, xmlDictionaryReader.Quotas.MaxArrayLength); } return ByteArrayHelperWithString.Instance.ReadArray(dictionaryReader, "item", string.Empty, dictionaryReader.Quotas.MaxArrayLength); } internal override byte[] ReadElementContentAsBase64() { if (isEndOfEmptyElement) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Start element expected. Found {0}.", "EndElement"))); } byte[] result; if (reader.IsStartElement() && reader.IsEmptyElement) { reader.Read(); result = new byte[0]; } else { reader.ReadStartElement(); result = ReadContentAsBase64(); reader.ReadEndElement(); } return result; } internal override DateTime ReadContentAsDateTime() { return ParseJsonDate(ReadContentAsString(), dateTimeFormat); } internal static DateTime ParseJsonDate(string originalDateTimeValue, DateTimeFormat dateTimeFormat) { if (dateTimeFormat == null) { return ParseJsonDateInDefaultFormat(originalDateTimeValue); } return DateTime.ParseExact(originalDateTimeValue, dateTimeFormat.FormatString, dateTimeFormat.FormatProvider, dateTimeFormat.DateTimeStyles); } internal static DateTime ParseJsonDateInDefaultFormat(string originalDateTimeValue) { string text = (string.IsNullOrEmpty(originalDateTimeValue) ? originalDateTimeValue : originalDateTimeValue.Trim()); if (string.IsNullOrEmpty(text) || !text.StartsWith("/Date(", StringComparison.Ordinal) || !text.EndsWith(")/", StringComparison.Ordinal)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString("Invalid JSON dateTime string is specified: original value '{0}', start guide writer: {1}, end guard writer: {2}.", originalDateTimeValue, "\\/Date(", ")\\/"))); } string text2 = text.Substring(6, text.Length - 8); DateTimeKind dateTimeKind = DateTimeKind.Utc; int num = text2.IndexOf('+', 1); if (num == -1) { num = text2.IndexOf('-', 1); } if (num != -1) { dateTimeKind = DateTimeKind.Local; text2 = text2.Substring(0, num); } long num2; try { num2 = long.Parse(text2, CultureInfo.InvariantCulture); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text2, "Int64", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text2, "Int64", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text2, "Int64", exception3)); } long ticks = num2 * 10000 + JsonGlobals.unixEpochTicks; try { DateTime dateTime = new DateTime(ticks, DateTimeKind.Utc); return dateTimeKind switch { DateTimeKind.Local => dateTime.ToLocalTime(), DateTimeKind.Unspecified => DateTime.SpecifyKind(dateTime.ToLocalTime(), DateTimeKind.Unspecified), _ => dateTime, }; } catch (ArgumentException exception4) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text2, "DateTime", exception4)); } } internal override DateTime ReadElementContentAsDateTime() { return ParseJsonDate(ReadElementContentAsString(), dateTimeFormat); } internal bool TryReadJsonDateTimeArray(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out DateTime[] array) { if (dictionaryReader == null || arrayLength != -1) { array = null; return false; } array = DateTimeArrayHelper.ReadArray(dictionaryReader, XmlDictionaryString.GetString(itemName), XmlDictionaryString.GetString(itemNamespace), GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); return true; } internal override ulong ReadContentAsUnsignedLong() { string text = reader.ReadContentAsString(); if (text == null || text.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.GetString("The value '{0}' cannot be parsed as the type '{1}'.", text, "UInt64")))); } try { return ulong.Parse(text, NumberStyles.Float, NumberFormatInfo.InvariantInfo); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text, "UInt64", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text, "UInt64", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text, "UInt64", exception3)); } } internal override ulong ReadElementContentAsUnsignedLong() { if (isEndOfEmptyElement) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Start element expected. Found {0}.", "EndElement"))); } string text = reader.ReadElementContentAsString(); if (text == null || text.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.GetString("The value '{0}' cannot be parsed as the type '{1}'.", text, "UInt64")))); } try { return ulong.Parse(text, NumberStyles.Float, NumberFormatInfo.InvariantInfo); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text, "UInt64", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text, "UInt64", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(text, "UInt64", exception3)); } } } [TypeForwardedFrom("System.ServiceModel.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public static class JsonReaderWriterFactory { private const string DefaultIndentChars = " "; public static XmlDictionaryReader CreateJsonReader(Stream stream, XmlDictionaryReaderQuotas quotas) { return CreateJsonReader(stream, null, quotas, null); } public static XmlDictionaryReader CreateJsonReader(byte[] buffer, XmlDictionaryReaderQuotas quotas) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); } return CreateJsonReader(buffer, 0, buffer.Length, null, quotas, null); } public static XmlDictionaryReader CreateJsonReader(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) { XmlJsonReader xmlJsonReader = new XmlJsonReader(); xmlJsonReader.SetInput(stream, encoding, quotas, onClose); return xmlJsonReader; } public static XmlDictionaryReader CreateJsonReader(byte[] buffer, int offset, int count, XmlDictionaryReaderQuotas quotas) { return CreateJsonReader(buffer, offset, count, null, quotas, null); } public static XmlDictionaryReader CreateJsonReader(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) { XmlJsonReader xmlJsonReader = new XmlJsonReader(); xmlJsonReader.SetInput(buffer, offset, count, encoding, quotas, onClose); return xmlJsonReader; } public static XmlDictionaryWriter CreateJsonWriter(Stream stream) { return CreateJsonWriter(stream, Encoding.UTF8, ownsStream: true); } public static XmlDictionaryWriter CreateJsonWriter(Stream stream, Encoding encoding) { return CreateJsonWriter(stream, encoding, ownsStream: true); } public static XmlDictionaryWriter CreateJsonWriter(Stream stream, Encoding encoding, bool ownsStream) { return CreateJsonWriter(stream, encoding, ownsStream, indent: false); } public static XmlDictionaryWriter CreateJsonWriter(Stream stream, Encoding encoding, bool ownsStream, bool indent) { return CreateJsonWriter(stream, encoding, ownsStream, indent, " "); } public static XmlDictionaryWriter CreateJsonWriter(Stream stream, Encoding encoding, bool ownsStream, bool indent, string indentChars) { XmlJsonWriter xmlJsonWriter = new XmlJsonWriter(indent, indentChars); xmlJsonWriter.SetOutput(stream, encoding, ownsStream); return xmlJsonWriter; } } internal class JsonStringDataContract : JsonDataContract { public JsonStringDataContract(StringDataContract traditionalStringDataContract) : base(traditionalStringDataContract) { } public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { if (context == null) { if (!JsonDataContract.TryReadNullAtTopLevel(jsonReader)) { return jsonReader.ReadElementContentAsString(); } return null; } return JsonDataContract.HandleReadValue(jsonReader.ReadElementContentAsString(), context); } } internal class JsonUriDataContract : JsonDataContract { public JsonUriDataContract(UriDataContract traditionalUriDataContract) : base(traditionalUriDataContract) { } public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { if (context == null) { if (!JsonDataContract.TryReadNullAtTopLevel(jsonReader)) { return jsonReader.ReadElementContentAsUri(); } return null; } return JsonDataContract.HandleReadValue(jsonReader.ReadElementContentAsUri(), context); } } internal class JsonWriterDelegator : XmlWriterDelegator { private DateTimeFormat dateTimeFormat; public JsonWriterDelegator(XmlWriter writer) : base(writer) { } public JsonWriterDelegator(XmlWriter writer, DateTimeFormat dateTimeFormat) : this(writer) { this.dateTimeFormat = dateTimeFormat; } internal override void WriteChar(char value) { WriteString(XmlConvert.ToString(value)); } internal override void WriteBase64(byte[] bytes) { if (bytes != null) { ByteArrayHelperWithString.Instance.WriteArray(base.Writer, bytes, 0, bytes.Length); } } internal override void WriteQName(XmlQualifiedName value) { if (value != XmlQualifiedName.Empty) { writer.WriteString(value.Name); writer.WriteString(":"); writer.WriteString(value.Namespace); } } internal override void WriteUnsignedLong(ulong value) { WriteDecimal(value); } internal override void WriteDecimal(decimal value) { writer.WriteAttributeString("type", "number"); base.WriteDecimal(value); } internal override void WriteDouble(double value) { writer.WriteAttributeString("type", "number"); base.WriteDouble(value); } internal override void WriteFloat(float value) { writer.WriteAttributeString("type", "number"); base.WriteFloat(value); } internal override void WriteLong(long value) { writer.WriteAttributeString("type", "number"); base.WriteLong(value); } internal override void WriteSignedByte(sbyte value) { writer.WriteAttributeString("type", "number"); base.WriteSignedByte(value); } internal override void WriteUnsignedInt(uint value) { writer.WriteAttributeString("type", "number"); base.WriteUnsignedInt(value); } internal override void WriteUnsignedShort(ushort value) { writer.WriteAttributeString("type", "number"); base.WriteUnsignedShort(value); } internal override void WriteUnsignedByte(byte value) { writer.WriteAttributeString("type", "number"); base.WriteUnsignedByte(value); } internal override void WriteShort(short value) { writer.WriteAttributeString("type", "number"); base.WriteShort(value); } internal override void WriteBoolean(bool value) { writer.WriteAttributeString("type", "boolean"); base.WriteBoolean(value); } internal override void WriteInt(int value) { writer.WriteAttributeString("type", "number"); base.WriteInt(value); } internal void WriteJsonBooleanArray(bool[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { for (int i = 0; i < value.Length; i++) { WriteBoolean(value[i], itemName, itemNamespace); } } internal void WriteJsonDateTimeArray(DateTime[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { for (int i = 0; i < value.Length; i++) { WriteDateTime(value[i], itemName, itemNamespace); } } internal void WriteJsonDecimalArray(decimal[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { for (int i = 0; i < value.Length; i++) { WriteDecimal(value[i], itemName, itemNamespace); } } internal void WriteJsonInt32Array(int[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { for (int i = 0; i < value.Length; i++) { WriteInt(value[i], itemName, itemNamespace); } } internal void WriteJsonInt64Array(long[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { for (int i = 0; i < value.Length; i++) { WriteLong(value[i], itemName, itemNamespace); } } internal override void WriteDateTime(DateTime value) { if (dateTimeFormat == null) { WriteDateTimeInDefaultFormat(value); } else { writer.WriteString(value.ToString(dateTimeFormat.FormatString, dateTimeFormat.FormatProvider)); } } private void WriteDateTimeInDefaultFormat(DateTime value) { if (value.Kind != DateTimeKind.Utc) { long num = (System.LocalAppContextSwitches.DoNotUseTimeZoneInfo ? (value.Ticks - TimeZone.CurrentTimeZone.GetUtcOffset(value).Ticks) : (value.Ticks - TimeZoneInfo.Local.GetUtcOffset(value).Ticks)); DateTime maxValue = DateTime.MaxValue; if (num <= maxValue.Ticks) { maxValue = DateTime.MinValue; if (num >= maxValue.Ticks) { goto IL_008d; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("JSON DateTime is out of range."), new ArgumentOutOfRangeException("value"))); } goto IL_008d; IL_008d: writer.WriteString("/Date("); writer.WriteValue((value.ToUniversalTime().Ticks - JsonGlobals.unixEpochTicks) / 10000); switch (value.Kind) { case DateTimeKind.Unspecified: case DateTimeKind.Local: { TimeSpan timeSpan = (System.LocalAppContextSwitches.DoNotUseTimeZoneInfo ? TimeZone.CurrentTimeZone.GetUtcOffset(value.ToLocalTime()) : TimeZoneInfo.Local.GetUtcOffset(value.ToLocalTime())); if (timeSpan.Ticks < 0) { writer.WriteString("-"); } else { writer.WriteString("+"); } int num2 = Math.Abs(timeSpan.Hours); writer.WriteString((num2 < 10) ? ("0" + num2) : num2.ToString(CultureInfo.InvariantCulture)); int num3 = Math.Abs(timeSpan.Minutes); writer.WriteString((num3 < 10) ? ("0" + num3) : num3.ToString(CultureInfo.InvariantCulture)); break; } } writer.WriteString(")/"); } internal void WriteJsonSingleArray(float[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { for (int i = 0; i < value.Length; i++) { WriteFloat(value[i], itemName, itemNamespace); } } internal void WriteJsonDoubleArray(double[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { for (int i = 0; i < value.Length; i++) { WriteDouble(value[i], itemName, itemNamespace); } } internal override void WriteStartElement(string prefix, string localName, string ns) { if (localName != null && localName.Length == 0) { WriteStartElement("item", "item"); WriteAttributeString(null, "item", null, localName); } else { base.WriteStartElement(prefix, localName, ns); } } } internal class JsonXmlDataContract : JsonDataContract { public JsonXmlDataContract(XmlDataContract traditionalXmlDataContract) : base(traditionalXmlDataContract) { } public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { string s = jsonReader.ReadElementContentAsString(); DataContractSerializer dataContractSerializer = new DataContractSerializer(base.TraditionalDataContract.UnderlyingType, GetKnownTypesFromContext(context, context?.SerializerKnownTypeList), 1, ignoreExtensionDataObject: false, preserveObjectReferences: false, null); MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(s)); XmlDictionaryReaderQuotas readerQuotas = ((JsonReaderDelegator)jsonReader).ReaderQuotas; object obj = ((readerQuotas != null) ? dataContractSerializer.ReadObject(XmlDictionaryReader.CreateTextReader(stream, readerQuotas)) : dataContractSerializer.ReadObject(stream)); context?.AddNewObject(obj); return obj; } public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { DataContractSerializer dataContractSerializer = new DataContractSerializer(Type.GetTypeFromHandle(declaredTypeHandle), GetKnownTypesFromContext(context, context?.SerializerKnownTypeList), 1, ignoreExtensionDataObject: false, preserveObjectReferences: false, null); MemoryStream memoryStream = new MemoryStream(); dataContractSerializer.WriteObject(memoryStream, obj); memoryStream.Position = 0L; string value = new StreamReader(memoryStream).ReadToEnd(); jsonWriter.WriteString(value); } private List GetKnownTypesFromContext(XmlObjectSerializerContext context, IList serializerKnownTypeList) { List list = new List(); if (context != null) { List list2 = new List(); Dictionary[] dataContractDictionaries = context.scopedKnownTypes.dataContractDictionaries; if (dataContractDictionaries != null) { foreach (Dictionary dictionary in dataContractDictionaries) { if (dictionary == null) { continue; } foreach (KeyValuePair item in dictionary) { if (!list2.Contains(item.Key)) { list2.Add(item.Key); list.Add(item.Value.UnderlyingType); } } } } if (serializerKnownTypeList != null) { list.AddRange(serializerKnownTypeList); } } return list; } } internal class XmlJsonReader : XmlBaseReader, IXmlJsonReaderInitializer { private enum JsonComplexTextMode { QuotedText, NumericalText, None } private static class CharType { public const byte FirstName = 1; public const byte Name = 2; public const byte None = 0; } private const int MaxTextChunk = 2048; private static byte[] charType = new byte[256] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 }; private bool buffered; private byte[] charactersToSkipOnNextRead; private JsonComplexTextMode complexTextMode = JsonComplexTextMode.None; private bool expectingFirstElementInNonPrimitiveChild; private int maxBytesPerRead; private OnXmlDictionaryReaderClose onReaderClose; private bool readServerTypeElement; private int scopeDepth; private JsonNodeType[] scopes; public override bool CanCanonicalize => false; public override string Value { get { if (IsAttributeValue && !IsLocalName("type")) { return UnescapeJsonString(base.Value); } return base.Value; } } private bool IsAttributeValue { get { if (base.Node.NodeType != XmlNodeType.Attribute) { return base.Node is XmlAttributeTextNode; } return true; } } private bool IsReadingCollection { get { if (scopeDepth > 0) { return scopes[scopeDepth] == JsonNodeType.Collection; } return false; } } private bool IsReadingComplexText { get { if (!base.Node.IsAtomicValue) { return base.Node.NodeType == XmlNodeType.Text; } return false; } } public override void Close() { base.Close(); OnXmlDictionaryReaderClose onXmlDictionaryReaderClose = onReaderClose; onReaderClose = null; ResetState(); if (onXmlDictionaryReaderClose == null) { return; } try { onXmlDictionaryReaderClose(this); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(ex); } } public override void EndCanonicalization() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } public override string GetAttribute(int index) { return UnescapeJsonString(base.GetAttribute(index)); } public override string GetAttribute(string localName, string namespaceUri) { if (localName != "type") { return UnescapeJsonString(base.GetAttribute(localName, namespaceUri)); } return base.GetAttribute(localName, namespaceUri); } public override string GetAttribute(string name) { if (name != "type") { return UnescapeJsonString(base.GetAttribute(name)); } return base.GetAttribute(name); } public override string GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { if (XmlDictionaryString.GetString(localName) != "type") { return UnescapeJsonString(base.GetAttribute(localName, namespaceUri)); } return base.GetAttribute(localName, namespaceUri); } public override bool Read() { if (base.Node.CanMoveToElement) { MoveToElement(); } if (base.Node.ReadState == ReadState.Closed) { return false; } if (base.Node.ExitScope) { ExitScope(); } if (!buffered) { base.BufferReader.SetWindow(base.ElementNode.BufferOffset, maxBytesPerRead); } byte ch; if (!IsReadingComplexText) { SkipWhitespaceInBufferReader(); if (TryGetByte(out ch) && (charactersToSkipOnNextRead[0] == ch || charactersToSkipOnNextRead[1] == ch)) { base.BufferReader.SkipByte(); charactersToSkipOnNextRead[0] = 0; charactersToSkipOnNextRead[1] = 0; } SkipWhitespaceInBufferReader(); if (TryGetByte(out ch) && ch == 93 && IsReadingCollection) { base.BufferReader.SkipByte(); SkipWhitespaceInBufferReader(); ExitJsonScope(); } if (base.BufferReader.EndOfFile) { if (scopeDepth > 0) { MoveToEndElement(); return true; } MoveToEndOfFile(); return false; } } ch = base.BufferReader.GetByte(); if (scopeDepth == 0) { ReadNonExistentElementName(StringHandleConstStringType.Root); } else if (IsReadingComplexText) { switch (complexTextMode) { case JsonComplexTextMode.NumericalText: ReadNumericalText(); break; case JsonComplexTextMode.QuotedText: if (ch == 92) { ReadEscapedCharacter(moveToText: true); } else { ReadQuotedText(moveToText: true); } break; case JsonComplexTextMode.None: XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.GetString("Encountered an unexpected character '{0}' in JSON.", (char)ch))); break; } } else if (IsReadingCollection) { ReadNonExistentElementName(StringHandleConstStringType.Item); } else if (ch == 93) { base.BufferReader.SkipByte(); MoveToEndElement(); ExitJsonScope(); } else if (ch == 123) { base.BufferReader.SkipByte(); SkipWhitespaceInBufferReader(); ch = base.BufferReader.GetByte(); if (ch == 125) { base.BufferReader.SkipByte(); SkipWhitespaceInBufferReader(); if (TryGetByte(out ch)) { if (ch == 44) { base.BufferReader.SkipByte(); } } else { charactersToSkipOnNextRead[0] = 44; } MoveToEndElement(); } else { EnterJsonScope(JsonNodeType.Object); ParseStartElement(); } } else if (ch == 125) { base.BufferReader.SkipByte(); if (expectingFirstElementInNonPrimitiveChild) { SkipWhitespaceInBufferReader(); ch = base.BufferReader.GetByte(); if (ch == 44 || ch == 125) { base.BufferReader.SkipByte(); } else { XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.GetString("Encountered an unexpected character '{0}' in JSON.", (char)ch))); } expectingFirstElementInNonPrimitiveChild = false; } MoveToEndElement(); } else if (ch == 44) { base.BufferReader.SkipByte(); MoveToEndElement(); } else if (ch == 34) { if (readServerTypeElement) { readServerTypeElement = false; EnterJsonScope(JsonNodeType.Object); ParseStartElement(); } else if (base.Node.NodeType == XmlNodeType.Element) { if (expectingFirstElementInNonPrimitiveChild) { EnterJsonScope(JsonNodeType.Object); ParseStartElement(); } else { base.BufferReader.SkipByte(); ReadQuotedText(moveToText: true); } } else if (base.Node.NodeType == XmlNodeType.EndElement) { EnterJsonScope(JsonNodeType.Element); ParseStartElement(); } else { XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.GetString("Encountered an unexpected character '{0}' in JSON.", '"'))); } } else if (ch == 102) { int offset; byte[] buffer = base.BufferReader.GetBuffer(5, out offset); if (buffer[offset + 1] != 97 || buffer[offset + 2] != 108 || buffer[offset + 3] != 115 || buffer[offset + 4] != 101) { XmlExceptionHelper.ThrowTokenExpected(this, "false", Encoding.UTF8.GetString(buffer, offset, 5)); } base.BufferReader.Advance(5); if (TryGetByte(out ch) && !IsWhitespace(ch) && ch != 44 && ch != 125 && ch != 93) { string @string = Encoding.UTF8.GetString(buffer, offset, 4); char c = (char)ch; XmlExceptionHelper.ThrowTokenExpected(this, "false", @string + c); } MoveToAtomicText().Value.SetValue(ValueHandleType.UTF8, offset, 5); } else if (ch == 116) { int offset2; byte[] buffer2 = base.BufferReader.GetBuffer(4, out offset2); if (buffer2[offset2 + 1] != 114 || buffer2[offset2 + 2] != 117 || buffer2[offset2 + 3] != 101) { XmlExceptionHelper.ThrowTokenExpected(this, "true", Encoding.UTF8.GetString(buffer2, offset2, 4)); } base.BufferReader.Advance(4); if (TryGetByte(out ch) && !IsWhitespace(ch) && ch != 44 && ch != 125 && ch != 93) { string string2 = Encoding.UTF8.GetString(buffer2, offset2, 4); char c = (char)ch; XmlExceptionHelper.ThrowTokenExpected(this, "true", string2 + c); } MoveToAtomicText().Value.SetValue(ValueHandleType.UTF8, offset2, 4); } else if (ch == 110) { int offset3; byte[] buffer3 = base.BufferReader.GetBuffer(4, out offset3); if (buffer3[offset3 + 1] != 117 || buffer3[offset3 + 2] != 108 || buffer3[offset3 + 3] != 108) { XmlExceptionHelper.ThrowTokenExpected(this, "null", Encoding.UTF8.GetString(buffer3, offset3, 4)); } base.BufferReader.Advance(4); SkipWhitespaceInBufferReader(); if (TryGetByte(out ch)) { switch (ch) { case 44: case 125: base.BufferReader.SkipByte(); break; default: { string string3 = Encoding.UTF8.GetString(buffer3, offset3, 4); char c = (char)ch; XmlExceptionHelper.ThrowTokenExpected(this, "null", string3 + c); break; } case 93: break; } } else { charactersToSkipOnNextRead[0] = 44; charactersToSkipOnNextRead[1] = 125; } MoveToEndElement(); } else if (ch == 45 || (48 <= ch && ch <= 57) || ch == 73 || ch == 78) { ReadNumericalText(); } else { XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.GetString("Encountered an unexpected character '{0}' in JSON.", (char)ch))); } return true; } public override decimal ReadContentAsDecimal() { string s = ReadContentAsString(); try { return decimal.Parse(s, NumberStyles.Float, NumberFormatInfo.InvariantInfo); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(s, "decimal", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(s, "decimal", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(s, "decimal", exception3)); } } public override int ReadContentAsInt() { return ParseInt(ReadContentAsString(), NumberStyles.Float); } public override long ReadContentAsLong() { string s = ReadContentAsString(); try { return long.Parse(s, NumberStyles.Float, NumberFormatInfo.InvariantInfo); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(s, "Int64", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(s, "Int64", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(s, "Int64", exception3)); } } public override int ReadValueAsBase64(byte[] buffer, int offset, int count) { if (IsAttributeValue) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("buffer")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString("The value of this argument must be non-negative."))); } if (offset > buffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", buffer.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", buffer.Length - offset))); } return 0; } return base.ReadValueAsBase64(buffer, offset, count); } public override int ReadValueChunk(char[] chars, int offset, int count) { if (IsAttributeValue) { if (chars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString("The value of this argument must be non-negative."))); } if (offset > chars.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString("The value of this argument must be non-negative."))); } if (count > chars.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", chars.Length - offset))); } string text = UnescapeJsonString(base.Node.ValueAsString); int num = Math.Min(count, text.Length); if (num > 0) { text.CopyTo(0, chars, offset, num); if (base.Node.QNameType == QNameType.Xmlns) { base.Node.Namespace.Uri.SetValue(0, 0); } else { base.Node.Value.SetValue(ValueHandleType.UTF8, 0, 0); } } return num; } return base.ReadValueChunk(chars, offset, count); } public void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString("The value of this argument must be non-negative."))); } if (offset > buffer.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString("On JSON writer, offset exceeded buffer size {0}.", buffer.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString("JSON size exceeded remaining buffer space, by {0} byte(s).", buffer.Length - offset))); } MoveToInitial(quotas, onClose); ArraySegment arraySegment = JsonEncodingStreamWrapper.ProcessBuffer(buffer, offset, count, encoding); base.BufferReader.SetBuffer(arraySegment.Array, arraySegment.Offset, arraySegment.Count, null, null); buffered = true; ResetState(); } public void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) { if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream"); } MoveToInitial(quotas, onClose); stream = new JsonEncodingStreamWrapper(stream, encoding, isReader: true); base.BufferReader.SetBuffer(stream, null, null); buffered = false; ResetState(); } public override void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } internal static void CheckArray(Array array, int offset, int count) { if (array == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("array")); } if (offset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString("The value of this argument must be non-negative."))); } if (offset > array.Length) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", array.Length))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString("The value of this argument must be non-negative."))); } if (count > array.Length - offset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", array.Length - offset))); } } protected override XmlSigningNodeWriter CreateSigningNodeWriter() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("Method {0} is not supported in JSON.", "CreateSigningNodeWriter"))); } private static int BreakText(byte[] buffer, int offset, int length) { if (length > 0 && (buffer[offset + length - 1] & 0x80) == 128) { int num = length; do { length--; } while (length > 0 && (buffer[offset + length] & 0xC0) != 192); if (length == 0) { return num; } byte b = (byte)(buffer[offset + length] << 2); int num2 = 2; while ((b & 0x80) == 128) { b <<= 1; num2++; if (num2 > 4) { return num; } } if (length + num2 == num) { return num; } if (length == 0) { return num; } } return length; } private static int ComputeNumericalTextLength(byte[] buffer, int offset, int offsetMax) { int num = offset; while (offset < offsetMax) { byte b = buffer[offset]; if (b == 44 || b == 125 || b == 93 || IsWhitespace(b)) { break; } offset++; } return offset - num; } private static int ComputeQuotedTextLengthUntilEndQuote(byte[] buffer, int offset, int offsetMax, out bool escaped) { int num = offset; escaped = false; for (; offset < offsetMax; offset++) { byte b = buffer[offset]; if (b < 32) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString("Encountered an invalid character '{0}'.", (char)b))); } switch (b) { case 92: case 239: escaped = true; break; default: continue; case 34: break; } break; } return offset - num; } private static bool IsWhitespace(byte ch) { if (ch != 32 && ch != 9 && ch != 10) { return ch == 13; } return true; } private static char ParseChar(string value, NumberStyles style) { int num = ParseInt(value, style); try { return Convert.ToChar(num); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "char", exception)); } } private static int ParseInt(string value, NumberStyles style) { try { return int.Parse(value, style, NumberFormatInfo.InvariantInfo); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int32", exception)); } catch (FormatException exception2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int32", exception2)); } catch (OverflowException exception3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(value, "Int32", exception3)); } } private void BufferElement() { int offset = base.BufferReader.Offset; bool flag = false; byte b = 0; while (!flag) { int offset2; int offsetMax; byte[] buffer = base.BufferReader.GetBuffer(128, out offset2, out offsetMax); if (offset2 + 128 != offsetMax) { break; } for (int i = offset2; i < offsetMax; i++) { if (flag) { break; } byte b2 = buffer[i]; if (b2 == 92) { i++; if (i >= offsetMax) { break; } } else if (b == 0) { if (b2 == 39 || b2 == 34) { b = b2; } if (b2 == 58) { flag = true; } } else if (b2 == b) { b = 0; } } base.BufferReader.Advance(128); } base.BufferReader.Offset = offset; } private void EnterJsonScope(JsonNodeType currentNodeType) { scopeDepth++; if (scopes == null) { scopes = new JsonNodeType[4]; } else if (scopes.Length == scopeDepth) { JsonNodeType[] destinationArray = new JsonNodeType[scopeDepth * 2]; Array.Copy(scopes, destinationArray, scopeDepth); scopes = destinationArray; } scopes[scopeDepth] = currentNodeType; } private JsonNodeType ExitJsonScope() { JsonNodeType result = scopes[scopeDepth]; scopes[scopeDepth] = JsonNodeType.None; scopeDepth--; return result; } private new void MoveToEndElement() { ExitJsonScope(); base.MoveToEndElement(); } private void MoveToInitial(XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) { MoveToInitial(quotas); maxBytesPerRead = quotas.MaxBytesPerRead; onReaderClose = onClose; } private void ParseAndSetLocalName() { XmlElementNode xmlElementNode = EnterScope(); xmlElementNode.NameOffset = base.BufferReader.Offset; do { if (base.BufferReader.GetByte() == 92) { ReadEscapedCharacter(moveToText: false); } else { ReadQuotedText(moveToText: false); } } while (complexTextMode == JsonComplexTextMode.QuotedText); int num = base.BufferReader.Offset - 1; xmlElementNode.LocalName.SetValue(xmlElementNode.NameOffset, num - xmlElementNode.NameOffset); xmlElementNode.NameLength = num - xmlElementNode.NameOffset; xmlElementNode.Namespace.Uri.SetValue(xmlElementNode.NameOffset, 0); xmlElementNode.Prefix.SetValue(PrefixHandleType.Empty); xmlElementNode.IsEmptyElement = false; xmlElementNode.ExitScope = false; xmlElementNode.BufferOffset = num; int @byte = base.BufferReader.GetByte(xmlElementNode.NameOffset); if ((charType[@byte] & 1) == 0) { SetJsonNameWithMapping(xmlElementNode); return; } int num2 = 0; int num3 = xmlElementNode.NameOffset; while (num2 < xmlElementNode.NameLength) { @byte = base.BufferReader.GetByte(num3); if ((charType[@byte] & 2) == 0 || @byte >= 128) { SetJsonNameWithMapping(xmlElementNode); break; } num2++; num3++; } } private void ParseStartElement() { if (!buffered) { BufferElement(); } expectingFirstElementInNonPrimitiveChild = false; byte @byte = base.BufferReader.GetByte(); if (@byte == 34) { base.BufferReader.SkipByte(); ParseAndSetLocalName(); SkipWhitespaceInBufferReader(); SkipExpectedByteInBufferReader(58); SkipWhitespaceInBufferReader(); if (base.BufferReader.GetByte() == 123) { base.BufferReader.SkipByte(); expectingFirstElementInNonPrimitiveChild = true; } ReadAttributes(); } else { XmlExceptionHelper.ThrowTokenExpected(this, "\"", (char)@byte); } } private void ReadAttributes() { XmlAttributeNode xmlAttributeNode = AddAttribute(); xmlAttributeNode.LocalName.SetConstantValue(StringHandleConstStringType.Type); xmlAttributeNode.Namespace.Uri.SetValue(0, 0); xmlAttributeNode.Prefix.SetValue(PrefixHandleType.Empty); SkipWhitespaceInBufferReader(); byte @byte = base.BufferReader.GetByte(); switch (@byte) { case 34: if (!expectingFirstElementInNonPrimitiveChild) { xmlAttributeNode.Value.SetConstantValue(ValueHandleConstStringType.String); return; } xmlAttributeNode.Value.SetConstantValue(ValueHandleConstStringType.Object); ReadServerTypeAttribute(consumedObjectChar: true); return; case 110: xmlAttributeNode.Value.SetConstantValue(ValueHandleConstStringType.Null); return; case 102: case 116: xmlAttributeNode.Value.SetConstantValue(ValueHandleConstStringType.Boolean); return; case 123: xmlAttributeNode.Value.SetConstantValue(ValueHandleConstStringType.Object); ReadServerTypeAttribute(consumedObjectChar: false); return; case 125: if (expectingFirstElementInNonPrimitiveChild) { xmlAttributeNode.Value.SetConstantValue(ValueHandleConstStringType.Object); return; } XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.GetString("Encountered an unexpected character '{0}' in JSON.", (char)@byte))); return; case 91: xmlAttributeNode.Value.SetConstantValue(ValueHandleConstStringType.Array); base.BufferReader.SkipByte(); EnterJsonScope(JsonNodeType.Collection); return; } switch (@byte) { default: if (@byte != 78 && @byte != 73) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.GetString("Encountered an unexpected character '{0}' in JSON.", (char)@byte))); break; } goto case 45; case 45: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: xmlAttributeNode.Value.SetConstantValue(ValueHandleConstStringType.Number); break; } } private void ReadEscapedCharacter(bool moveToText) { base.BufferReader.SkipByte(); char c = (char)base.BufferReader.GetByte(); switch (c) { case 'u': { base.BufferReader.SkipByte(); int offset; byte[] buffer = base.BufferReader.GetBuffer(5, out offset); string @string = Encoding.UTF8.GetString(buffer, offset, 4); base.BufferReader.Advance(4); int num = ParseChar(@string, NumberStyles.HexNumber); if (char.IsHighSurrogate((char)num) && base.BufferReader.GetByte() == 92) { base.BufferReader.SkipByte(); SkipExpectedByteInBufferReader(117); buffer = base.BufferReader.GetBuffer(5, out offset); @string = Encoding.UTF8.GetString(buffer, offset, 4); base.BufferReader.Advance(4); char c2 = ParseChar(@string, NumberStyles.HexNumber); if (!char.IsLowSurrogate(c2)) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.GetString("Low surrogate char '0x{0}' not valid. Low surrogate chars range from 0xDC00 to 0xDFFF.", @string))); } num = new SurrogateChar(c2, (char)num).Char; } if (buffer[offset + 4] == 34) { base.BufferReader.SkipByte(); if (moveToText) { MoveToAtomicText().Value.SetCharValue(num); } complexTextMode = JsonComplexTextMode.None; } else { if (moveToText) { MoveToComplexText().Value.SetCharValue(num); } complexTextMode = JsonComplexTextMode.QuotedText; } return; } case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; default: XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.GetString("Encountered an unexpected character '{0}' in JSON.", c))); break; case '"': case '/': case '\\': break; } base.BufferReader.SkipByte(); if (base.BufferReader.GetByte() == 34) { base.BufferReader.SkipByte(); if (moveToText) { MoveToAtomicText().Value.SetCharValue(c); } complexTextMode = JsonComplexTextMode.None; } else { if (moveToText) { MoveToComplexText().Value.SetCharValue(c); } complexTextMode = JsonComplexTextMode.QuotedText; } } private void ReadNonExistentElementName(StringHandleConstStringType elementName) { EnterJsonScope(JsonNodeType.Object); XmlElementNode xmlElementNode = EnterScope(); xmlElementNode.LocalName.SetConstantValue(elementName); xmlElementNode.Namespace.Uri.SetValue(xmlElementNode.NameOffset, 0); xmlElementNode.Prefix.SetValue(PrefixHandleType.Empty); xmlElementNode.BufferOffset = base.BufferReader.Offset; xmlElementNode.IsEmptyElement = false; xmlElementNode.ExitScope = false; ReadAttributes(); } private int ReadNonFFFE() { int offset; byte[] buffer = base.BufferReader.GetBuffer(3, out offset); if (buffer[offset + 1] == 191 && (buffer[offset + 2] == 190 || buffer[offset + 2] == 191)) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.GetString("FFFE in JSON is invalid."))); } return 3; } private void ReadNumericalText() { int num; int offset; int offsetMax; if (buffered) { num = ComputeNumericalTextLength(base.BufferReader.GetBuffer(out offset, out offsetMax), offset, offsetMax); } else { byte[] buffer = base.BufferReader.GetBuffer(2048, out offset, out offsetMax); num = BreakText(length: ComputeNumericalTextLength(buffer, offset, offsetMax), buffer: buffer, offset: offset); } base.BufferReader.Advance(num); if (offset <= offsetMax - num) { MoveToAtomicText().Value.SetValue(ValueHandleType.UTF8, offset, num); complexTextMode = JsonComplexTextMode.None; } else { MoveToComplexText().Value.SetValue(ValueHandleType.UTF8, offset, num); complexTextMode = JsonComplexTextMode.NumericalText; } } private void ReadQuotedText(bool moveToText) { int offset; int offsetMax; bool escaped; bool flag; int num; if (buffered) { num = ComputeQuotedTextLengthUntilEndQuote(base.BufferReader.GetBuffer(out offset, out offsetMax), offset, offsetMax, out escaped); flag = offset < offsetMax - num; } else { byte[] buffer = base.BufferReader.GetBuffer(2048, out offset, out offsetMax); num = ComputeQuotedTextLengthUntilEndQuote(buffer, offset, offsetMax, out escaped); flag = offset < offsetMax - num; num = BreakText(buffer, offset, num); } if (escaped && base.BufferReader.GetByte() == 239) { offset = base.BufferReader.Offset; num = ReadNonFFFE(); } base.BufferReader.Advance(num); if (!escaped && flag) { if (moveToText) { MoveToAtomicText().Value.SetValue(ValueHandleType.UTF8, offset, num); } SkipExpectedByteInBufferReader(34); complexTextMode = JsonComplexTextMode.None; } else if (num == 0 && escaped) { ReadEscapedCharacter(moveToText); } else { if (moveToText) { MoveToComplexText().Value.SetValue(ValueHandleType.UTF8, offset, num); } complexTextMode = JsonComplexTextMode.QuotedText; } } private void ReadServerTypeAttribute(bool consumedObjectChar) { if (!consumedObjectChar) { SkipExpectedByteInBufferReader(123); SkipWhitespaceInBufferReader(); byte @byte = base.BufferReader.GetByte(); if (@byte != 34 && @byte != 125) { XmlExceptionHelper.ThrowTokenExpected(this, "\"", (char)@byte); } } else { SkipWhitespaceInBufferReader(); } byte[] buffer = base.BufferReader.GetBuffer(8, out var offset, out var offsetMax); if (offset + 8 <= offsetMax && buffer[offset] == 34 && buffer[offset + 1] == 95 && buffer[offset + 2] == 95 && buffer[offset + 3] == 116 && buffer[offset + 4] == 121 && buffer[offset + 5] == 112 && buffer[offset + 6] == 101 && buffer[offset + 7] == 34) { XmlAttributeNode xmlAttributeNode = AddAttribute(); xmlAttributeNode.LocalName.SetValue(offset + 1, 6); xmlAttributeNode.Namespace.Uri.SetValue(0, 0); xmlAttributeNode.Prefix.SetValue(PrefixHandleType.Empty); base.BufferReader.Advance(8); if (!buffered) { BufferElement(); } SkipWhitespaceInBufferReader(); SkipExpectedByteInBufferReader(58); SkipWhitespaceInBufferReader(); SkipExpectedByteInBufferReader(34); buffer = base.BufferReader.GetBuffer(out offset, out offsetMax); do { if (base.BufferReader.GetByte() == 92) { ReadEscapedCharacter(moveToText: false); } else { ReadQuotedText(moveToText: false); } } while (complexTextMode == JsonComplexTextMode.QuotedText); xmlAttributeNode.Value.SetValue(ValueHandleType.UTF8, offset, base.BufferReader.Offset - 1 - offset); SkipWhitespaceInBufferReader(); if (base.BufferReader.GetByte() == 44) { base.BufferReader.SkipByte(); readServerTypeElement = true; } } if (base.BufferReader.GetByte() == 125) { base.BufferReader.SkipByte(); readServerTypeElement = false; expectingFirstElementInNonPrimitiveChild = false; } else { readServerTypeElement = true; } } private void ResetState() { complexTextMode = JsonComplexTextMode.None; expectingFirstElementInNonPrimitiveChild = false; charactersToSkipOnNextRead = new byte[2]; scopeDepth = 0; if (scopes != null && scopes.Length > 25) { scopes = null; } } private void SetJsonNameWithMapping(XmlElementNode elementNode) { Namespace @namespace = AddNamespace(); @namespace.Prefix.SetValue(PrefixHandleType.A); @namespace.Uri.SetConstantValue(StringHandleConstStringType.Item); AddXmlnsAttribute(@namespace); XmlAttributeNode xmlAttributeNode = AddAttribute(); xmlAttributeNode.LocalName.SetConstantValue(StringHandleConstStringType.Item); xmlAttributeNode.Namespace.Uri.SetValue(0, 0); xmlAttributeNode.Prefix.SetValue(PrefixHandleType.Empty); xmlAttributeNode.Value.SetValue(ValueHandleType.UTF8, elementNode.NameOffset, elementNode.NameLength); elementNode.NameLength = 0; elementNode.Prefix.SetValue(PrefixHandleType.A); elementNode.LocalName.SetConstantValue(StringHandleConstStringType.Item); elementNode.Namespace = @namespace; } private void SkipExpectedByteInBufferReader(byte characterToSkip) { if (base.BufferReader.GetByte() != characterToSkip) { char c = (char)characterToSkip; XmlExceptionHelper.ThrowTokenExpected(this, c.ToString(), (char)base.BufferReader.GetByte()); } base.BufferReader.SkipByte(); } private void SkipWhitespaceInBufferReader() { byte ch; while (TryGetByte(out ch) && IsWhitespace(ch)) { base.BufferReader.SkipByte(); } } private bool TryGetByte(out byte ch) { int offset; int offsetMax; byte[] buffer = base.BufferReader.GetBuffer(1, out offset, out offsetMax); if (offset < offsetMax) { ch = buffer[offset]; return true; } ch = 0; return false; } private string UnescapeJsonString(string val) { if (val == null) { return null; } StringBuilder stringBuilder = null; int startIndex = 0; int num = 0; for (int i = 0; i < val.Length; i++) { if (val[i] == '\\') { i++; if (stringBuilder == null) { stringBuilder = new StringBuilder(); } stringBuilder.Append(val, startIndex, num); if (i >= val.Length) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.GetString("Encountered an unexpected character '{0}' in JSON.", val[i]))); } switch (val[i]) { case '"': case '\'': case '/': case '\\': stringBuilder.Append(val[i]); break; case 'b': stringBuilder.Append('\b'); break; case 'f': stringBuilder.Append('\f'); break; case 'n': stringBuilder.Append('\n'); break; case 'r': stringBuilder.Append('\r'); break; case 't': stringBuilder.Append('\t'); break; case 'u': if (i + 3 >= val.Length) { XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.GetString("Encountered an unexpected character '{0}' in JSON.", val[i]))); } stringBuilder.Append(ParseChar(val.Substring(i + 1, 4), NumberStyles.HexNumber)); i += 4; break; } startIndex = i + 1; num = 0; } else { num++; } } if (stringBuilder == null) { return val; } if (num > 0) { stringBuilder.Append(val, startIndex, num); } return stringBuilder.ToString(); } } internal class XmlJsonWriter : XmlDictionaryWriter, IXmlJsonWriterInitializer { private enum JsonDataType { None, Null, Boolean, Number, String, Object, Array } [Flags] private enum NameState { None = 0, IsWritingNameWithMapping = 1, IsWritingNameAttribute = 2, WrittenNameWithMapping = 4 } private class JsonNodeWriter : XmlUTF8NodeWriter { [SecurityCritical] internal unsafe void WriteChars(char* chars, int charCount) { UnsafeWriteUTF8Chars(chars, charCount); } } private const char BACK_SLASH = '\\'; private const char FORWARD_SLASH = '/'; private const char HIGH_SURROGATE_START = '\ud800'; private const char LOW_SURROGATE_END = '\udfff'; private const char MAX_CHAR = '\ufffe'; private const char WHITESPACE = ' '; private const char CARRIAGE_RETURN = '\r'; private const char NEWLINE = '\n'; private const char BACKSPACE = '\b'; private const char FORM_FEED = '\f'; private const char HORIZONTAL_TABULATION = '\t'; private const string xmlNamespace = "http://www.w3.org/XML/1998/namespace"; private const string xmlnsNamespace = "http://www.w3.org/2000/xmlns/"; [SecurityCritical] private static BinHexEncoding binHexEncoding; private static char[] CharacterAbbrevs; private string attributeText; private JsonDataType dataType; private int depth; private bool endElementBuffer; private bool isWritingDataTypeAttribute; private bool isWritingServerTypeAttribute; private bool isWritingXmlnsAttribute; private bool isWritingXmlnsAttributeDefaultNs; private NameState nameState; private JsonNodeType nodeType; private JsonNodeWriter nodeWriter; private JsonNodeType[] scopes; private string serverTypeValue; private WriteState writeState; private bool wroteServerTypeAttribute; private bool indent; private string indentChars; private int indentLevel; public override XmlWriterSettings Settings => null; public override WriteState WriteState { get { if (writeState == WriteState.Closed) { return WriteState.Closed; } if (HasOpenAttribute) { return WriteState.Attribute; } switch (nodeType) { case JsonNodeType.None: return WriteState.Start; case JsonNodeType.Element: return WriteState.Element; case JsonNodeType.EndElement: case JsonNodeType.QuotedText: case JsonNodeType.StandaloneText: return WriteState.Content; default: return WriteState.Error; } } } public override string XmlLang => null; public override XmlSpace XmlSpace => XmlSpace.None; private static BinHexEncoding BinHexEncoding { [SecuritySafeCritical] get { if (binHexEncoding == null) { binHexEncoding = new BinHexEncoding(); } return binHexEncoding; } } private bool HasOpenAttribute { get { if (!isWritingDataTypeAttribute && !isWritingServerTypeAttribute && !IsWritingNameAttribute) { return isWritingXmlnsAttribute; } return true; } } private bool IsClosed => WriteState == WriteState.Closed; private bool IsWritingCollection { get { if (depth > 0) { return scopes[depth] == JsonNodeType.Collection; } return false; } } private bool IsWritingNameAttribute => (nameState & NameState.IsWritingNameAttribute) == NameState.IsWritingNameAttribute; private bool IsWritingNameWithMapping => (nameState & NameState.IsWritingNameWithMapping) == NameState.IsWritingNameWithMapping; private bool WrittenNameWithMapping => (nameState & NameState.WrittenNameWithMapping) == NameState.WrittenNameWithMapping; public XmlJsonWriter() : this(indent: false, null) { } public XmlJsonWriter(bool indent, string indentChars) { this.indent = indent; if (indent) { if (indentChars == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("indentChars"); } this.indentChars = indentChars; } InitializeWriter(); if (CharacterAbbrevs == null) { CharacterAbbrevs = GetCharacterAbbrevs(); } } private static char[] GetCharacterAbbrevs() { char[] array = new char[32]; for (int i = 0; i < 32; i++) { if (!System.LocalAppContextSwitches.DoNotUseEcmaScriptV6EscapeControlCharacter && TryEscapeControlCharacter((char)i, out var abbrev)) { array[i] = abbrev; } else { array[i] = '\0'; } } return array; } private static bool TryEscapeControlCharacter(char ch, out char abbrev) { switch (ch) { case '\b': abbrev = 'b'; break; case '\t': abbrev = 't'; break; case '\n': abbrev = 'n'; break; case '\f': abbrev = 'f'; break; case '\r': abbrev = 'r'; break; default: abbrev = ' '; return false; } return true; } public override void Close() { if (IsClosed) { return; } try { WriteEndDocument(); } finally { try { nodeWriter.Flush(); nodeWriter.Close(); } finally { writeState = WriteState.Closed; if (depth != 0) { depth = 0; } } } } public override void Flush() { if (IsClosed) { ThrowClosed(); } nodeWriter.Flush(); } public override string LookupPrefix(string ns) { if (ns == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ns"); } if (ns == "http://www.w3.org/2000/xmlns/") { return "xmlns"; } if (ns == "http://www.w3.org/XML/1998/namespace") { return "xml"; } if (ns == string.Empty) { return string.Empty; } return null; } public void SetOutput(Stream stream, Encoding encoding, bool ownsStream) { if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream"); } if (encoding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encoding"); } if (encoding.WebName != Encoding.UTF8.WebName) { stream = new JsonEncodingStreamWrapper(stream, encoding, isReader: false); } else { encoding = null; } if (nodeWriter == null) { nodeWriter = new JsonNodeWriter(); } nodeWriter.SetOutput(stream, ownsStream, encoding); InitializeWriter(); } public override void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, string localName, string namespaceUri, short[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, string localName, string namespaceUri, int[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, string localName, string namespaceUri, long[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("JSON WriteArray is not supported."))); } public override void WriteBase64(byte[] buffer, int index, int count) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); } if (index < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", SR.GetString("The value of this argument must be non-negative."))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - index) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString("JSON size exceeded remaining buffer space, by {0} byte(s).", buffer.Length - index))); } StartText(); nodeWriter.WriteBase64Text(buffer, 0, buffer, index, count); } public override void WriteBinHex(byte[] buffer, int index, int count) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); } if (index < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", SR.GetString("The value of this argument must be non-negative."))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - index) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString("JSON size exceeded remaining buffer space, by {0} byte(s).", buffer.Length - index))); } StartText(); WriteEscapedJsonString(BinHexEncoding.GetString(buffer, index, count)); } public override void WriteCData(string text) { WriteString(text); } public override void WriteCharEntity(char ch) { WriteString(ch.ToString()); } public override void WriteChars(char[] buffer, int index, int count) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); } if (index < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", SR.GetString("The value of this argument must be non-negative."))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - index) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString("JSON size exceeded remaining buffer space, by {0} byte(s).", buffer.Length - index))); } WriteString(new string(buffer, index, count)); } public override void WriteComment(string text) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("Method {0} is not supported in JSON.", "WriteComment"))); } public override void WriteDocType(string name, string pubid, string sysid, string subset) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("Method {0} is not supported in JSON.", "WriteDocType"))); } public override void WriteEndAttribute() { if (IsClosed) { ThrowClosed(); } if (!HasOpenAttribute) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("WriteEndAttribute was called while there is no open attribute."))); } if (isWritingDataTypeAttribute) { switch (attributeText) { case "number": ThrowIfServerTypeWritten("number"); dataType = JsonDataType.Number; break; case "string": ThrowIfServerTypeWritten("string"); dataType = JsonDataType.String; break; case "array": ThrowIfServerTypeWritten("array"); dataType = JsonDataType.Array; break; case "object": dataType = JsonDataType.Object; break; case "null": ThrowIfServerTypeWritten("null"); dataType = JsonDataType.Null; break; case "boolean": ThrowIfServerTypeWritten("boolean"); dataType = JsonDataType.Boolean; break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Unexpected attribute value '{0}'.", attributeText))); } attributeText = null; isWritingDataTypeAttribute = false; if (!IsWritingNameWithMapping || WrittenNameWithMapping) { WriteDataTypeServerType(); } } else if (isWritingServerTypeAttribute) { serverTypeValue = attributeText; attributeText = null; isWritingServerTypeAttribute = false; if ((!IsWritingNameWithMapping || WrittenNameWithMapping) && dataType == JsonDataType.Object) { WriteServerTypeAttribute(); } } else if (IsWritingNameAttribute) { WriteJsonElementName(attributeText); attributeText = null; nameState = NameState.IsWritingNameWithMapping | NameState.WrittenNameWithMapping; WriteDataTypeServerType(); } else if (isWritingXmlnsAttribute) { if (!string.IsNullOrEmpty(attributeText) && isWritingXmlnsAttributeDefaultNs) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("ns", SR.GetString("JSON namespace is specified as '{0}' but it must be empty.", attributeText)); } attributeText = null; isWritingXmlnsAttribute = false; isWritingXmlnsAttributeDefaultNs = false; } } public override void WriteEndDocument() { if (IsClosed) { ThrowClosed(); } if (nodeType != 0) { while (depth > 0) { WriteEndElement(); } } } public override void WriteEndElement() { if (IsClosed) { ThrowClosed(); } if (depth == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Encountered an end element while there was no open element in JSON writer."))); } if (HasOpenAttribute) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("JSON attribute must be closed first before calling {0} method.", "WriteEndElement"))); } endElementBuffer = false; JsonNodeType jsonNodeType = ExitScope(); if (jsonNodeType == JsonNodeType.Collection) { indentLevel--; if (indent) { if (nodeType == JsonNodeType.Element) { nodeWriter.WriteText(32); } else { WriteNewLine(); WriteIndent(); } } nodeWriter.WriteText(93); jsonNodeType = ExitScope(); } else if (nodeType == JsonNodeType.QuotedText) { WriteJsonQuote(); } else if (nodeType == JsonNodeType.Element) { if (dataType == JsonDataType.None && serverTypeValue != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("On JSON writer data type '{0}' must be specified. Object string is '{1}', server type string is '{2}'.", "type", "object", "__type"))); } if (IsWritingNameWithMapping && !WrittenNameWithMapping) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("On JSON writer data type '{0}' must be specified. Object string is '{1}', server type string is '{2}'.", "item", string.Empty, "item"))); } if (dataType == JsonDataType.None || dataType == JsonDataType.String) { nodeWriter.WriteText(34); nodeWriter.WriteText(34); } } if (depth != 0) { switch (jsonNodeType) { case JsonNodeType.Element: endElementBuffer = true; break; case JsonNodeType.Object: indentLevel--; if (indent) { if (nodeType == JsonNodeType.Element) { nodeWriter.WriteText(32); } else { WriteNewLine(); WriteIndent(); } } nodeWriter.WriteText(125); if (depth > 0 && scopes[depth] == JsonNodeType.Element) { ExitScope(); endElementBuffer = true; } break; } } dataType = JsonDataType.None; nodeType = JsonNodeType.EndElement; nameState = NameState.None; wroteServerTypeAttribute = false; } public override void WriteEntityRef(string name) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("Method {0} is not supported in JSON.", "WriteEntityRef"))); } public override void WriteFullEndElement() { WriteEndElement(); } public override void WriteProcessingInstruction(string name, string text) { if (IsClosed) { ThrowClosed(); } if (!name.Equals("xml", StringComparison.OrdinalIgnoreCase)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString("processing instruction is not supported in JSON writer."), "name")); } if (WriteState != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Attempt to write invalid XML declration."))); } } public override void WriteQualifiedName(string localName, string ns) { if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localName"); } if (localName.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("localName", SR.GetString("Empty string is invalid as a local name.")); } if (ns == null) { ns = string.Empty; } base.WriteQualifiedName(localName, ns); } public override void WriteRaw(string data) { WriteString(data); } public override void WriteRaw(char[] buffer, int index, int count) { if (buffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer"); } if (index < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", SR.GetString("The value of this argument must be non-negative."))); } if (count < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString("The value of this argument must be non-negative."))); } if (count > buffer.Length - index) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString("JSON size exceeded remaining buffer space, by {0} byte(s).", buffer.Length - index))); } WriteString(new string(buffer, index, count)); } public override void WriteStartAttribute(string prefix, string localName, string ns) { if (IsClosed) { ThrowClosed(); } if (!string.IsNullOrEmpty(prefix)) { if (!IsWritingNameWithMapping || !(prefix == "xmlns")) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("prefix", SR.GetString("JSON prefix must be null or empty. '{0}' is specified instead.", prefix)); } if (ns != null && ns != "http://www.w3.org/2000/xmlns/") { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString("The prefix '{0}' is bound to the namespace '{1}' and cannot be changed to '{2}'.", "xmlns", "http://www.w3.org/2000/xmlns/", ns), "ns")); } } else if (IsWritingNameWithMapping && ns == "http://www.w3.org/2000/xmlns/" && localName != "xmlns") { prefix = "xmlns"; } if (!string.IsNullOrEmpty(ns)) { if (IsWritingNameWithMapping && ns == "http://www.w3.org/2000/xmlns/") { prefix = "xmlns"; } else { if (!string.IsNullOrEmpty(prefix) || !(localName == "xmlns") || !(ns == "http://www.w3.org/2000/xmlns/")) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("ns", SR.GetString("JSON namespace is specified as '{0}' but it must be empty.", ns)); } prefix = "xmlns"; isWritingXmlnsAttributeDefaultNs = true; } } if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localName"); } if (localName.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("localName", SR.GetString("Empty string is invalid as a local name.")); } if (nodeType != JsonNodeType.Element && !wroteServerTypeAttribute) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("JSON attribute must have an owner element."))); } if (HasOpenAttribute) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("JSON attribute must be closed first before calling {0} method.", "WriteStartAttribute"))); } if (prefix == "xmlns") { isWritingXmlnsAttribute = true; return; } switch (localName) { case "type": if (dataType != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("JSON attribute '{0}' is already written.", "type"))); } isWritingDataTypeAttribute = true; break; case "__type": if (serverTypeValue != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("JSON attribute '{0}' is already written.", "__type"))); } if (dataType != 0 && dataType != JsonDataType.Object) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Server type is specified for invalid data type in JSON. Server type: '{0}', type: '{1}', dataType: '{2}', object: '{3}'.", "__type", "type", dataType.ToString().ToLowerInvariant(), "object"))); } isWritingServerTypeAttribute = true; break; case "item": if (WrittenNameWithMapping) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("JSON attribute '{0}' is already written.", "item"))); } if (!IsWritingNameWithMapping) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Encountered an end element while there was no open element in JSON writer."))); } nameState |= NameState.IsWritingNameAttribute; break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("localName", SR.GetString("Unexpected attribute local name '{0}'.", localName)); } } public override void WriteStartDocument(bool standalone) { WriteStartDocument(); } public override void WriteStartDocument() { if (IsClosed) { ThrowClosed(); } if (WriteState != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Invalid write state {1} for '{0}' method.", "WriteStartDocument", WriteState.ToString()))); } } public override void WriteStartElement(string prefix, string localName, string ns) { if (localName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localName"); } if (localName.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("localName", SR.GetString("Empty string is invalid as a local name.")); } if (!string.IsNullOrEmpty(prefix) && (string.IsNullOrEmpty(ns) || !TrySetWritingNameWithMapping(localName, ns))) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("prefix", SR.GetString("JSON prefix must be null or empty. '{0}' is specified instead.", prefix)); } if (!string.IsNullOrEmpty(ns) && !TrySetWritingNameWithMapping(localName, ns)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("ns", SR.GetString("JSON namespace is specified as '{0}' but it must be empty.", ns)); } if (IsClosed) { ThrowClosed(); } if (HasOpenAttribute) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("JSON attribute must be closed first before calling {0} method.", "WriteStartElement"))); } if (nodeType != 0 && depth == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Multiple root element is not allowed on JSON writer."))); } switch (nodeType) { case JsonNodeType.None: if (!localName.Equals("root")) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Invalid root element name '{0}' (root element is '{1}' in JSON).", localName, "root"))); } EnterScope(JsonNodeType.Element); break; case JsonNodeType.Element: if (dataType != JsonDataType.Array && dataType != JsonDataType.Object) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Either Object or Array of JSON node type must be specified."))); } if (indent) { WriteNewLine(); WriteIndent(); } if (!IsWritingCollection) { if (nameState != NameState.IsWritingNameWithMapping) { WriteJsonElementName(localName); } } else if (!localName.Equals("item")) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Invalid JSON item name '{0}' for array element (item element is '{1}' in JSON).", localName, "item"))); } EnterScope(JsonNodeType.Element); break; case JsonNodeType.EndElement: if (endElementBuffer) { nodeWriter.WriteText(44); } if (indent) { WriteNewLine(); WriteIndent(); } if (!IsWritingCollection) { if (nameState != NameState.IsWritingNameWithMapping) { WriteJsonElementName(localName); } } else if (!localName.Equals("item")) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Invalid JSON item name '{0}' for array element (item element is '{1}' in JSON).", localName, "item"))); } EnterScope(JsonNodeType.Element); break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Invalid call to JSON WriteStartElement method."))); } isWritingDataTypeAttribute = false; isWritingServerTypeAttribute = false; isWritingXmlnsAttribute = false; wroteServerTypeAttribute = false; serverTypeValue = null; dataType = JsonDataType.None; nodeType = JsonNodeType.Element; } public override void WriteString(string text) { if (HasOpenAttribute && text != null) { attributeText += text; return; } if (text == null) { text = string.Empty; } if ((dataType != JsonDataType.Array && dataType != JsonDataType.Object && nodeType != JsonNodeType.EndElement) || !XmlConverter.IsWhitespace(text)) { StartText(); WriteEscapedJsonString(text); } } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { WriteString(string.Concat(highChar, lowChar)); } public override void WriteValue(bool value) { StartText(); nodeWriter.WriteBoolText(value); } public override void WriteValue(decimal value) { StartText(); nodeWriter.WriteDecimalText(value); } public override void WriteValue(double value) { StartText(); nodeWriter.WriteDoubleText(value); } public override void WriteValue(float value) { StartText(); nodeWriter.WriteFloatText(value); } public override void WriteValue(int value) { StartText(); nodeWriter.WriteInt32Text(value); } public override void WriteValue(long value) { StartText(); nodeWriter.WriteInt64Text(value); } public override void WriteValue(Guid value) { StartText(); nodeWriter.WriteGuidText(value); } public override void WriteValue(DateTime value) { StartText(); nodeWriter.WriteDateTimeText(value); } public override void WriteValue(string value) { WriteString(value); } public override void WriteValue(TimeSpan value) { StartText(); nodeWriter.WriteTimeSpanText(value); } public override void WriteValue(UniqueId value) { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } StartText(); nodeWriter.WriteUniqueIdText(value); } public override void WriteValue(object value) { if (IsClosed) { ThrowClosed(); } if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } if (value is Array) { WriteValue((Array)value); } else if (value is IStreamProvider) { WriteValue((IStreamProvider)value); } else { WritePrimitiveValue(value); } } public override void WriteWhitespace(string ws) { if (IsClosed) { ThrowClosed(); } if (ws == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ws"); } for (int i = 0; i < ws.Length; i++) { char c = ws[i]; if (c != ' ' && c != '\t' && c != '\n' && c != '\r') { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("ws", SR.GetString("Only whitespace characters are allowed for {1} method. The specified value is '{0}'", c.ToString(), "WriteWhitespace")); } } WriteString(ws); } public override void WriteXmlAttribute(string localName, string value) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("Method {0} is not supported in JSON.", "WriteXmlAttribute"))); } public override void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString value) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("Method {0} is not supported in JSON.", "WriteXmlAttribute"))); } public override void WriteXmlnsAttribute(string prefix, string namespaceUri) { if (!IsWritingNameWithMapping) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("Method {0} is not supported in JSON.", "WriteXmlnsAttribute"))); } } public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString namespaceUri) { if (!IsWritingNameWithMapping) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString("Method {0} is not supported in JSON.", "WriteXmlnsAttribute"))); } } internal static bool CharacterNeedsEscaping(char ch) { if (ch != '/' && ch != '"' && ch >= ' ' && ch != '\\') { if (ch >= '\ud800') { if (ch > '\udfff') { return ch >= '\ufffe'; } return true; } return false; } return true; } private static void ThrowClosed() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString("JSON writer is already closed."))); } private void CheckText(JsonNodeType nextNodeType) { if (IsClosed) { ThrowClosed(); } if (depth == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString("Text cannot be written outside the root element."))); } if (nextNodeType == JsonNodeType.StandaloneText && nodeType == JsonNodeType.QuotedText) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("JSON writer cannot write standalone text after quoted text."))); } } private void EnterScope(JsonNodeType currentNodeType) { depth++; if (scopes == null) { scopes = new JsonNodeType[4]; } else if (scopes.Length == depth) { JsonNodeType[] destinationArray = new JsonNodeType[depth * 2]; Array.Copy(scopes, destinationArray, depth); scopes = destinationArray; } scopes[depth] = currentNodeType; } private JsonNodeType ExitScope() { JsonNodeType result = scopes[depth]; scopes[depth] = JsonNodeType.None; depth--; return result; } private void InitializeWriter() { nodeType = JsonNodeType.None; dataType = JsonDataType.None; isWritingDataTypeAttribute = false; wroteServerTypeAttribute = false; isWritingServerTypeAttribute = false; serverTypeValue = null; attributeText = null; if (depth != 0) { depth = 0; } if (scopes != null && scopes.Length > 25) { scopes = null; } writeState = WriteState.Start; endElementBuffer = false; indentLevel = 0; } private static bool IsUnicodeNewlineCharacter(char c) { if (c != '\u0085' && c != '\u2028') { return c == '\u2029'; } return true; } private void StartText() { if (HasOpenAttribute) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString("On JSON writer WriteString must be used for writing attribute values."))); } if (dataType == JsonDataType.None && serverTypeValue != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("On JSON writer data type '{0}' must be specified. Object string is '{1}', server type string is '{2}'.", "type", "object", "__type"))); } if (IsWritingNameWithMapping && !WrittenNameWithMapping) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("On JSON writer data type '{0}' must be specified. Object string is '{1}', server type string is '{2}'.", "item", string.Empty, "item"))); } if (dataType == JsonDataType.String || dataType == JsonDataType.None) { CheckText(JsonNodeType.QuotedText); if (nodeType != JsonNodeType.QuotedText) { WriteJsonQuote(); } nodeType = JsonNodeType.QuotedText; } else if (dataType == JsonDataType.Number || dataType == JsonDataType.Boolean) { CheckText(JsonNodeType.StandaloneText); nodeType = JsonNodeType.StandaloneText; } else { ThrowInvalidAttributeContent(); } } private void ThrowIfServerTypeWritten(string dataTypeSpecified) { if (serverTypeValue != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("The specified data type is invalid for server type. Type: '{0}', specified data type: '{1}', server type: '{2}', object '{3}'.", "type", dataTypeSpecified, "__type", "object"))); } } private void ThrowInvalidAttributeContent() { if (HasOpenAttribute) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("Invalid method call state between start and end attribute."))); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString("JSON writer cannot write text after non-text attribute. Data type is '{0}'.", dataType.ToString().ToLowerInvariant()))); } private bool TrySetWritingNameWithMapping(string localName, string ns) { if (localName.Equals("item") && ns.Equals("item")) { nameState = NameState.IsWritingNameWithMapping; return true; } return false; } private void WriteDataTypeServerType() { if (dataType != 0) { switch (dataType) { case JsonDataType.Array: EnterScope(JsonNodeType.Collection); nodeWriter.WriteText(91); indentLevel++; break; case JsonDataType.Object: EnterScope(JsonNodeType.Object); nodeWriter.WriteText(123); indentLevel++; break; case JsonDataType.Null: nodeWriter.WriteText("null"); break; } if (serverTypeValue != null) { WriteServerTypeAttribute(); } } } [SecuritySafeCritical] private unsafe void WriteEscapedJsonString(string str) { fixed (char* ptr = str) { int num = 0; int i; for (i = 0; i < str.Length; i++) { char c = ptr[i]; if (c <= '/') { if (c == '/' || c == '"') { nodeWriter.WriteChars(ptr + num, i - num); nodeWriter.WriteText(92); nodeWriter.WriteText(c); num = i + 1; } else if (c < ' ') { nodeWriter.WriteChars(ptr + num, i - num); nodeWriter.WriteText(92); if (CharacterAbbrevs[(uint)c] == '\0') { nodeWriter.WriteText(117); nodeWriter.WriteText(string.Format(CultureInfo.InvariantCulture, "{0:x4}", (int)c)); num = i + 1; } else { nodeWriter.WriteText(CharacterAbbrevs[(uint)c]); num = i + 1; } } } else if (c == '\\') { nodeWriter.WriteChars(ptr + num, i - num); nodeWriter.WriteText(92); nodeWriter.WriteText(c); num = i + 1; } else if ((c >= '\ud800' && (c <= '\udfff' || c >= '\ufffe')) || IsUnicodeNewlineCharacter(c)) { nodeWriter.WriteChars(ptr + num, i - num); nodeWriter.WriteText(92); nodeWriter.WriteText(117); nodeWriter.WriteText(string.Format(CultureInfo.InvariantCulture, "{0:x4}", (int)c)); num = i + 1; } } if (num < i) { nodeWriter.WriteChars(ptr + num, i - num); } } } private void WriteIndent() { for (int i = 0; i < indentLevel; i++) { nodeWriter.WriteText(indentChars); } } private void WriteNewLine() { nodeWriter.WriteText(13); nodeWriter.WriteText(10); } private void WriteJsonElementName(string localName) { WriteJsonQuote(); WriteEscapedJsonString(localName); WriteJsonQuote(); nodeWriter.WriteText(58); if (indent) { nodeWriter.WriteText(32); } } private void WriteJsonQuote() { nodeWriter.WriteText(34); } private void WritePrimitiveValue(object value) { if (IsClosed) { ThrowClosed(); } if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } if (value is ulong) { WriteValue((ulong)value); return; } if (value is string) { WriteValue((string)value); return; } if (value is int) { WriteValue((int)value); return; } if (value is long) { WriteValue((long)value); return; } if (value is bool) { WriteValue((bool)value); return; } if (value is double) { WriteValue((double)value); return; } if (value is DateTime) { WriteValue((DateTime)value); return; } if (value is float) { WriteValue((float)value); return; } if (value is decimal) { WriteValue((decimal)value); return; } if (value is XmlDictionaryString) { WriteValue((XmlDictionaryString)value); return; } if (value is UniqueId) { WriteValue((UniqueId)value); return; } if (value is Guid) { WriteValue((Guid)value); return; } if (value is TimeSpan) { WriteValue((TimeSpan)value); return; } if (value.GetType().IsArray) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString("Nested array is not supported in JSON: '{0}'"), "value")); } base.WriteValue(value); } private void WriteServerTypeAttribute() { string value = serverTypeValue; JsonDataType jsonDataType = dataType; NameState nameState = this.nameState; WriteStartElement("__type"); WriteValue(value); WriteEndElement(); dataType = jsonDataType; this.nameState = nameState; wroteServerTypeAttribute = true; } private void WriteValue(ulong value) { StartText(); nodeWriter.WriteUInt64Text(value); } private void WriteValue(Array array) { JsonDataType jsonDataType = dataType; dataType = JsonDataType.String; StartText(); for (int i = 0; i < array.Length; i++) { if (i != 0) { nodeWriter.WriteText(32); } WritePrimitiveValue(array.GetValue(i)); } dataType = jsonDataType; } } internal class XmlObjectSerializerReadContextComplexJson : XmlObjectSerializerReadContextComplex { private string extensionDataValueType; private DateTimeFormat dateTimeFormat; private bool useSimpleDictionaryFormat; internal IList SerializerKnownTypeList => serializerKnownTypeList; public bool UseSimpleDictionaryFormat => useSimpleDictionaryFormat; public XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract) : base(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(StreamingContextStates.All), serializer.IgnoreExtensionDataObject) { base.rootTypeDataContract = rootTypeDataContract; serializerKnownTypeList = serializer.knownTypeList; dataContractSurrogate = serializer.DataContractSurrogate; dateTimeFormat = serializer.DateTimeFormat; useSimpleDictionaryFormat = serializer.UseSimpleDictionaryFormat; } protected override void StartReadExtensionDataValue(XmlReaderDelegator xmlReader) { extensionDataValueType = xmlReader.GetAttribute("type"); } protected override IDataNode ReadPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { IDataNode result; switch (extensionDataValueType) { case null: case "string": result = new DataNode(xmlReader.ReadContentAsString()); break; case "boolean": result = new DataNode(xmlReader.ReadContentAsBoolean()); break; case "number": result = ReadNumericalPrimitiveExtensionDataValue(xmlReader); break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Unexpected attribute value '{0}'.", extensionDataValueType))); } xmlReader.ReadEndElement(); return result; } private IDataNode ReadNumericalPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader) { TypeCode objectTypeCode; object obj = JsonObjectDataContract.ParseJsonNumber(xmlReader.ReadContentAsString(), out objectTypeCode); return objectTypeCode switch { TypeCode.Byte => new DataNode((byte)obj), TypeCode.SByte => new DataNode((sbyte)obj), TypeCode.Int16 => new DataNode((short)obj), TypeCode.Int32 => new DataNode((int)obj), TypeCode.Int64 => new DataNode((long)obj), TypeCode.UInt16 => new DataNode((ushort)obj), TypeCode.UInt32 => new DataNode((uint)obj), TypeCode.UInt64 => new DataNode((ulong)obj), TypeCode.Single => new DataNode((float)obj), TypeCode.Double => new DataNode((double)obj), TypeCode.Decimal => new DataNode((decimal)obj), _ => throw Fx.AssertAndThrow("JsonObjectDataContract.ParseJsonNumber shouldn't return a TypeCode that we're not expecting"), }; } internal static XmlObjectSerializerReadContextComplexJson CreateContext(DataContractJsonSerializer serializer, DataContract rootTypeDataContract) { return new XmlObjectSerializerReadContextComplexJson(serializer, rootTypeDataContract); } internal override int GetArraySize() { return -1; } protected override object ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) { return DataContractJsonSerializer.ReadJsonValue(dataContract, reader, this); } internal override void ReadAttributes(XmlReaderDelegator xmlReader) { if (attributes == null) { attributes = new Attributes(); } attributes.Reset(); if (xmlReader.MoveToAttribute("type") && xmlReader.Value == "null") { attributes.XsiNil = true; } else if (xmlReader.MoveToAttribute("__type")) { XmlQualifiedName xmlQualifiedName = JsonReaderDelegator.ParseQualifiedName(xmlReader.Value); attributes.XsiTypeName = xmlQualifiedName.Name; string text = xmlQualifiedName.Namespace; if (!string.IsNullOrEmpty(text)) { switch (text[0]) { case '#': text = "http://schemas.datacontract.org/2004/07/" + text.Substring(1); break; case '\\': if (text.Length >= 2) { char c = text[1]; if (c == '#' || c == '\\') { text = text.Substring(1); } } break; } } attributes.XsiTypeNamespace = text; } xmlReader.MoveToElement(); } public int GetJsonMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, int memberIndex, ExtensionDataObject extensionData) { int num = memberNames.Length; if (num != 0) { int num2 = 0; int num3 = (memberIndex + 1) % num; while (num2 < num) { if (xmlReader.IsStartElement(memberNames[num3], XmlDictionaryString.Empty)) { return num3; } num2++; num3 = (num3 + 1) % num; } if (TryGetJsonLocalName(xmlReader, out var name)) { int num4 = 0; int num5 = (memberIndex + 1) % num; while (num4 < num) { if (memberNames[num5].Value == name) { return num5; } num4++; num5 = (num5 + 1) % num; } } } HandleMemberNotFound(xmlReader, extensionData, memberIndex); return num; } internal static bool TryGetJsonLocalName(XmlReaderDelegator xmlReader, out string name) { if (xmlReader.IsStartElement(JsonGlobals.itemDictionaryString, JsonGlobals.itemDictionaryString) && xmlReader.MoveToAttribute("item")) { name = xmlReader.Value; return true; } name = null; return false; } public static string GetJsonMemberName(XmlReaderDelegator xmlReader) { if (!TryGetJsonLocalName(xmlReader, out var name)) { return xmlReader.LocalName; } return name; } public static void ThrowMissingRequiredMembers(object obj, XmlDictionaryString[] memberNames, byte[] expectedElements, byte[] requiredElements) { StringBuilder stringBuilder = new StringBuilder(); int num = 0; for (int i = 0; i < memberNames.Length; i++) { if (IsBitSet(expectedElements, i) && IsBitSet(requiredElements, i)) { if (stringBuilder.Length != 0) { stringBuilder.Append(", "); } stringBuilder.Append(memberNames[i]); num++; } } if (num == 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString("Required member {1} in type '{0}' is not found.", DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString()))); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString("Required members {0} in type '{1}' are not found.", DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString()))); } public static void ThrowDuplicateMemberException(object obj, XmlDictionaryString[] memberNames, int memberIndex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString("Duplicate member '{0}' is found in JSON input.", DataContract.GetClrTypeFullName(obj.GetType()), memberNames[memberIndex]))); } [SecuritySafeCritical] private static bool IsBitSet(byte[] bytes, int bitIndex) { return BitFlagsGenerator.IsBitSet(bytes, bitIndex); } protected override bool IsReadingCollectionExtensionData(XmlReaderDelegator xmlReader) { return xmlReader.GetAttribute("type") == "array"; } protected override bool IsReadingClassExtensionData(XmlReaderDelegator xmlReader) { return xmlReader.GetAttribute("type") == "object"; } protected override XmlReaderDelegator CreateReaderDelegatorForReader(XmlReader xmlReader) { return new JsonReaderDelegator(xmlReader, dateTimeFormat); } internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type) { DataContract dataContract = base.GetDataContract(typeHandle, type); DataContractJsonSerializer.CheckIfTypeIsReference(dataContract); return dataContract; } internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type) { DataContract dataContractSkipValidation = base.GetDataContractSkipValidation(typeId, typeHandle, type); DataContractJsonSerializer.CheckIfTypeIsReference(dataContractSkipValidation); return dataContractSkipValidation; } internal override DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle) { DataContract dataContract = base.GetDataContract(id, typeHandle); DataContractJsonSerializer.CheckIfTypeIsReference(dataContract); return dataContract; } protected override DataContract ResolveDataContractFromRootDataContract(XmlQualifiedName typeQName) { return XmlObjectSerializerWriteContextComplexJson.ResolveJsonDataContractFromRootDataContract(this, typeQName, rootTypeDataContract); } } internal class XmlObjectSerializerWriteContextComplexJson : XmlObjectSerializerWriteContextComplex { private EmitTypeInformation emitXsiType; private bool perCallXsiTypeAlreadyEmitted; private bool useSimpleDictionaryFormat; internal IList SerializerKnownTypeList => serializerKnownTypeList; public bool UseSimpleDictionaryFormat => useSimpleDictionaryFormat; internal XmlDictionaryString CollectionItemName => JsonGlobals.itemDictionaryString; public XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract) : base(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(StreamingContextStates.All), serializer.IgnoreExtensionDataObject) { emitXsiType = serializer.EmitTypeInformation; base.rootTypeDataContract = rootTypeDataContract; serializerKnownTypeList = serializer.knownTypeList; dataContractSurrogate = serializer.DataContractSurrogate; serializeReadOnlyTypes = serializer.SerializeReadOnlyTypes; useSimpleDictionaryFormat = serializer.UseSimpleDictionaryFormat; } internal static XmlObjectSerializerWriteContextComplexJson CreateContext(DataContractJsonSerializer serializer, DataContract rootTypeDataContract) { return new XmlObjectSerializerWriteContextComplexJson(serializer, rootTypeDataContract); } internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName) { return false; } internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract) { return false; } internal override void WriteArraySize(XmlWriterDelegator xmlWriter, int size) { } protected override void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string dataContractNamespace) { if (emitXsiType != EmitTypeInformation.Never) { if (string.IsNullOrEmpty(dataContractNamespace)) { WriteTypeInfo(writer, dataContractName); } else { WriteTypeInfo(writer, dataContractName + ":" + TruncateDefaultDataContractNamespace(dataContractNamespace)); } } } internal static string TruncateDefaultDataContractNamespace(string dataContractNamespace) { if (!string.IsNullOrEmpty(dataContractNamespace)) { if (dataContractNamespace[0] == '#') { return "\\" + dataContractNamespace; } if (dataContractNamespace[0] == '\\') { return "\\" + dataContractNamespace; } if (dataContractNamespace.StartsWith("http://schemas.datacontract.org/2004/07/", StringComparison.Ordinal)) { return "#" + dataContractNamespace.Substring(JsonGlobals.DataContractXsdBaseNamespaceLength); } } return dataContractNamespace; } private static bool RequiresJsonTypeInfo(DataContract contract) { return contract is ClassDataContract; } private void WriteTypeInfo(XmlWriterDelegator writer, string typeInformation) { writer.WriteAttributeString(null, "__type", null, typeInformation); } protected override bool WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract) { if ((contract.Name != declaredContract.Name || contract.Namespace != declaredContract.Namespace) && (!(contract.Name.Value == declaredContract.Name.Value) || !(contract.Namespace.Value == declaredContract.Namespace.Value)) && contract.UnderlyingType != Globals.TypeOfObjectArray && emitXsiType != EmitTypeInformation.Never) { if (RequiresJsonTypeInfo(contract)) { perCallXsiTypeAlreadyEmitted = true; WriteTypeInfo(writer, contract.Name.Value, contract.Namespace.Value); } else if (declaredContract.UnderlyingType == typeof(Enum)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString("Enum type is not supported by DataContractJsonSerializer. The underlying type is '{0}'.", declaredContract.UnderlyingType))); } return true; } return false; } internal void WriteJsonISerializable(XmlWriterDelegator xmlWriter, ISerializable obj) { Type type = obj.GetType(); SerializationInfo serializationInfo = new SerializationInfo(type, XmlObjectSerializer.FormatterConverter); GetObjectData(obj, serializationInfo, GetStreamingContext()); if (DataContract.GetClrTypeFullName(type) != serializationInfo.FullTypeName) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Changing full type name is not supported. Serialization type name: '{0}', data contract type name: '{1}'.", serializationInfo.FullTypeName, DataContract.GetClrTypeFullName(type)))); } WriteSerializationInfo(xmlWriter, type, serializationInfo); } internal static DataContract GetRevisedItemContract(DataContract oldItemContract) { if (oldItemContract != null && oldItemContract.UnderlyingType.IsGenericType && oldItemContract.UnderlyingType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue) { return DataContract.GetDataContract(oldItemContract.UnderlyingType); } return oldItemContract; } protected override void WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle) { JsonDataContract jsonDataContract = JsonDataContract.GetJsonDataContract(dataContract); if (emitXsiType == EmitTypeInformation.Always && !perCallXsiTypeAlreadyEmitted && RequiresJsonTypeInfo(dataContract)) { WriteTypeInfo(xmlWriter, jsonDataContract.TypeName); } perCallXsiTypeAlreadyEmitted = false; DataContractJsonSerializer.WriteJsonValue(jsonDataContract, xmlWriter, obj, this, declaredTypeHandle); } protected override void WriteNull(XmlWriterDelegator xmlWriter) { DataContractJsonSerializer.WriteJsonNull(xmlWriter); } internal static void WriteJsonNameWithMapping(XmlWriterDelegator xmlWriter, XmlDictionaryString[] memberNames, int index) { xmlWriter.WriteStartElement("a", "item", "item"); xmlWriter.WriteAttributeString(null, "item", null, memberNames[index].Value); } internal override void WriteExtensionDataTypeInfo(XmlWriterDelegator xmlWriter, IDataNode dataNode) { Type dataType = dataNode.DataType; if (dataType == Globals.TypeOfClassDataNode || dataType == Globals.TypeOfISerializableDataNode) { xmlWriter.WriteAttributeString(null, "type", null, "object"); base.WriteExtensionDataTypeInfo(xmlWriter, dataNode); } else if (dataType == Globals.TypeOfCollectionDataNode) { xmlWriter.WriteAttributeString(null, "type", null, "array"); } else if (!(dataType == Globals.TypeOfXmlDataNode) && dataType == Globals.TypeOfObject && dataNode.Value != null && RequiresJsonTypeInfo(GetDataContract(dataNode.Value.GetType()))) { base.WriteExtensionDataTypeInfo(xmlWriter, dataNode); } } protected override void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType) { bool verifyKnownType = false; bool isInterface = declaredType.IsInterface; DataContract dataContract; if (isInterface && CollectionDataContract.IsCollectionInterface(declaredType)) { dataContract = GetDataContract(declaredTypeHandle, declaredType); } else if (declaredType.IsArray) { dataContract = GetDataContract(declaredTypeHandle, declaredType); } else { dataContract = GetDataContract(objectTypeHandle, objectType); verifyKnownType = WriteTypeInfo(declaredContract: (declaredTypeID >= 0) ? GetDataContract(declaredTypeID, declaredTypeHandle) : GetDataContract(declaredTypeHandle, declaredType), writer: xmlWriter, contract: dataContract); HandleCollectionAssignedToObject(declaredType, ref dataContract, ref obj, ref verifyKnownType); } if (isInterface) { VerifyObjectCompatibilityWithInterface(dataContract, obj, declaredType); } SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredType.TypeHandle, declaredType); } private static void VerifyObjectCompatibilityWithInterface(DataContract contract, object graph, Type declaredType) { Type type = contract.GetType(); if (type == typeof(XmlDataContract) && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(declaredType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Object of type '{0}' is assigned to an incompatible interface '{1}'.", graph.GetType(), declaredType))); } if (type == typeof(CollectionDataContract) && !CollectionDataContract.IsCollectionInterface(declaredType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Collection of type '{0}' is assigned to an incompatible interface '{1}'", graph.GetType(), declaredType))); } } private void HandleCollectionAssignedToObject(Type declaredType, ref DataContract dataContract, ref object obj, ref bool verifyKnownType) { if (!(declaredType != dataContract.UnderlyingType) || !(dataContract is CollectionDataContract)) { return; } if (verifyKnownType) { VerifyType(dataContract, declaredType); verifyKnownType = false; } if (((CollectionDataContract)dataContract).Kind == CollectionKind.Dictionary) { IDictionary obj2 = obj as IDictionary; Dictionary dictionary = new Dictionary(); foreach (DictionaryEntry item in obj2) { dictionary.Add(item.Key, item.Value); } obj = dictionary; } dataContract = GetDataContract(Globals.TypeOfIEnumerable); } internal override void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType) { bool verifyKnownType = false; Type underlyingType = rootTypeDataContract.UnderlyingType; bool isInterface = underlyingType.IsInterface; if ((!isInterface || !CollectionDataContract.IsCollectionInterface(underlyingType)) && !underlyingType.IsArray) { verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, rootTypeDataContract); HandleCollectionAssignedToObject(underlyingType, ref dataContract, ref obj, ref verifyKnownType); } if (isInterface) { VerifyObjectCompatibilityWithInterface(dataContract, obj, underlyingType); } SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, underlyingType.TypeHandle, underlyingType); } private void VerifyType(DataContract dataContract, Type declaredType) { bool flag = false; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); flag = true; } if (!IsKnownType(dataContract, declaredType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Type '{0}' with data contract name '{1}:{2}' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.", DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace))); } if (flag) { scopedKnownTypes.Pop(); } } internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type) { DataContract dataContract = base.GetDataContract(typeHandle, type); DataContractJsonSerializer.CheckIfTypeIsReference(dataContract); return dataContract; } internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type) { DataContract dataContractSkipValidation = base.GetDataContractSkipValidation(typeId, typeHandle, type); DataContractJsonSerializer.CheckIfTypeIsReference(dataContractSkipValidation); return dataContractSkipValidation; } internal override DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle) { DataContract dataContract = base.GetDataContract(id, typeHandle); DataContractJsonSerializer.CheckIfTypeIsReference(dataContract); return dataContract; } internal static DataContract ResolveJsonDataContractFromRootDataContract(XmlObjectSerializerContext context, XmlQualifiedName typeQName, DataContract rootTypeDataContract) { if (rootTypeDataContract.StableName == typeQName) { return rootTypeDataContract; } CollectionDataContract collectionDataContract = rootTypeDataContract as CollectionDataContract; while (collectionDataContract != null) { DataContract dataContract = ((!collectionDataContract.ItemType.IsGenericType || !(collectionDataContract.ItemType.GetGenericTypeDefinition() == typeof(KeyValue<, >))) ? context.GetDataContract(context.GetSurrogatedType(collectionDataContract.ItemType)) : context.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionDataContract.ItemType.GetGenericArguments()))); if (dataContract.StableName == typeQName) { return dataContract; } collectionDataContract = dataContract as CollectionDataContract; } return null; } protected override DataContract ResolveDataContractFromRootDataContract(XmlQualifiedName typeQName) { return ResolveJsonDataContractFromRootDataContract(this, typeQName, rootTypeDataContract); } } internal class JsonFormatReaderInterpreter { private enum KeyParseMode { Fail, AsString, UsingParseEnum, UsingCustomParse } private bool is_get_only_collection; private ClassDataContract classContract; private CollectionDataContract collectionContract; private object objectLocal; private Type objectType; private XmlReaderDelegator xmlReader; private XmlObjectSerializerReadContextComplexJson context; private XmlDictionaryString[] memberNames; private XmlDictionaryString emptyDictionaryString; private XmlDictionaryString itemName; private XmlDictionaryString itemNamespace; public JsonFormatReaderInterpreter(ClassDataContract classContract) { this.classContract = classContract; } public JsonFormatReaderInterpreter(CollectionDataContract collectionContract, bool isGetOnly) { this.collectionContract = collectionContract; is_get_only_collection = isGetOnly; } public object ReadFromJson(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[] memberNames) { this.xmlReader = xmlReader; this.context = context; this.emptyDictionaryString = emptyDictionaryString; this.memberNames = memberNames; CreateObject(classContract); context.AddNewObject(objectLocal); InvokeOnDeserializing(classContract); if (classContract.IsISerializable) { ReadISerializable(classContract); } else { ReadClass(classContract); } if (Globals.TypeOfIDeserializationCallback.IsAssignableFrom(classContract.UnderlyingType)) { ((IDeserializationCallback)objectLocal).OnDeserialization(null); } InvokeOnDeserialized(classContract); if (!InvokeFactoryMethod(classContract) && classContract.UnderlyingType == Globals.TypeOfDateTimeOffsetAdapter) { objectLocal = DateTimeOffsetAdapter.GetDateTimeOffset((DateTimeOffsetAdapter)objectLocal); } return objectLocal; } public object ReadCollectionFromJson(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract) { this.xmlReader = xmlReader; this.context = context; this.emptyDictionaryString = emptyDictionaryString; this.itemName = itemName; this.collectionContract = collectionContract; ReadCollection(collectionContract); return objectLocal; } public void ReadGetOnlyCollectionFromJson(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract) { this.xmlReader = xmlReader; this.context = context; this.emptyDictionaryString = emptyDictionaryString; this.itemName = itemName; this.collectionContract = collectionContract; ReadGetOnlyCollection(collectionContract); } private void CreateObject(ClassDataContract classContract) { Type type = (objectType = classContract.UnderlyingType); if (type.IsValueType && !classContract.IsNonAttributedType) { type = Globals.TypeOfValueType; } if (classContract.UnderlyingType == Globals.TypeOfDBNull) { objectLocal = DBNull.Value; } else if (classContract.IsNonAttributedType) { if (type.IsValueType) { objectLocal = FormatterServices.GetUninitializedObject(type); } else { objectLocal = classContract.GetNonAttributedTypeConstructor().Invoke(new object[0]); } } else { objectLocal = CodeInterpreter.ConvertValue(XmlFormatReaderGenerator.UnsafeGetUninitializedObject(DataContract.GetIdForInitialization(classContract)), Globals.TypeOfObject, type); } } private void InvokeOnDeserializing(ClassDataContract classContract) { if (classContract.BaseContract != null) { InvokeOnDeserializing(classContract.BaseContract); } if (classContract.OnDeserializing != null) { classContract.OnDeserializing.Invoke(objectLocal, new object[1] { context.GetStreamingContext() }); } } private void InvokeOnDeserialized(ClassDataContract classContract) { if (classContract.BaseContract != null) { InvokeOnDeserialized(classContract.BaseContract); } if (classContract.OnDeserialized != null) { classContract.OnDeserialized.Invoke(objectLocal, new object[1] { context.GetStreamingContext() }); } } private bool HasFactoryMethod(ClassDataContract classContract) { return Globals.TypeOfIObjectReference.IsAssignableFrom(classContract.UnderlyingType); } private bool InvokeFactoryMethod(ClassDataContract classContract) { if (HasFactoryMethod(classContract)) { objectLocal = CodeInterpreter.ConvertValue(context.GetRealObject((IObjectReference)objectLocal, Globals.NewObjectId), Globals.TypeOfObject, classContract.UnderlyingType); return true; } return false; } private void ReadISerializable(ClassDataContract classContract) { ConstructorInfo constructor = classContract.UnderlyingType.GetConstructor(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, JsonFormatGeneratorStatics.SerInfoCtorArgs, null); if (constructor == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString("Constructor that takes SerializationInfo and StreamingContext is not found for '{0}'.", DataContract.GetClrTypeFullName(classContract.UnderlyingType)))); } context.ReadSerializationInfo(xmlReader, classContract.UnderlyingType); constructor.Invoke(objectLocal, new object[1] { context.GetStreamingContext() }); } private void ReadClass(ClassDataContract classContract) { if (classContract.HasExtensionData) { ExtensionDataObject extensionDataObject = new ExtensionDataObject(); ReadMembers(classContract, extensionDataObject); for (ClassDataContract classDataContract = classContract; classDataContract != null; classDataContract = classDataContract.BaseContract) { MethodInfo extensionDataSetMethod = classDataContract.ExtensionDataSetMethod; if (extensionDataSetMethod != null) { extensionDataSetMethod.Invoke(objectLocal, new object[1] { extensionDataObject }); } } } else { ReadMembers(classContract, null); } } private void ReadMembers(ClassDataContract classContract, ExtensionDataObject extensionData) { int num = classContract.MemberNames.Length; context.IncrementItemCount(num); int memberIndex = -1; BitFlagsGenerator bitFlagsGenerator = new BitFlagsGenerator(num); byte[] requiredElements = new byte[bitFlagsGenerator.GetLocalCount()]; SetRequiredElements(classContract, requiredElements); SetExpectedElements(bitFlagsGenerator, 0); while (XmlObjectSerializerReadContext.MoveToNextElement(xmlReader)) { int jsonMemberIndex = context.GetJsonMemberIndex(xmlReader, memberNames, memberIndex, extensionData); if (num > 0) { ReadMembers(jsonMemberIndex, classContract, bitFlagsGenerator, ref memberIndex); } } if (!CheckRequiredElements(bitFlagsGenerator, requiredElements)) { XmlObjectSerializerReadContextComplexJson.ThrowMissingRequiredMembers(objectLocal, memberNames, bitFlagsGenerator.LoadArray(), requiredElements); } } private int ReadMembers(int index, ClassDataContract classContract, BitFlagsGenerator expectedElements, ref int memberIndex) { int num = ((classContract.BaseContract != null) ? ReadMembers(index, classContract.BaseContract, expectedElements, ref memberIndex) : 0); if (num <= index && index < num + classContract.Members.Count) { DataMember dataMember = classContract.Members[index - num]; Type memberType = dataMember.MemberType; memberIndex = num; if (!expectedElements.Load(index)) { XmlObjectSerializerReadContextComplexJson.ThrowDuplicateMemberException(objectLocal, memberNames, memberIndex); } if (dataMember.IsGetOnlyCollection) { object member = CodeInterpreter.GetMember(dataMember.MemberInfo, objectLocal); context.StoreCollectionMemberInfo(member); ReadValue(memberType, dataMember.Name); } else { object value = ReadValue(memberType, dataMember.Name); CodeInterpreter.SetMember(dataMember.MemberInfo, objectLocal, value); } memberIndex = index; ResetExpectedElements(expectedElements, index); } return num + classContract.Members.Count; } private bool CheckRequiredElements(BitFlagsGenerator expectedElements, byte[] requiredElements) { for (int i = 0; i < requiredElements.Length; i++) { if ((expectedElements.GetLocal(i) & requiredElements[i]) != 0) { return false; } } return true; } private int SetRequiredElements(ClassDataContract contract, byte[] requiredElements) { int num = ((contract.BaseContract != null) ? SetRequiredElements(contract.BaseContract, requiredElements) : 0); List members = contract.Members; int num2 = 0; while (num2 < members.Count) { if (members[num2].IsRequired) { BitFlagsGenerator.SetBit(requiredElements, num); } num2++; num++; } return num; } private void SetExpectedElements(BitFlagsGenerator expectedElements, int startIndex) { int bitCount = expectedElements.GetBitCount(); for (int i = startIndex; i < bitCount; i++) { expectedElements.Store(i, value: true); } } private void ResetExpectedElements(BitFlagsGenerator expectedElements, int index) { expectedElements.Store(index, value: false); } private object ReadValue(Type type, string name) { Type type2 = type; object obj = null; bool flag = false; int num = 0; while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) { num++; type = type.GetGenericArguments()[0]; } PrimitiveDataContract primitiveDataContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if ((primitiveDataContract != null && primitiveDataContract.UnderlyingType != Globals.TypeOfObject) || num != 0 || type.IsValueType) { context.ReadAttributes(xmlReader); string text = context.ReadIfNullOrRef(xmlReader, type, DataContract.IsTypeSerializable(type)); if (text == null) { if (num != 0) { obj = Activator.CreateInstance(type2); } else { if (type.IsValueType) { throw new SerializationException(SR.GetString("ValueType '{0}' cannot be null.", DataContract.GetClrTypeFullName(type))); } obj = null; } } else if (text == string.Empty) { text = context.GetObjectId(); if (type.IsValueType && !string.IsNullOrEmpty(text)) { throw new SerializationException(SR.GetString("ValueType '{0}' cannot have id.", DataContract.GetClrTypeFullName(type))); } if (num != 0) { flag = true; } if (primitiveDataContract != null && primitiveDataContract.UnderlyingType != Globals.TypeOfObject) { obj = primitiveDataContract.XmlFormatReaderMethod.Invoke(xmlReader, new object[0]); if (!type.IsValueType) { context.AddNewObject(obj); } } else { obj = InternalDeserialize(type, name); } } else { if (type.IsValueType) { throw new SerializationException(SR.GetString("ValueType '{0}' cannot have ref to another object.", DataContract.GetClrTypeFullName(type))); } obj = CodeInterpreter.ConvertValue(context.GetExistingObject(text, type, name, string.Empty), Globals.TypeOfObject, type); } if (flag && text != null) { obj = WrapNullableObject(type, obj, type2, num); } } else { obj = InternalDeserialize(type, name); } return obj; } private object InternalDeserialize(Type type, string name) { Type type2 = (type.IsPointer ? Globals.TypeOfReflectionPointer : type); object obj = context.InternalDeserialize(xmlReader, DataContract.GetId(type2.TypeHandle), type2.TypeHandle, name, string.Empty); if (type.IsPointer) { return JsonFormatGeneratorStatics.UnboxPointer.Invoke(null, new object[1] { obj }); } return CodeInterpreter.ConvertValue(obj, Globals.TypeOfObject, type); } private object WrapNullableObject(Type innerType, object innerValue, Type outerType, int nullables) { object obj = innerValue; for (int i = 1; i < nullables; i++) { Type type = Globals.TypeOfNullable.MakeGenericType(innerType); obj = Activator.CreateInstance(type, obj); innerType = type; } return Activator.CreateInstance(outerType, obj); } private void ReadCollection(CollectionDataContract collectionContract) { Type type = collectionContract.UnderlyingType; Type itemType = collectionContract.ItemType; bool flag = collectionContract.Kind == CollectionKind.Array; ConstructorInfo constructor = collectionContract.Constructor; if (type.IsInterface) { switch (collectionContract.Kind) { case CollectionKind.GenericDictionary: type = Globals.TypeOfDictionaryGeneric.MakeGenericType(itemType.GetGenericArguments()); constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Globals.EmptyTypeArray, null); break; case CollectionKind.Dictionary: type = Globals.TypeOfHashtable; constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Globals.EmptyTypeArray, null); break; case CollectionKind.GenericList: case CollectionKind.GenericCollection: case CollectionKind.List: case CollectionKind.GenericEnumerable: case CollectionKind.Collection: case CollectionKind.Enumerable: type = itemType.MakeArrayType(); flag = true; break; } } if (!flag) { if (type.IsValueType) { objectLocal = FormatterServices.GetUninitializedObject(type); } else { objectLocal = constructor.Invoke(new object[0]); context.AddNewObject(objectLocal); } } if ((collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary) & context.UseSimpleDictionaryFormat) { ReadSimpleDictionary(collectionContract, itemType); return; } string objectId = context.GetObjectId(); bool flag2 = false; bool readResult = false; if (flag && TryReadPrimitiveArray(itemType, out readResult)) { flag2 = true; } if (!flag2) { object obj = null; if (flag) { obj = Array.CreateInstance(itemType, 32); } int i; for (i = 0; i < int.MaxValue; i++) { if (IsStartElement(itemName, emptyDictionaryString)) { context.IncrementItemCount(1); object value = ReadCollectionItem(collectionContract, itemType); if (flag) { obj = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod(itemType).Invoke(null, new object[2] { obj, i }); ((Array)obj).SetValue(value, i); } else { StoreCollectionValue(objectLocal, itemType, value, collectionContract); } } else { if (IsEndElement()) { break; } HandleUnexpectedItemInCollection(ref i); } } if (flag) { MethodInfo methodInfo = XmlFormatGeneratorStatics.TrimArraySizeMethod.MakeGenericMethod(itemType); objectLocal = methodInfo.Invoke(null, new object[2] { obj, i }); context.AddNewObjectWithId(objectId, objectLocal); } } else { context.AddNewObjectWithId(objectId, objectLocal); } } private void ReadSimpleDictionary(CollectionDataContract collectionContract, Type keyValueType) { Type[] genericArguments = keyValueType.GetGenericArguments(); Type type = genericArguments[0]; Type type2 = genericArguments[1]; int num = 0; while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) { num++; type = type.GetGenericArguments()[0]; } DataContract memberTypeContract = ((ClassDataContract)collectionContract.ItemContract).Members[0].MemberTypeContract; KeyParseMode keyParseMode = KeyParseMode.Fail; if (type == Globals.TypeOfString || type == Globals.TypeOfObject) { keyParseMode = KeyParseMode.AsString; } else if (type.IsEnum) { keyParseMode = KeyParseMode.UsingParseEnum; } else if (memberTypeContract.ParseMethod != null) { keyParseMode = KeyParseMode.UsingCustomParse; } if (keyParseMode == KeyParseMode.Fail) { ThrowSerializationException(SR.GetString("Key type '{1}' for collection type '{0}' cannot be parsed in simple dictionary.", DataContract.GetClrTypeFullName(collectionContract.UnderlyingType), DataContract.GetClrTypeFullName(type))); return; } XmlNodeType xmlNodeType; while ((xmlNodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (xmlNodeType != XmlNodeType.Element) { ThrowUnexpectedStateException(XmlNodeType.Element); } context.IncrementItemCount(1); string jsonMemberName = XmlObjectSerializerReadContextComplexJson.GetJsonMemberName(xmlReader); object obj = null; switch (keyParseMode) { case KeyParseMode.AsString: obj = jsonMemberName; break; case KeyParseMode.UsingParseEnum: obj = Enum.Parse(type, jsonMemberName); break; case KeyParseMode.UsingCustomParse: obj = memberTypeContract.ParseMethod.Invoke(null, new object[1] { jsonMemberName }); break; } if (num > 0) { obj = WrapNullableObject(type, obj, type2, num); } object obj2 = ReadValue(type2, string.Empty); collectionContract.AddMethod.Invoke(objectLocal, new object[2] { obj, obj2 }); } } private void ReadGetOnlyCollection(CollectionDataContract collectionContract) { Type underlyingType = collectionContract.UnderlyingType; Type itemType = collectionContract.ItemType; bool flag = collectionContract.Kind == CollectionKind.Array; int arraySize = 0; objectLocal = context.GetCollectionMember(); if ((collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary) && context.UseSimpleDictionaryFormat) { if (objectLocal == null) { XmlObjectSerializerReadContext.ThrowNullValueReturnedForGetOnlyCollectionException(underlyingType); return; } ReadSimpleDictionary(collectionContract, itemType); context.CheckEndOfArray(xmlReader, arraySize, itemName, emptyDictionaryString); } else { if (!IsStartElement(itemName, emptyDictionaryString)) { return; } if (objectLocal == null) { XmlObjectSerializerReadContext.ThrowNullValueReturnedForGetOnlyCollectionException(underlyingType); return; } arraySize = 0; if (flag) { arraySize = ((Array)objectLocal).Length; } int iterator = 0; while (iterator < int.MaxValue) { if (IsStartElement(itemName, emptyDictionaryString)) { context.IncrementItemCount(1); object value = ReadCollectionItem(collectionContract, itemType); if (flag) { if (arraySize == iterator) { XmlObjectSerializerReadContext.ThrowArrayExceededSizeException(arraySize, underlyingType); } else { ((Array)objectLocal).SetValue(value, iterator); } } else { StoreCollectionValue(objectLocal, itemType, value, collectionContract); } } else { if (IsEndElement()) { break; } HandleUnexpectedItemInCollection(ref iterator); } } context.CheckEndOfArray(xmlReader, arraySize, itemName, emptyDictionaryString); } } private bool TryReadPrimitiveArray(Type itemType, out bool readResult) { readResult = false; if (PrimitiveDataContract.GetPrimitiveDataContract(itemType) == null) { return false; } string text = null; switch (Type.GetTypeCode(itemType)) { case TypeCode.Boolean: text = "TryReadBooleanArray"; break; case TypeCode.Decimal: text = "TryReadDecimalArray"; break; case TypeCode.Int32: text = "TryReadInt32Array"; break; case TypeCode.Int64: text = "TryReadInt64Array"; break; case TypeCode.Single: text = "TryReadSingleArray"; break; case TypeCode.Double: text = "TryReadDoubleArray"; break; case TypeCode.DateTime: text = "TryReadJsonDateTimeArray"; break; } if (text != null) { MethodInfo method = typeof(JsonReaderDelegator).GetMethod(text, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); object[] array = new object[5] { context, itemName, emptyDictionaryString, -1, objectLocal }; readResult = (bool)method.Invoke((JsonReaderDelegator)xmlReader, array); objectLocal = array.Last(); return true; } return false; } private object ReadCollectionItem(CollectionDataContract collectionContract, Type itemType) { if (collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary) { context.ResetAttributes(); return CodeInterpreter.ConvertValue(DataContractJsonSerializer.ReadJsonValue(XmlObjectSerializerWriteContextComplexJson.GetRevisedItemContract(collectionContract.ItemContract), xmlReader, context), Globals.TypeOfObject, itemType); } return ReadValue(itemType, "item"); } private void StoreCollectionValue(object collection, Type valueType, object value, CollectionDataContract collectionContract) { if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary) { ClassDataContract obj = DataContract.GetDataContract(valueType) as ClassDataContract; DataMember dataMember = obj.Members[0]; DataMember dataMember2 = obj.Members[1]; object member = CodeInterpreter.GetMember(dataMember.MemberInfo, value); object member2 = CodeInterpreter.GetMember(dataMember2.MemberInfo, value); try { collectionContract.AddMethod.Invoke(collection, new object[2] { member, member2 }); return; } catch (TargetInvocationException ex) { if (ex.InnerException != null) { throw ex.InnerException; } throw; } } collectionContract.AddMethod.Invoke(collection, new object[1] { value }); } private void HandleUnexpectedItemInCollection(ref int iterator) { if (IsStartElement()) { context.SkipUnknownElement(xmlReader); iterator--; return; } throw XmlObjectSerializerReadContext.CreateUnexpectedStateException(XmlNodeType.Element, xmlReader); } private bool IsStartElement(XmlDictionaryString name, XmlDictionaryString ns) { return xmlReader.IsStartElement(name, ns); } private bool IsStartElement() { return xmlReader.IsStartElement(); } private bool IsEndElement() { return xmlReader.NodeType == XmlNodeType.EndElement; } private void ThrowUnexpectedStateException(XmlNodeType expectedState) { throw XmlObjectSerializerReadContext.CreateUnexpectedStateException(expectedState, xmlReader); } private void ThrowSerializationException(string msg, params object[] values) { if (values != null && values.Length != 0) { msg = string.Format(msg, values); } throw new SerializationException(msg); } } internal class JsonFormatWriterInterpreter { private ClassDataContract classContract; private CollectionDataContract collectionContract; private XmlWriterDelegator writer; private object obj; private XmlObjectSerializerWriteContextComplexJson context; private DataContract dataContract; private object objLocal; private XmlDictionaryString[] memberNames; private int typeIndex = 1; private int childElementIndex; private ClassDataContract classDataContract => (ClassDataContract)dataContract; private CollectionDataContract collectionDataContract => (CollectionDataContract)dataContract; public JsonFormatWriterInterpreter(ClassDataContract classContract) { this.classContract = classContract; } public JsonFormatWriterInterpreter(CollectionDataContract collectionContract) { this.collectionContract = collectionContract; } public void WriteToJson(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract dataContract, XmlDictionaryString[] memberNames) { writer = xmlWriter; this.obj = obj; this.context = context; this.dataContract = dataContract; this.memberNames = memberNames; InitArgs(classContract.UnderlyingType); if (classContract.IsReadOnlyContract) { DataContract.ThrowInvalidDataContractException(classContract.SerializationExceptionMessage, null); } WriteClass(classContract); } public void WriteCollectionToJson(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract dataContract) { writer = xmlWriter; this.obj = obj; this.context = context; this.dataContract = dataContract; InitArgs(collectionContract.UnderlyingType); if (collectionContract.IsReadOnlyContract) { DataContract.ThrowInvalidDataContractException(collectionContract.SerializationExceptionMessage, null); } WriteCollection(collectionContract); } private void InitArgs(Type objType) { if (objType == Globals.TypeOfDateTimeOffsetAdapter) { objLocal = DateTimeOffsetAdapter.GetDateTimeOffsetAdapter((DateTimeOffset)obj); } else { objLocal = CodeInterpreter.ConvertValue(obj, typeof(object), objType); } } private void InvokeOnSerializing(ClassDataContract classContract, object objSerialized, XmlObjectSerializerWriteContext context) { if (classContract.BaseContract != null) { InvokeOnSerializing(classContract.BaseContract, objSerialized, context); } if (classContract.OnSerializing != null) { classContract.OnSerializing.Invoke(objSerialized, new object[1] { context.GetStreamingContext() }); } } private void InvokeOnSerialized(ClassDataContract classContract, object objSerialized, XmlObjectSerializerWriteContext context) { if (classContract.BaseContract != null) { InvokeOnSerialized(classContract.BaseContract, objSerialized, context); } if (classContract.OnSerialized != null) { classContract.OnSerialized.Invoke(objSerialized, new object[1] { context.GetStreamingContext() }); } } private void WriteClass(ClassDataContract classContract) { InvokeOnSerializing(classContract, objLocal, context); if (classContract.IsISerializable) { context.WriteJsonISerializable(writer, (ISerializable)objLocal); } else if (classContract.HasExtensionData) { ExtensionDataObject extensionData = ((IExtensibleDataObject)objLocal).ExtensionData; context.WriteExtensionData(writer, extensionData, -1); WriteMembers(classContract, extensionData, classContract); } else { WriteMembers(classContract, null, classContract); } InvokeOnSerialized(classContract, objLocal, context); } private void WriteCollection(CollectionDataContract collectionContract) { XmlDictionaryString collectionItemName = context.CollectionItemName; if (collectionContract.Kind == CollectionKind.Array) { Type itemType = collectionContract.ItemType; if (objLocal.GetType().GetElementType() != itemType) { throw new InvalidCastException($"Cannot cast array of {objLocal.GetType().GetElementType()} to array of {itemType}"); } context.IncrementArrayCount(writer, (Array)objLocal); if (TryWritePrimitiveArray(collectionContract.UnderlyingType, itemType, () => objLocal, collectionItemName)) { return; } WriteArrayAttribute(); Array array = (Array)objLocal; int[] array2 = new int[1]; for (int i = 0; i < array.Length; i++) { if (!TryWritePrimitive(itemType, null, null, i, collectionItemName, 0)) { WriteStartElement(collectionItemName, 0); array2[0] = i; object value = array.GetValue(array2); WriteValue(itemType, value); WriteEndElement(); } } return; } if (!collectionContract.UnderlyingType.IsAssignableFrom(objLocal.GetType())) { throw new InvalidCastException($"Cannot cast {objLocal.GetType()} to {collectionContract.UnderlyingType}"); } MethodInfo methodInfo = null; switch (collectionContract.Kind) { case CollectionKind.Dictionary: case CollectionKind.List: case CollectionKind.Collection: methodInfo = XmlFormatGeneratorStatics.IncrementCollectionCountMethod; break; case CollectionKind.GenericList: case CollectionKind.GenericCollection: methodInfo = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(collectionContract.ItemType); break; case CollectionKind.GenericDictionary: methodInfo = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments())); break; } if (methodInfo != null) { methodInfo.Invoke(context, new object[2] { writer, objLocal }); } bool flag = false; bool flag2 = false; Type type = null; Type[] typeArguments = null; if (collectionContract.Kind == CollectionKind.GenericDictionary) { flag2 = true; typeArguments = collectionContract.ItemType.GetGenericArguments(); type = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType(typeArguments); } else if (collectionContract.Kind == CollectionKind.Dictionary) { flag = true; typeArguments = new Type[2] { Globals.TypeOfObject, Globals.TypeOfObject }; type = Globals.TypeOfDictionaryEnumerator; } else { type = collectionContract.GetEnumeratorMethod.ReturnType; } MethodInfo methodInfo2 = type.GetMethod("MoveNext", BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null); MethodInfo methodInfo3 = type.GetMethod("get_Current", BindingFlags.Instance | BindingFlags.Public, null, Globals.EmptyTypeArray, null); if (methodInfo2 == null || methodInfo3 == null) { if (type.IsInterface) { if (methodInfo2 == null) { methodInfo2 = JsonFormatGeneratorStatics.MoveNextMethod; } if (methodInfo3 == null) { methodInfo3 = JsonFormatGeneratorStatics.GetCurrentMethod; } } else { Type interfaceType = Globals.TypeOfIEnumerator; CollectionKind kind = collectionContract.Kind; if (kind == CollectionKind.GenericDictionary || kind == CollectionKind.GenericCollection || kind == CollectionKind.GenericEnumerable) { Type[] interfaces = type.GetInterfaces(); foreach (Type type2 in interfaces) { if (type2.IsGenericType && type2.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric && type2.GetGenericArguments()[0] == collectionContract.ItemType) { interfaceType = type2; break; } } } if (methodInfo2 == null) { methodInfo2 = CollectionDataContract.GetTargetMethodWithName("MoveNext", type, interfaceType); } if (methodInfo3 == null) { methodInfo3 = CollectionDataContract.GetTargetMethodWithName("get_Current", type, interfaceType); } } } Type returnType = methodInfo3.ReturnType; object currentValue = null; IEnumerator enumerator = (IEnumerator)collectionContract.GetEnumeratorMethod.Invoke(objLocal, new object[0]); if (flag) { enumerator = (IEnumerator)type.GetConstructor(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { Globals.TypeOfIDictionaryEnumerator }, null).Invoke(new object[1] { enumerator }); } else if (flag2) { Type type3 = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(typeArguments)); type.GetConstructor(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { type3 }, null); enumerator = (IEnumerator)Activator.CreateInstance(type, enumerator); } bool num = flag || flag2; bool flag3 = num && context.UseSimpleDictionaryFormat; PropertyInfo memberInfo = null; PropertyInfo propertyInfo = null; if (num) { Type type4 = Globals.TypeOfKeyValue.MakeGenericType(typeArguments); memberInfo = type4.GetProperty("Key"); propertyInfo = type4.GetProperty("Value"); } if (flag3) { WriteObjectAttribute(); object[] parameters = new object[0]; while ((bool)methodInfo2.Invoke(enumerator, parameters)) { currentValue = methodInfo3.Invoke(enumerator, parameters); object member = CodeInterpreter.GetMember(memberInfo, currentValue); object member2 = CodeInterpreter.GetMember(propertyInfo, currentValue); WriteStartElement(member, 0); WriteValue(propertyInfo.PropertyType, member2); WriteEndElement(); } return; } WriteArrayAttribute(); object[] parameters2 = new object[0]; while (enumerator != null && enumerator.MoveNext()) { currentValue = methodInfo3.Invoke(enumerator, parameters2); if (methodInfo == null) { XmlFormatGeneratorStatics.IncrementItemCountMethod.Invoke(context, new object[1] { 1 }); } if (!TryWritePrimitive(returnType, () => currentValue, null, null, collectionItemName, 0)) { WriteStartElement(collectionItemName, 0); if (flag2 || flag) { DataContractJsonSerializer.WriteJsonValue(JsonDataContract.GetJsonDataContract(XmlObjectSerializerWriteContextComplexJson.GetRevisedItemContract(collectionDataContract.ItemContract)), writer, currentValue, context, currentValue.GetType().TypeHandle); } else { WriteValue(returnType, currentValue); } WriteEndElement(); } } } private int WriteMembers(ClassDataContract classContract, ExtensionDataObject extensionData, ClassDataContract derivedMostClassContract) { int num = ((classContract.BaseContract != null) ? WriteMembers(classContract.BaseContract, extensionData, derivedMostClassContract) : 0); context.IncrementItemCount(classContract.Members.Count); int num2 = 0; while (num2 < classContract.Members.Count) { DataMember dataMember = classContract.Members[num2]; Type memberType = dataMember.MemberType; object memberValue = null; if (dataMember.IsGetOnlyCollection) { context.StoreIsGetOnlyCollection(); } bool flag = true; bool flag2 = false; if (!dataMember.EmitDefaultValue) { flag2 = true; memberValue = LoadMemberValue(dataMember); flag = !IsDefaultValue(memberType, memberValue); } if (flag) { bool flag3 = DataContractJsonSerializer.CheckIfXmlNameRequiresMapping(classContract.MemberNames[num2]); if (flag3 || !TryWritePrimitive(memberType, flag2 ? ((Func)(() => memberValue)) : null, dataMember.MemberInfo, null, null, num2 + childElementIndex)) { if (flag3) { XmlObjectSerializerWriteContextComplexJson.WriteJsonNameWithMapping(writer, memberNames, num2 + childElementIndex); } else { WriteStartElement(null, num2 + childElementIndex); } if (memberValue == null) { memberValue = LoadMemberValue(dataMember); } WriteValue(memberType, memberValue); WriteEndElement(); } if (classContract.HasExtensionData) { context.WriteExtensionData(writer, extensionData, num); } } else if (!dataMember.EmitDefaultValue && dataMember.IsRequired) { XmlObjectSerializerWriteContext.ThrowRequiredMemberMustBeEmitted(dataMember.Name, classContract.UnderlyingType); } num2++; num++; } typeIndex++; childElementIndex += classContract.Members.Count; return num; } internal bool IsDefaultValue(Type type, object value) { return GetDefaultValue(type)?.Equals(value) ?? (value == null); } internal object GetDefaultValue(Type type) { if (type.IsValueType) { switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: return false; case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: return 0; case TypeCode.Int64: case TypeCode.UInt64: return 0L; case TypeCode.Single: return 0f; case TypeCode.Double: return 0.0; case TypeCode.Decimal: return 0m; case TypeCode.DateTime: return default(DateTime); } } return null; } private void WriteStartElement(object nameLocal, int nameIndex) { object obj = nameLocal ?? memberNames[nameIndex]; if (nameLocal != null && nameLocal is string) { writer.WriteStartElement((string)obj, null); } else { writer.WriteStartElement((XmlDictionaryString)obj, null); } } private void WriteEndElement() { writer.WriteEndElement(); } private void WriteArrayAttribute() { writer.WriteAttributeString(null, "type", string.Empty, "array"); } private void WriteObjectAttribute() { writer.WriteAttributeString(null, "type", null, "object"); } private void WriteValue(Type memberType, object memberValue) { if (memberType.IsPointer) { _ = (Pointer)JsonFormatGeneratorStatics.BoxPointer.Invoke(null, new object[2] { memberValue, memberType }); } bool flag = memberType.IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable; if (memberType.IsValueType && !flag) { PrimitiveDataContract primitiveDataContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); if (primitiveDataContract != null) { primitiveDataContract.XmlFormatContentWriterMethod.Invoke(writer, new object[1] { memberValue }); } else { InternalSerialize(XmlFormatGeneratorStatics.InternalSerializeMethod, () => memberValue, memberType, writeXsiType: false); } return; } bool isNull; if (flag) { memberValue = UnwrapNullableObject(() => memberValue, ref memberType, out isNull); } else { isNull = memberValue == null; } if (isNull) { XmlFormatGeneratorStatics.WriteNullMethod.Invoke(context, new object[3] { writer, memberType, DataContract.IsTypeSerializable(memberType) }); return; } PrimitiveDataContract primitiveDataContract2 = PrimitiveDataContract.GetPrimitiveDataContract(memberType); if (primitiveDataContract2 != null && primitiveDataContract2.UnderlyingType != Globals.TypeOfObject) { if (flag) { primitiveDataContract2.XmlFormatContentWriterMethod.Invoke(writer, new object[1] { memberValue }); } else { primitiveDataContract2.XmlFormatContentWriterMethod.Invoke(context, new object[2] { writer, memberValue }); } return; } bool flag2 = false; if (memberType == Globals.TypeOfObject || memberType == Globals.TypeOfValueType || ((IList)Globals.TypeOfNullable.GetInterfaces()).Contains((object?)memberType)) { object obj = CodeInterpreter.ConvertValue(memberValue, memberType.GetType(), Globals.TypeOfObject); memberValue = obj; flag2 = memberValue == null; } if (flag2) { XmlFormatGeneratorStatics.WriteNullMethod.Invoke(context, new object[3] { writer, memberType, DataContract.IsTypeSerializable(memberType) }); } else { InternalSerialize(flag ? XmlFormatGeneratorStatics.InternalSerializeMethod : XmlFormatGeneratorStatics.InternalSerializeReferenceMethod, () => memberValue, memberType, writeXsiType: false); } } private void InternalSerialize(MethodInfo methodInfo, Func memberValue, Type memberType, bool writeXsiType) { object obj = memberValue(); bool flag = Type.GetTypeHandle(obj).Equals(CodeInterpreter.ConvertValue(obj, memberType, Globals.TypeOfObject)); try { methodInfo.Invoke(context, new object[6] { writer, (memberValue != null) ? obj : null, flag, writeXsiType, DataContract.GetId(memberType.TypeHandle), memberType.TypeHandle }); } catch (TargetInvocationException ex) { if (ex.InnerException != null) { throw ex.InnerException; } throw; } } private object UnwrapNullableObject(Func memberValue, ref Type memberType, out bool isNull) { object obj = memberValue(); isNull = false; while (memberType.IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable) { Type type = memberType.GetGenericArguments()[0]; if ((bool)XmlFormatGeneratorStatics.GetHasValueMethod.MakeGenericMethod(type).Invoke(null, new object[1] { obj })) { obj = XmlFormatGeneratorStatics.GetNullableValueMethod.MakeGenericMethod(type).Invoke(null, new object[1] { obj }); } else { isNull = true; obj = XmlFormatGeneratorStatics.GetDefaultValueMethod.MakeGenericMethod(memberType).Invoke(null, new object[0]); } memberType = type; } return obj; } private bool TryWritePrimitive(Type type, Func value, MemberInfo memberInfo, int? arrayItemIndex, XmlDictionaryString name, int nameIndex) { PrimitiveDataContract primitiveDataContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if (primitiveDataContract == null || primitiveDataContract.UnderlyingType == Globals.TypeOfObject) { return false; } object obj = null; List list = new List(); if (type.IsValueType) { obj = writer; } else { obj = context; list.Add(writer); } if (value != null) { list.Add(value()); } else if (memberInfo != null) { list.Add(CodeInterpreter.GetMember(memberInfo, objLocal)); } else { list.Add(((Array)objLocal).GetValue(new int[1] { arrayItemIndex.Value })); } if (name != null) { list.Add(name); } else { list.Add(memberNames[nameIndex]); } list.Add(null); primitiveDataContract.XmlFormatWriterMethod.Invoke(obj, list.ToArray()); return true; } private bool TryWritePrimitiveArray(Type type, Type itemType, Func value, XmlDictionaryString itemName) { if (PrimitiveDataContract.GetPrimitiveDataContract(itemType) == null) { return false; } string text = null; switch (Type.GetTypeCode(itemType)) { case TypeCode.Boolean: text = "WriteJsonBooleanArray"; break; case TypeCode.DateTime: text = "WriteJsonDateTimeArray"; break; case TypeCode.Decimal: text = "WriteJsonDecimalArray"; break; case TypeCode.Int32: text = "WriteJsonInt32Array"; break; case TypeCode.Int64: text = "WriteJsonInt64Array"; break; case TypeCode.Single: text = "WriteJsonSingleArray"; break; case TypeCode.Double: text = "WriteJsonDoubleArray"; break; } if (text != null) { WriteArrayAttribute(); typeof(JsonWriterDelegator).GetMethod(text, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[3] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) }, null).Invoke(writer, new object[3] { value(), itemName, null }); return true; } return false; } private object LoadMemberValue(DataMember member) { return CodeInterpreter.GetMember(member.MemberInfo, objLocal); } } } namespace System.Runtime.Serialization.Diagnostics { internal static class TraceCode { public const int Serialization = 196608; public const int WriteObjectBegin = 196609; public const int WriteObjectEnd = 196610; public const int WriteObjectContentBegin = 196611; public const int WriteObjectContentEnd = 196612; public const int ReadObjectBegin = 196613; public const int ReadObjectEnd = 196614; public const int ElementIgnored = 196615; public const int XsdExportBegin = 196616; public const int XsdExportEnd = 196617; public const int XsdImportBegin = 196618; public const int XsdImportEnd = 196619; public const int XsdExportError = 196620; public const int XsdImportError = 196621; public const int XsdExportAnnotationFailed = 196622; public const int XsdImportAnnotationFailed = 196623; public const int XsdExportDupItems = 196624; public const int FactoryTypeNotFound = 196625; public const int ObjectWithLargeDepth = 196626; } internal static class TraceUtility { private static Dictionary traceCodes = new Dictionary(18) { { 196609, "WriteObjectBegin" }, { 196610, "WriteObjectEnd" }, { 196611, "WriteObjectContentBegin" }, { 196612, "WriteObjectContentEnd" }, { 196613, "ReadObjectBegin" }, { 196614, "ReadObjectEnd" }, { 196615, "ElementIgnored" }, { 196616, "XsdExportBegin" }, { 196617, "XsdExportEnd" }, { 196618, "XsdImportBegin" }, { 196619, "XsdImportEnd" }, { 196620, "XsdExportError" }, { 196621, "XsdImportError" }, { 196622, "XsdExportAnnotationFailed" }, { 196623, "XsdImportAnnotationFailed" }, { 196624, "XsdExportDupItems" }, { 196625, "FactoryTypeNotFound" }, { 196626, "ObjectWithLargeDepth" } }; internal static void Trace(TraceEventType severity, int traceCode, string traceDescription) { Trace(severity, traceCode, traceDescription, null); } internal static void Trace(TraceEventType severity, int traceCode, string traceDescription, TraceRecord record) { Trace(severity, traceCode, traceDescription, record, null); } internal static void Trace(TraceEventType severity, int traceCode, string traceDescription, TraceRecord record, Exception exception) { string text = ""; DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, text, traceDescription, record, exception, null); } } } namespace System.Runtime.Serialization.Diagnostics.Application { internal class TD { private static ResourceManager resourceManager; private static CultureInfo resourceCulture; [SecurityCritical] private static EventDescriptor[] eventDescriptors; private static object syncLock = new object(); private static volatile bool eventDescriptorsCreated; private static ResourceManager ResourceManager { get { if (resourceManager == null) { resourceManager = new ResourceManager("System.Runtime.Serialization.Diagnostics.Application.TD", typeof(TD).Assembly); } return resourceManager; } } internal static CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } private TD() { } internal static bool ReaderQuotaExceededIsEnabled() { if (FxTrace.ShouldTraceError) { return IsEtwEventEnabled(0); } return false; } internal static void ReaderQuotaExceeded(string param0) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) TracePayload serializedPayload = FxTrace.Trace.GetSerializedPayload((object)null, (TraceRecord)null, (Exception)null); if (IsEtwEventEnabled(0)) { WriteEtwEvent(0, null, param0, ((TracePayload)(ref serializedPayload)).AppDomainFriendlyName); } } internal static bool DCSerializeWithSurrogateStartIsEnabled() { if (FxTrace.ShouldTraceVerbose) { return IsEtwEventEnabled(1); } return false; } internal static void DCSerializeWithSurrogateStart(string SurrogateType) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) TracePayload serializedPayload = FxTrace.Trace.GetSerializedPayload((object)null, (TraceRecord)null, (Exception)null); if (IsEtwEventEnabled(1)) { WriteEtwEvent(1, null, SurrogateType, ((TracePayload)(ref serializedPayload)).AppDomainFriendlyName); } } internal static bool DCSerializeWithSurrogateStopIsEnabled() { if (FxTrace.ShouldTraceVerbose) { return IsEtwEventEnabled(2); } return false; } internal static void DCSerializeWithSurrogateStop() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) TracePayload serializedPayload = FxTrace.Trace.GetSerializedPayload((object)null, (TraceRecord)null, (Exception)null); if (IsEtwEventEnabled(2)) { WriteEtwEvent(2, null, ((TracePayload)(ref serializedPayload)).AppDomainFriendlyName); } } internal static bool DCDeserializeWithSurrogateStartIsEnabled() { if (FxTrace.ShouldTraceVerbose) { return IsEtwEventEnabled(3); } return false; } internal static void DCDeserializeWithSurrogateStart(string SurrogateType) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) TracePayload serializedPayload = FxTrace.Trace.GetSerializedPayload((object)null, (TraceRecord)null, (Exception)null); if (IsEtwEventEnabled(3)) { WriteEtwEvent(3, null, SurrogateType, ((TracePayload)(ref serializedPayload)).AppDomainFriendlyName); } } internal static bool DCDeserializeWithSurrogateStopIsEnabled() { if (FxTrace.ShouldTraceVerbose) { return IsEtwEventEnabled(4); } return false; } internal static void DCDeserializeWithSurrogateStop() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) TracePayload serializedPayload = FxTrace.Trace.GetSerializedPayload((object)null, (TraceRecord)null, (Exception)null); if (IsEtwEventEnabled(4)) { WriteEtwEvent(4, null, ((TracePayload)(ref serializedPayload)).AppDomainFriendlyName); } } internal static bool ImportKnownTypesStartIsEnabled() { if (FxTrace.ShouldTraceVerbose) { return IsEtwEventEnabled(5); } return false; } internal static void ImportKnownTypesStart() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) TracePayload serializedPayload = FxTrace.Trace.GetSerializedPayload((object)null, (TraceRecord)null, (Exception)null); if (IsEtwEventEnabled(5)) { WriteEtwEvent(5, null, ((TracePayload)(ref serializedPayload)).AppDomainFriendlyName); } } internal static bool ImportKnownTypesStopIsEnabled() { if (FxTrace.ShouldTraceVerbose) { return IsEtwEventEnabled(6); } return false; } internal static void ImportKnownTypesStop() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) TracePayload serializedPayload = FxTrace.Trace.GetSerializedPayload((object)null, (TraceRecord)null, (Exception)null); if (IsEtwEventEnabled(6)) { WriteEtwEvent(6, null, ((TracePayload)(ref serializedPayload)).AppDomainFriendlyName); } } internal static bool DCResolverResolveIsEnabled() { if (FxTrace.ShouldTraceVerbose) { return IsEtwEventEnabled(7); } return false; } internal static void DCResolverResolve(string TypeName) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) TracePayload serializedPayload = FxTrace.Trace.GetSerializedPayload((object)null, (TraceRecord)null, (Exception)null); if (IsEtwEventEnabled(7)) { WriteEtwEvent(7, null, TypeName, ((TracePayload)(ref serializedPayload)).AppDomainFriendlyName); } } internal static bool DCGenWriterStartIsEnabled() { if (FxTrace.ShouldTraceVerbose) { return IsEtwEventEnabled(8); } return false; } internal static void DCGenWriterStart(string Kind, string TypeName) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) TracePayload serializedPayload = FxTrace.Trace.GetSerializedPayload((object)null, (TraceRecord)null, (Exception)null); if (IsEtwEventEnabled(8)) { WriteEtwEvent(8, null, Kind, TypeName, ((TracePayload)(ref serializedPayload)).AppDomainFriendlyName); } } internal static bool DCGenWriterStopIsEnabled() { if (FxTrace.ShouldTraceVerbose) { return IsEtwEventEnabled(9); } return false; } internal static void DCGenWriterStop() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) TracePayload serializedPayload = FxTrace.Trace.GetSerializedPayload((object)null, (TraceRecord)null, (Exception)null); if (IsEtwEventEnabled(9)) { WriteEtwEvent(9, null, ((TracePayload)(ref serializedPayload)).AppDomainFriendlyName); } } internal static bool DCGenReaderStartIsEnabled() { if (FxTrace.ShouldTraceVerbose) { return IsEtwEventEnabled(10); } return false; } internal static void DCGenReaderStart(string Kind, string TypeName) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) TracePayload serializedPayload = FxTrace.Trace.GetSerializedPayload((object)null, (TraceRecord)null, (Exception)null); if (IsEtwEventEnabled(10)) { WriteEtwEvent(10, null, Kind, TypeName, ((TracePayload)(ref serializedPayload)).AppDomainFriendlyName); } } internal static bool DCGenReaderStopIsEnabled() { if (FxTrace.ShouldTraceVerbose) { return IsEtwEventEnabled(11); } return false; } internal static void DCGenReaderStop() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) TracePayload serializedPayload = FxTrace.Trace.GetSerializedPayload((object)null, (TraceRecord)null, (Exception)null); if (IsEtwEventEnabled(11)) { WriteEtwEvent(11, null, ((TracePayload)(ref serializedPayload)).AppDomainFriendlyName); } } internal static bool DCJsonGenReaderStartIsEnabled() { if (FxTrace.ShouldTraceVerbose) { return IsEtwEventEnabled(12); } return false; } internal static void DCJsonGenReaderStart(string Kind, string TypeName) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) TracePayload serializedPayload = FxTrace.Trace.GetSerializedPayload((object)null, (TraceRecord)null, (Exception)null); if (IsEtwEventEnabled(12)) { WriteEtwEvent(12, null, Kind, TypeName, ((TracePayload)(ref serializedPayload)).AppDomainFriendlyName); } } internal static bool DCJsonGenReaderStopIsEnabled() { if (FxTrace.ShouldTraceVerbose) { return IsEtwEventEnabled(13); } return false; } internal static void DCJsonGenReaderStop() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) TracePayload serializedPayload = FxTrace.Trace.GetSerializedPayload((object)null, (TraceRecord)null, (Exception)null); if (IsEtwEventEnabled(13)) { WriteEtwEvent(13, null, ((TracePayload)(ref serializedPayload)).AppDomainFriendlyName); } } internal static bool DCJsonGenWriterStartIsEnabled() { if (FxTrace.ShouldTraceVerbose) { return IsEtwEventEnabled(14); } return false; } internal static void DCJsonGenWriterStart(string Kind, string TypeName) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) TracePayload serializedPayload = FxTrace.Trace.GetSerializedPayload((object)null, (TraceRecord)null, (Exception)null); if (IsEtwEventEnabled(14)) { WriteEtwEvent(14, null, Kind, TypeName, ((TracePayload)(ref serializedPayload)).AppDomainFriendlyName); } } internal static bool DCJsonGenWriterStopIsEnabled() { if (FxTrace.ShouldTraceVerbose) { return IsEtwEventEnabled(15); } return false; } internal static void DCJsonGenWriterStop() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) TracePayload serializedPayload = FxTrace.Trace.GetSerializedPayload((object)null, (TraceRecord)null, (Exception)null); if (IsEtwEventEnabled(15)) { WriteEtwEvent(15, null, ((TracePayload)(ref serializedPayload)).AppDomainFriendlyName); } } internal static bool GenXmlSerializableStartIsEnabled() { if (FxTrace.ShouldTraceVerbose) { return IsEtwEventEnabled(16); } return false; } internal static void GenXmlSerializableStart(string DCType) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) TracePayload serializedPayload = FxTrace.Trace.GetSerializedPayload((object)null, (TraceRecord)null, (Exception)null); if (IsEtwEventEnabled(16)) { WriteEtwEvent(16, null, DCType, ((TracePayload)(ref serializedPayload)).AppDomainFriendlyName); } } internal static bool GenXmlSerializableStopIsEnabled() { if (FxTrace.ShouldTraceVerbose) { return IsEtwEventEnabled(17); } return false; } internal static void GenXmlSerializableStop() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) TracePayload serializedPayload = FxTrace.Trace.GetSerializedPayload((object)null, (TraceRecord)null, (Exception)null); if (IsEtwEventEnabled(17)) { WriteEtwEvent(17, null, ((TracePayload)(ref serializedPayload)).AppDomainFriendlyName); } } [SecuritySafeCritical] private static void CreateEventDescriptors() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01d5: Unknown result type (might be due to invalid IL or missing references) //IL_01da: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Unknown result type (might be due to invalid IL or missing references) //IL_0244: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_0269: Unknown result type (might be due to invalid IL or missing references) //IL_026e: Unknown result type (might be due to invalid IL or missing references) //IL_028e: Unknown result type (might be due to invalid IL or missing references) //IL_0293: Unknown result type (might be due to invalid IL or missing references) EventDescriptor[] ed = new EventDescriptor[18] { new EventDescriptor(1420, (byte)0, (byte)18, (byte)2, (byte)0, 2560, 2305843009217888256L), new EventDescriptor(5001, (byte)0, (byte)19, (byte)5, (byte)1, 2592, 1152921504606846978L), new EventDescriptor(5002, (byte)0, (byte)19, (byte)5, (byte)2, 2592, 1152921504606846978L), new EventDescriptor(5003, (byte)0, (byte)19, (byte)5, (byte)1, 2591, 1152921504606846978L), new EventDescriptor(5004, (byte)0, (byte)19, (byte)5, (byte)2, 2591, 1152921504606846978L), new EventDescriptor(5005, (byte)0, (byte)19, (byte)5, (byte)1, 2547, 1152921504606846978L), new EventDescriptor(5006, (byte)0, (byte)19, (byte)5, (byte)2, 2547, 1152921504606846978L), new EventDescriptor(5007, (byte)0, (byte)19, (byte)5, (byte)1, 2528, 1152921504606846978L), new EventDescriptor(5008, (byte)0, (byte)19, (byte)5, (byte)1, 2544, 1152921504606846978L), new EventDescriptor(5009, (byte)0, (byte)19, (byte)5, (byte)2, 2544, 1152921504606846978L), new EventDescriptor(5010, (byte)0, (byte)19, (byte)5, (byte)1, 2543, 1152921504606846978L), new EventDescriptor(5011, (byte)0, (byte)19, (byte)5, (byte)2, 2543, 1152921504606846978L), new EventDescriptor(5012, (byte)0, (byte)19, (byte)5, (byte)1, 2543, 1152921504606846978L), new EventDescriptor(5013, (byte)0, (byte)19, (byte)5, (byte)2, 2543, 1152921504606846978L), new EventDescriptor(5014, (byte)0, (byte)19, (byte)5, (byte)1, 2544, 1152921504606846978L), new EventDescriptor(5015, (byte)0, (byte)19, (byte)5, (byte)2, 2544, 1152921504606846978L), new EventDescriptor(5016, (byte)0, (byte)19, (byte)5, (byte)1, 2545, 1152921504606846978L), new EventDescriptor(5017, (byte)0, (byte)19, (byte)5, (byte)2, 2545, 1152921504606846978L) }; ushort[] events = new ushort[0]; FxTrace.UpdateEventDefinitions((EventDescriptor[])(object)ed, events); eventDescriptors = (EventDescriptor[])(object)ed; } private static void EnsureEventDescriptors() { if (eventDescriptorsCreated) { return; } Monitor.Enter(syncLock); try { if (!eventDescriptorsCreated) { CreateEventDescriptors(); eventDescriptorsCreated = true; } } finally { Monitor.Exit(syncLock); } } private static bool IsEtwEventEnabled(int eventIndex) { if (FxTrace.Trace.IsEtwProviderEnabled) { EnsureEventDescriptors(); return FxTrace.IsEventEnabled(eventIndex); } return false; } [SecuritySafeCritical] private static bool WriteEtwEvent(int eventIndex, EventTraceActivity eventParam0, string eventParam1, string eventParam2) { EnsureEventDescriptors(); return FxTrace.Trace.EtwProvider.WriteEvent(ref eventDescriptors[eventIndex], eventParam0, eventParam1, eventParam2); } [SecuritySafeCritical] private static bool WriteEtwEvent(int eventIndex, EventTraceActivity eventParam0, string eventParam1) { EnsureEventDescriptors(); return ((DiagnosticsEventProvider)FxTrace.Trace.EtwProvider).WriteEvent(ref eventDescriptors[eventIndex], eventParam0, eventParam1); } [SecuritySafeCritical] private static bool WriteEtwEvent(int eventIndex, EventTraceActivity eventParam0, string eventParam1, string eventParam2, string eventParam3) { EnsureEventDescriptors(); return FxTrace.Trace.EtwProvider.WriteEvent(ref eventDescriptors[eventIndex], eventParam0, eventParam1, eventParam2, eventParam3); } } } namespace System.Runtime.Serialization { [EditorBrowsable(EditorBrowsableState.Never)] public static class DataContractSerializerExtensions { [EditorBrowsable(EditorBrowsableState.Never)] public static ISerializationSurrogateProvider GetSerializationSurrogateProvider(this DataContractSerializer serializer) { ThrowStub.ThrowNotSupportedException(); return null; } [EditorBrowsable(EditorBrowsableState.Never)] public static void SetSerializationSurrogateProvider(this DataContractSerializer serializer, ISerializationSurrogateProvider provider) { ThrowStub.ThrowNotSupportedException(); } } public class ImportOptions { public CodeDomProvider CodeProvider { get { ThrowStub.ThrowNotSupportedException(); return null; } set { ThrowStub.ThrowNotSupportedException(); } } public IDataContractSurrogate DataContractSurrogate { get { ThrowStub.ThrowNotSupportedException(); return null; } set { ThrowStub.ThrowNotSupportedException(); } } public bool EnableDataBinding { get { ThrowStub.ThrowNotSupportedException(); return default(bool); } set { ThrowStub.ThrowNotSupportedException(); } } public bool GenerateInternal { get { ThrowStub.ThrowNotSupportedException(); return default(bool); } set { ThrowStub.ThrowNotSupportedException(); } } public bool GenerateSerializable { get { ThrowStub.ThrowNotSupportedException(); return default(bool); } set { ThrowStub.ThrowNotSupportedException(); } } public bool ImportXmlType { get { ThrowStub.ThrowNotSupportedException(); return default(bool); } set { ThrowStub.ThrowNotSupportedException(); } } public IDictionary Namespaces { get { //IL_0007: Expected O, but got I4 ThrowStub.ThrowNotSupportedException(); return (IDictionary)0; } } public ICollection ReferencedCollectionTypes { get { //IL_0007: Expected O, but got I4 ThrowStub.ThrowNotSupportedException(); return (ICollection)0; } } public ICollection ReferencedTypes { get { //IL_0007: Expected O, but got I4 ThrowStub.ThrowNotSupportedException(); return (ICollection)0; } } public ImportOptions() { ThrowStub.ThrowNotSupportedException(); } } public class XsdDataContractImporter { public CodeCompileUnit CodeCompileUnit { get { ThrowStub.ThrowNotSupportedException(); return null; } } public ImportOptions Options { get { ThrowStub.ThrowNotSupportedException(); return null; } set { ThrowStub.ThrowNotSupportedException(); } } public XsdDataContractImporter() { ThrowStub.ThrowNotSupportedException(); } public XsdDataContractImporter(CodeCompileUnit codeCompileUnit) { ThrowStub.ThrowNotSupportedException(); } public bool CanImport(XmlSchemaSet schemas) { ThrowStub.ThrowNotSupportedException(); return default(bool); } public bool CanImport(XmlSchemaSet schemas, ICollection typeNames) { ThrowStub.ThrowNotSupportedException(); return default(bool); } public bool CanImport(XmlSchemaSet schemas, XmlSchemaElement element) { ThrowStub.ThrowNotSupportedException(); return default(bool); } public bool CanImport(XmlSchemaSet schemas, XmlQualifiedName typeName) { ThrowStub.ThrowNotSupportedException(); return default(bool); } public CodeTypeReference GetCodeTypeReference(XmlQualifiedName typeName) { ThrowStub.ThrowNotSupportedException(); return null; } public CodeTypeReference GetCodeTypeReference(XmlQualifiedName typeName, XmlSchemaElement element) { ThrowStub.ThrowNotSupportedException(); return null; } public ICollection GetKnownTypeReferences(XmlQualifiedName typeName) { //IL_0007: Expected O, but got I4 ThrowStub.ThrowNotSupportedException(); return (ICollection)0; } public void Import(XmlSchemaSet schemas) { ThrowStub.ThrowNotSupportedException(); } public void Import(XmlSchemaSet schemas, ICollection typeNames) { ThrowStub.ThrowNotSupportedException(); } public XmlQualifiedName Import(XmlSchemaSet schemas, XmlSchemaElement element) { ThrowStub.ThrowNotSupportedException(); return null; } public void Import(XmlSchemaSet schemas, XmlQualifiedName typeName) { ThrowStub.ThrowNotSupportedException(); } } } namespace System.Runtime.Serialization.Configuration { public sealed class DataContractSerializerSection : ConfigurationSection { public DeclaredTypeElementCollection DeclaredTypes { get { ThrowStub.ThrowNotSupportedException(); return null; } } protected override ConfigurationPropertyCollection Properties { get { ThrowStub.ThrowNotSupportedException(); return null; } } public DataContractSerializerSection() { ThrowStub.ThrowNotSupportedException(); } } [ConfigurationCollection(typeof(DeclaredTypeElement))] public sealed class DeclaredTypeElementCollection : ConfigurationElementCollection { public DeclaredTypeElement this[string typeName] { get { ThrowStub.ThrowNotSupportedException(); return null; } set { ThrowStub.ThrowNotSupportedException(); } } public DeclaredTypeElementCollection() { ThrowStub.ThrowNotSupportedException(); } [SpecialName] public DeclaredTypeElement get_Item(int index) { ThrowStub.ThrowNotSupportedException(); return null; } [SpecialName] public void set_Item(int index, DeclaredTypeElement value) { ThrowStub.ThrowNotSupportedException(); } public void Add(DeclaredTypeElement element) { ThrowStub.ThrowNotSupportedException(); } public void Clear() { ThrowStub.ThrowNotSupportedException(); } public bool Contains(string typeName) { ThrowStub.ThrowNotSupportedException(); return default(bool); } protected override ConfigurationElement CreateNewElement() { ThrowStub.ThrowNotSupportedException(); return null; } protected override object GetElementKey(ConfigurationElement element) { ThrowStub.ThrowNotSupportedException(); return null; } public int IndexOf(DeclaredTypeElement element) { ThrowStub.ThrowNotSupportedException(); return default(int); } public void Remove(DeclaredTypeElement element) { ThrowStub.ThrowNotSupportedException(); } public void Remove(string typeName) { ThrowStub.ThrowNotSupportedException(); } public void RemoveAt(int index) { ThrowStub.ThrowNotSupportedException(); } } public sealed class DeclaredTypeElement : ConfigurationElement { public TypeElementCollection KnownTypes { get { ThrowStub.ThrowNotSupportedException(); return null; } } protected override ConfigurationPropertyCollection Properties { get { ThrowStub.ThrowNotSupportedException(); return null; } } public string Type { get { ThrowStub.ThrowNotSupportedException(); return null; } set { ThrowStub.ThrowNotSupportedException(); } } public DeclaredTypeElement() { ThrowStub.ThrowNotSupportedException(); } public DeclaredTypeElement(string typeName) { ThrowStub.ThrowNotSupportedException(); } [SecuritySafeCritical] protected override void PostDeserialize() { ThrowStub.ThrowNotSupportedException(); } } [ConfigurationCollection(/*Could not decode attribute arguments.*/)] public sealed class TypeElementCollection : ConfigurationElementCollection { public override ConfigurationElementCollectionType CollectionType { get { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) ThrowStub.ThrowNotSupportedException(); return default(ConfigurationElementCollectionType); } } protected override string ElementName { get { ThrowStub.ThrowNotSupportedException(); return null; } } public TypeElement this[int index] { get { ThrowStub.ThrowNotSupportedException(); return null; } set { ThrowStub.ThrowNotSupportedException(); } } public TypeElementCollection() { ThrowStub.ThrowNotSupportedException(); } public void Add(TypeElement element) { ThrowStub.ThrowNotSupportedException(); } public void Clear() { ThrowStub.ThrowNotSupportedException(); } protected override ConfigurationElement CreateNewElement() { ThrowStub.ThrowNotSupportedException(); return null; } protected override object GetElementKey(ConfigurationElement element) { ThrowStub.ThrowNotSupportedException(); return null; } public int IndexOf(TypeElement element) { ThrowStub.ThrowNotSupportedException(); return default(int); } public void Remove(TypeElement element) { ThrowStub.ThrowNotSupportedException(); } public void RemoveAt(int index) { ThrowStub.ThrowNotSupportedException(); } } public sealed class TypeElement : ConfigurationElement { public int Index { get { ThrowStub.ThrowNotSupportedException(); return default(int); } set { ThrowStub.ThrowNotSupportedException(); } } public ParameterElementCollection Parameters { get { ThrowStub.ThrowNotSupportedException(); return null; } } protected override ConfigurationPropertyCollection Properties { get { ThrowStub.ThrowNotSupportedException(); return null; } } public string Type { get { ThrowStub.ThrowNotSupportedException(); return null; } set { ThrowStub.ThrowNotSupportedException(); } } public TypeElement() { ThrowStub.ThrowNotSupportedException(); } public TypeElement(string typeName) { ThrowStub.ThrowNotSupportedException(); } protected override void Reset(ConfigurationElement parentElement) { ThrowStub.ThrowNotSupportedException(); } } [ConfigurationCollection(/*Could not decode attribute arguments.*/)] public sealed class ParameterElementCollection : ConfigurationElementCollection { public override ConfigurationElementCollectionType CollectionType { get { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) ThrowStub.ThrowNotSupportedException(); return default(ConfigurationElementCollectionType); } } protected override string ElementName { get { ThrowStub.ThrowNotSupportedException(); return null; } } public ParameterElement this[int index] { get { ThrowStub.ThrowNotSupportedException(); return null; } set { ThrowStub.ThrowNotSupportedException(); } } public ParameterElementCollection() { ThrowStub.ThrowNotSupportedException(); } public void Add(ParameterElement element) { ThrowStub.ThrowNotSupportedException(); } public void Clear() { ThrowStub.ThrowNotSupportedException(); } public bool Contains(string typeName) { ThrowStub.ThrowNotSupportedException(); return default(bool); } protected override ConfigurationElement CreateNewElement() { ThrowStub.ThrowNotSupportedException(); return null; } protected override object GetElementKey(ConfigurationElement element) { ThrowStub.ThrowNotSupportedException(); return null; } public int IndexOf(ParameterElement element) { ThrowStub.ThrowNotSupportedException(); return default(int); } public void Remove(ParameterElement element) { ThrowStub.ThrowNotSupportedException(); } public void RemoveAt(int index) { ThrowStub.ThrowNotSupportedException(); } } public sealed class ParameterElement : ConfigurationElement { public int Index { get { ThrowStub.ThrowNotSupportedException(); return default(int); } set { ThrowStub.ThrowNotSupportedException(); } } public ParameterElementCollection Parameters { get { ThrowStub.ThrowNotSupportedException(); return null; } } protected override ConfigurationPropertyCollection Properties { get { ThrowStub.ThrowNotSupportedException(); return null; } } public string Type { get { ThrowStub.ThrowNotSupportedException(); return null; } set { ThrowStub.ThrowNotSupportedException(); } } public ParameterElement() { ThrowStub.ThrowNotSupportedException(); } public ParameterElement(int index) { ThrowStub.ThrowNotSupportedException(); } public ParameterElement(string typeName) { ThrowStub.ThrowNotSupportedException(); } protected override void PostDeserialize() { ThrowStub.ThrowNotSupportedException(); } protected override void PreSerialize(XmlWriter writer) { ThrowStub.ThrowNotSupportedException(); } } public sealed class NetDataContractSerializerSection : ConfigurationSection { public bool EnableUnsafeTypeForwarding { get { ThrowStub.ThrowNotSupportedException(); return default(bool); } } protected override ConfigurationPropertyCollection Properties { get { ThrowStub.ThrowNotSupportedException(); return null; } } public NetDataContractSerializerSection() { ThrowStub.ThrowNotSupportedException(); } } public sealed class SerializationSectionGroup : ConfigurationSectionGroup { public DataContractSerializerSection DataContractSerializer { get { ThrowStub.ThrowNotSupportedException(); return null; } } public NetDataContractSerializerSection NetDataContractSerializer { get { ThrowStub.ThrowNotSupportedException(); return null; } } public SerializationSectionGroup() { ThrowStub.ThrowNotSupportedException(); } public static SerializationSectionGroup GetSectionGroup(Configuration config) { ThrowStub.ThrowNotSupportedException(); return null; } } } namespace Unity { internal sealed class ThrowStub : ObjectDisposedException { public static void ThrowNotSupportedException() { throw new PlatformNotSupportedException(); } } }