Decompiled source of Reely SpecTackleLure v0.2.4
Newtonsoft.Json.dll
Decompiled 6 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Data.SqlTypes; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Numerics; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Newtonsoft.Json.Bson; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq.JsonPath; using Newtonsoft.Json.Schema; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AllowPartiallyTrustedCallers] [assembly: InternalsVisibleTo("Newtonsoft.Json.Schema, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cbd8d53b9d7de30f1f1278f636ec462cf9c254991291e66ebb157a885638a517887633b898ccbcf0d5c5ff7be85a6abe9e765d0ac7cd33c68dac67e7e64530e8222101109f154ab14a941c490ac155cd1d4fcba0fabb49016b4ef28593b015cab5937da31172f03f67d09edda404b88a60023f062ae71d0b2e4438b74cc11dc9")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("9ca358aa-317b-4925-8ada-4a29e943a363")] [assembly: CLSCompliant(true)] [assembly: TargetFramework(".NETFramework,Version=v4.5", FrameworkDisplayName = ".NET Framework 4.5")] [assembly: AssemblyCompany("Newtonsoft")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © James Newton-King 2008")] [assembly: AssemblyDescription("Json.NET is a popular high-performance JSON framework for .NET")] [assembly: AssemblyFileVersion("13.0.1.25517")] [assembly: AssemblyInformationalVersion("13.0.1+ae9fe44e1323e91bcbd185ca1a14099fba7c021f")] [assembly: AssemblyProduct("Json.NET")] [assembly: AssemblyTitle("Json.NET")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/JamesNK/Newtonsoft.Json")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("13.0.0.0")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } } namespace Newtonsoft.Json { public enum ConstructorHandling { Default, AllowNonPublicDefaultConstructor } public enum DateFormatHandling { IsoDateFormat, MicrosoftDateFormat } public enum DateParseHandling { None, DateTime, DateTimeOffset } public enum DateTimeZoneHandling { Local, Utc, Unspecified, RoundtripKind } public class DefaultJsonNameTable : JsonNameTable { private class Entry { internal readonly string Value; internal readonly int HashCode; internal Entry Next; internal Entry(string value, int hashCode, Entry next) { Value = value; HashCode = hashCode; Next = next; } } private static readonly int HashCodeRandomizer; private int _count; private Entry[] _entries; private int _mask = 31; static DefaultJsonNameTable() { HashCodeRandomizer = Environment.TickCount; } public DefaultJsonNameTable() { _entries = new Entry[_mask + 1]; } public override string? Get(char[] key, int start, int length) { if (length == 0) { return string.Empty; } int num = length + HashCodeRandomizer; num += (num << 7) ^ key[start]; int num2 = start + length; for (int i = start + 1; i < num2; i++) { num += (num << 7) ^ key[i]; } num -= num >> 17; num -= num >> 11; num -= num >> 5; int num3 = num & _mask; for (Entry entry = _entries[num3]; entry != null; entry = entry.Next) { if (entry.HashCode == num && TextEquals(entry.Value, key, start, length)) { return entry.Value; } } return null; } public string Add(string key) { if (key == null) { throw new ArgumentNullException("key"); } int length = key.Length; if (length == 0) { return string.Empty; } int num = length + HashCodeRandomizer; for (int i = 0; i < key.Length; i++) { num += (num << 7) ^ key[i]; } num -= num >> 17; num -= num >> 11; num -= num >> 5; for (Entry entry = _entries[num & _mask]; entry != null; entry = entry.Next) { if (entry.HashCode == num && entry.Value.Equals(key, StringComparison.Ordinal)) { return entry.Value; } } return AddEntry(key, num); } private string AddEntry(string str, int hashCode) { int num = hashCode & _mask; Entry entry = new Entry(str, hashCode, _entries[num]); _entries[num] = entry; if (_count++ == _mask) { Grow(); } return entry.Value; } private void Grow() { Entry[] entries = _entries; int num = _mask * 2 + 1; Entry[] array = new Entry[num + 1]; for (int i = 0; i < entries.Length; i++) { Entry entry = entries[i]; while (entry != null) { int num2 = entry.HashCode & num; Entry next = entry.Next; entry.Next = array[num2]; array[num2] = entry; entry = next; } } _entries = array; _mask = num; } private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length) { if (str1.Length != str2Length) { return false; } for (int i = 0; i < str1.Length; i++) { if (str1[i] != str2[str2Start + i]) { return false; } } return true; } } [Flags] public enum DefaultValueHandling { Include = 0, Ignore = 1, Populate = 2, IgnoreAndPopulate = 3 } public enum FloatFormatHandling { String, Symbol, DefaultValue } public enum FloatParseHandling { Double, Decimal } public enum Formatting { None, Indented } public interface IArrayPool<T> { T[] Rent(int minimumLength); void Return(T[]? array); } public interface IJsonLineInfo { int LineNumber { get; } int LinePosition { get; } bool HasLineInfo(); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonArrayAttribute : JsonContainerAttribute { private bool _allowNullItems; public bool AllowNullItems { get { return _allowNullItems; } set { _allowNullItems = value; } } public JsonArrayAttribute() { } public JsonArrayAttribute(bool allowNullItems) { _allowNullItems = allowNullItems; } public JsonArrayAttribute(string id) : base(id) { } } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)] public sealed class JsonConstructorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public abstract class JsonContainerAttribute : Attribute { internal bool? _isReference; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; private Type? _namingStrategyType; private object[]? _namingStrategyParameters; public string? Id { get; set; } public string? Title { get; set; } public string? Description { get; set; } public Type? ItemConverterType { get; set; } public object[]? ItemConverterParameters { get; set; } public Type? NamingStrategyType { get { return _namingStrategyType; } set { _namingStrategyType = value; NamingStrategyInstance = null; } } public object[]? NamingStrategyParameters { get { return _namingStrategyParameters; } set { _namingStrategyParameters = value; NamingStrategyInstance = null; } } internal NamingStrategy? NamingStrategyInstance { get; set; } public bool IsReference { get { return _isReference.GetValueOrDefault(); } set { _isReference = value; } } public bool ItemIsReference { get { return _itemIsReference.GetValueOrDefault(); } set { _itemIsReference = value; } } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling.GetValueOrDefault(); } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling.GetValueOrDefault(); } set { _itemTypeNameHandling = value; } } protected JsonContainerAttribute() { } protected JsonContainerAttribute(string id) { Id = id; } } public static class JsonConvert { public static readonly string True = "true"; public static readonly string False = "false"; public static readonly string Null = "null"; public static readonly string Undefined = "undefined"; public static readonly string PositiveInfinity = "Infinity"; public static readonly string NegativeInfinity = "-Infinity"; public static readonly string NaN = "NaN"; public static Func<JsonSerializerSettings>? DefaultSettings { get; set; } public static string ToString(DateTime value) { return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind); } public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling) { DateTime value2 = DateTimeUtils.EnsureDateTime(value, timeZoneHandling); using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeString(stringWriter, value2, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(DateTimeOffset value) { return ToString(value, DateFormatHandling.IsoDateFormat); } public static string ToString(DateTimeOffset value, DateFormatHandling format) { using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeOffsetString(stringWriter, value, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(bool value) { if (!value) { return False; } return True; } public static string ToString(char value) { return ToString(char.ToString(value)); } public static string ToString(Enum value) { return value.ToString("D"); } public static string ToString(int value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(short value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ushort value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(uint value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(long value) { return value.ToString(null, CultureInfo.InvariantCulture); } private static string ToStringInternal(BigInteger value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ulong value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(float value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { if (floatFormatHandling == FloatFormatHandling.Symbol || (!double.IsInfinity(value) && !double.IsNaN(value))) { return text; } if (floatFormatHandling == FloatFormatHandling.DefaultValue) { if (nullable) { return Null; } return "0.0"; } return quoteChar + text + quoteChar; } public static string ToString(double value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureDecimalPlace(double value, string text) { if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1) { return text; } return text + ".0"; } private static string EnsureDecimalPlace(string text) { if (text.IndexOf('.') != -1) { return text; } return text + ".0"; } public static string ToString(byte value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(sbyte value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(decimal value) { return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture)); } public static string ToString(Guid value) { return ToString(value, '"'); } internal static string ToString(Guid value, char quoteChar) { string text = value.ToString("D", CultureInfo.InvariantCulture); string text2 = quoteChar.ToString(CultureInfo.InvariantCulture); return text2 + text + text2; } public static string ToString(TimeSpan value) { return ToString(value, '"'); } internal static string ToString(TimeSpan value, char quoteChar) { return ToString(value.ToString(), quoteChar); } public static string ToString(Uri? value) { if (value == null) { return Null; } return ToString(value, '"'); } internal static string ToString(Uri value, char quoteChar) { return ToString(value.OriginalString, quoteChar); } public static string ToString(string? value) { return ToString(value, '"'); } public static string ToString(string? value, char delimiter) { return ToString(value, delimiter, StringEscapeHandling.Default); } public static string ToString(string? value, char delimiter, StringEscapeHandling stringEscapeHandling) { if (delimiter != '"' && delimiter != '\'') { throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter"); } return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, appendDelimiters: true, stringEscapeHandling); } public static string ToString(object? value) { if (value == null) { return Null; } return ConvertUtils.GetTypeCode(value.GetType()) switch { PrimitiveTypeCode.String => ToString((string)value), PrimitiveTypeCode.Char => ToString((char)value), PrimitiveTypeCode.Boolean => ToString((bool)value), PrimitiveTypeCode.SByte => ToString((sbyte)value), PrimitiveTypeCode.Int16 => ToString((short)value), PrimitiveTypeCode.UInt16 => ToString((ushort)value), PrimitiveTypeCode.Int32 => ToString((int)value), PrimitiveTypeCode.Byte => ToString((byte)value), PrimitiveTypeCode.UInt32 => ToString((uint)value), PrimitiveTypeCode.Int64 => ToString((long)value), PrimitiveTypeCode.UInt64 => ToString((ulong)value), PrimitiveTypeCode.Single => ToString((float)value), PrimitiveTypeCode.Double => ToString((double)value), PrimitiveTypeCode.DateTime => ToString((DateTime)value), PrimitiveTypeCode.Decimal => ToString((decimal)value), PrimitiveTypeCode.DBNull => Null, PrimitiveTypeCode.DateTimeOffset => ToString((DateTimeOffset)value), PrimitiveTypeCode.Guid => ToString((Guid)value), PrimitiveTypeCode.Uri => ToString((Uri)value), PrimitiveTypeCode.TimeSpan => ToString((TimeSpan)value), PrimitiveTypeCode.BigInteger => ToStringInternal((BigInteger)value), _ => throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())), }; } [DebuggerStepThrough] public static string SerializeObject(object? value) { return SerializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting) { return SerializeObject(value, formatting, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static string SerializeObject(object? value, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, JsonSerializerSettings? settings) { return SerializeObject(value, null, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); return SerializeObjectInternal(value, type, jsonSerializer); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings) { return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); jsonSerializer.Formatting = formatting; return SerializeObjectInternal(value, type, jsonSerializer); } private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer) { StringWriter stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture); using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter)) { jsonTextWriter.Formatting = jsonSerializer.Formatting; jsonSerializer.Serialize(jsonTextWriter, value, type); } return stringWriter.ToString(); } [DebuggerStepThrough] public static object? DeserializeObject(string value) { return DeserializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static object? DeserializeObject(string value, JsonSerializerSettings settings) { return DeserializeObject(value, null, settings); } [DebuggerStepThrough] public static object? DeserializeObject(string value, Type type) { return DeserializeObject(value, type, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value) { return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject) { return DeserializeObject<T>(value); } [DebuggerStepThrough] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings) { return DeserializeObject<T>(value, settings); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value, params JsonConverter[] converters) { return (T)DeserializeObject(value, typeof(T), converters); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings) { return (T)DeserializeObject(value, typeof(T), settings); } [DebuggerStepThrough] public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return DeserializeObject(value, type, settings); } public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings) { ValidationUtils.ArgumentNotNull(value, "value"); JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); if (!jsonSerializer.IsCheckAdditionalContentSet()) { jsonSerializer.CheckAdditionalContent = true; } using JsonTextReader reader = new JsonTextReader(new StringReader(value)); return jsonSerializer.Deserialize(reader, type); } [DebuggerStepThrough] public static void PopulateObject(string value, object target) { PopulateObject(value, target, null); } public static void PopulateObject(string value, object target, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); using JsonReader jsonReader = new JsonTextReader(new StringReader(value)); jsonSerializer.Populate(jsonReader, target); if (settings == null || !settings.CheckAdditionalContent) { return; } while (jsonReader.Read()) { if (jsonReader.TokenType != JsonToken.Comment) { throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object."); } } } public static string SerializeXmlNode(XmlNode? node) { return SerializeXmlNode(node, Formatting.None); } public static string SerializeXmlNode(XmlNode? node, Formatting formatting) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); return SerializeObject(node, formatting, xmlNodeConverter); } public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, xmlNodeConverter); } public static XmlDocument? DeserializeXmlNode(string value) { return DeserializeXmlNode(value, null); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute: false); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName; xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute; xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters; return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), xmlNodeConverter); } public static string SerializeXNode(XObject? node) { return SerializeXNode(node, Formatting.None); } public static string SerializeXNode(XObject? node, Formatting formatting) { return SerializeXNode(node, formatting, omitRootObject: false); } public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, xmlNodeConverter); } public static XDocument? DeserializeXNode(string value) { return DeserializeXNode(value, null); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute: false); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName; xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute; xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters; return (XDocument)DeserializeObject(value, typeof(XDocument), xmlNodeConverter); } } public abstract class JsonConverter { public virtual bool CanRead => true; public virtual bool CanWrite => true; public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer); public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer); public abstract bool CanConvert(Type objectType); } public abstract class JsonConverter<T> : JsonConverter { public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (!((value != null) ? (value is T) : ReflectionUtils.IsNullable(typeof(T)))) { throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } WriteJson(writer, (T)value, serializer); } public abstract void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer); public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { bool flag = existingValue == null; if (!flag && !(existingValue is T)) { throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } return ReadJson(reader, objectType, flag ? default(T) : ((T)existingValue), !flag, serializer); } public abstract T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer); public sealed override bool CanConvert(Type objectType) { return typeof(T).IsAssignableFrom(objectType); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonConverterAttribute : Attribute { private readonly Type _converterType; public Type ConverterType => _converterType; public object[]? ConverterParameters { get; } public JsonConverterAttribute(Type converterType) { if (converterType == null) { throw new ArgumentNullException("converterType"); } _converterType = converterType; } public JsonConverterAttribute(Type converterType, params object[] converterParameters) : this(converterType) { ConverterParameters = converterParameters; } } public class JsonConverterCollection : Collection<JsonConverter> { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonDictionaryAttribute : JsonContainerAttribute { public JsonDictionaryAttribute() { } public JsonDictionaryAttribute(string id) : base(id) { } } [Serializable] public class JsonException : Exception { public JsonException() { } public JsonException(string message) : base(message) { } public JsonException(string message, Exception? innerException) : base(message, innerException) { } public JsonException(SerializationInfo info, StreamingContext context) : base(info, context) { } internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message) { message = JsonPosition.FormatMessage(lineInfo, path, message); return new JsonException(message); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class JsonExtensionDataAttribute : Attribute { public bool WriteData { get; set; } public bool ReadData { get; set; } public JsonExtensionDataAttribute() { WriteData = true; ReadData = true; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonIgnoreAttribute : Attribute { } public abstract class JsonNameTable { public abstract string? Get(char[] key, int start, int length); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonObjectAttribute : JsonContainerAttribute { private MemberSerialization _memberSerialization; internal MissingMemberHandling? _missingMemberHandling; internal Required? _itemRequired; internal NullValueHandling? _itemNullValueHandling; public MemberSerialization MemberSerialization { get { return _memberSerialization; } set { _memberSerialization = value; } } public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling.GetValueOrDefault(); } set { _missingMemberHandling = value; } } public NullValueHandling ItemNullValueHandling { get { return _itemNullValueHandling.GetValueOrDefault(); } set { _itemNullValueHandling = value; } } public Required ItemRequired { get { return _itemRequired.GetValueOrDefault(); } set { _itemRequired = value; } } public JsonObjectAttribute() { } public JsonObjectAttribute(MemberSerialization memberSerialization) { MemberSerialization = memberSerialization; } public JsonObjectAttribute(string id) : base(id) { } } internal enum JsonContainerType { None, Object, Array, Constructor } internal struct JsonPosition { private static readonly char[] SpecialCharacters = new char[18] { '.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t', '\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029' }; internal JsonContainerType Type; internal int Position; internal string? PropertyName; internal bool HasIndex; public JsonPosition(JsonContainerType type) { Type = type; HasIndex = TypeHasIndex(type); Position = -1; PropertyName = null; } internal int CalculateLength() { switch (Type) { case JsonContainerType.Object: return PropertyName.Length + 5; case JsonContainerType.Array: case JsonContainerType.Constructor: return MathUtils.IntLength((ulong)Position) + 2; default: throw new ArgumentOutOfRangeException("Type"); } } internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer) { switch (Type) { case JsonContainerType.Object: { string propertyName = PropertyName; if (propertyName.IndexOfAny(SpecialCharacters) != -1) { sb.Append("['"); if (writer == null) { writer = new StringWriter(sb); } JavaScriptUtils.WriteEscapedJavaScriptString(writer, propertyName, '\'', appendDelimiters: false, JavaScriptUtils.SingleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer); sb.Append("']"); } else { if (sb.Length > 0) { sb.Append('.'); } sb.Append(propertyName); } break; } case JsonContainerType.Array: case JsonContainerType.Constructor: sb.Append('['); sb.Append(Position); sb.Append(']'); break; } } internal static bool TypeHasIndex(JsonContainerType type) { if (type != JsonContainerType.Array) { return type == JsonContainerType.Constructor; } return true; } internal static string BuildPath(List<JsonPosition> positions, JsonPosition? currentPosition) { int num = 0; if (positions != null) { for (int i = 0; i < positions.Count; i++) { num += positions[i].CalculateLength(); } } if (currentPosition.HasValue) { num += currentPosition.GetValueOrDefault().CalculateLength(); } StringBuilder stringBuilder = new StringBuilder(num); StringWriter writer = null; char[] buffer = null; if (positions != null) { foreach (JsonPosition position in positions) { position.WriteTo(stringBuilder, ref writer, ref buffer); } } currentPosition?.WriteTo(stringBuilder, ref writer, ref buffer); return stringBuilder.ToString(); } internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message) { if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal)) { message = message.Trim(); if (!StringUtils.EndsWith(message, '.')) { message += "."; } message += " "; } message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path); if (lineInfo != null && lineInfo.HasLineInfo()) { message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition); } message += "."; return message; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonPropertyAttribute : Attribute { internal NullValueHandling? _nullValueHandling; internal DefaultValueHandling? _defaultValueHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal ObjectCreationHandling? _objectCreationHandling; internal TypeNameHandling? _typeNameHandling; internal bool? _isReference; internal int? _order; internal Required? _required; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; public Type? ItemConverterType { get; set; } public object[]? ItemConverterParameters { get; set; } public Type? NamingStrategyType { get; set; } public object[]? NamingStrategyParameters { get; set; } public NullValueHandling NullValueHandling { get { return _nullValueHandling.GetValueOrDefault(); } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling.GetValueOrDefault(); } set { _defaultValueHandling = value; } } public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling.GetValueOrDefault(); } set { _referenceLoopHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling.GetValueOrDefault(); } set { _objectCreationHandling = value; } } public TypeNameHandling TypeNameHandling { get { return _typeNameHandling.GetValueOrDefault(); } set { _typeNameHandling = value; } } public bool IsReference { get { return _isReference.GetValueOrDefault(); } set { _isReference = value; } } public int Order { get { return _order.GetValueOrDefault(); } set { _order = value; } } public Required Required { get { return _required.GetValueOrDefault(); } set { _required = value; } } public string? PropertyName { get; set; } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling.GetValueOrDefault(); } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling.GetValueOrDefault(); } set { _itemTypeNameHandling = value; } } public bool ItemIsReference { get { return _itemIsReference.GetValueOrDefault(); } set { _itemIsReference = value; } } public JsonPropertyAttribute() { } public JsonPropertyAttribute(string propertyName) { PropertyName = propertyName; } } public abstract class JsonReader : IDisposable { protected internal enum State { Start, Complete, Property, ObjectStart, Object, ArrayStart, Array, Closed, PostValue, ConstructorStart, Constructor, Error, Finished } private JsonToken _tokenType; private object? _value; internal char _quoteChar; internal State _currentState; private JsonPosition _currentPosition; private CultureInfo? _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; private string? _dateFormatString; private List<JsonPosition>? _stack; protected State CurrentState => _currentState; public bool CloseInput { get; set; } public bool SupportMultipleContent { get; set; } public virtual char QuoteChar { get { return _quoteChar; } protected internal set { _quoteChar = value; } } public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling; } set { if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind) { throw new ArgumentOutOfRangeException("value"); } _dateTimeZoneHandling = value; } } public DateParseHandling DateParseHandling { get { return _dateParseHandling; } set { if (value < DateParseHandling.None || value > DateParseHandling.DateTimeOffset) { throw new ArgumentOutOfRangeException("value"); } _dateParseHandling = value; } } public FloatParseHandling FloatParseHandling { get { return _floatParseHandling; } set { if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal) { throw new ArgumentOutOfRangeException("value"); } _floatParseHandling = value; } } public string? DateFormatString { get { return _dateFormatString; } set { _dateFormatString = value; } } public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; } } public virtual JsonToken TokenType => _tokenType; public virtual object? Value => _value; public virtual Type? ValueType => _value?.GetType(); public virtual int Depth { get { int num = _stack?.Count ?? 0; if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) { return num; } return num + 1; } } public virtual string Path { get { if (_currentPosition.Type == JsonContainerType.None) { return string.Empty; } JsonPosition? currentPosition = ((_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart) ? new JsonPosition?(_currentPosition) : null); return JsonPosition.BuildPath(_stack, currentPosition); } } public CultureInfo Culture { get { return _culture ?? CultureInfo.InvariantCulture; } set { _culture = value; } } public virtual Task<bool> ReadAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<bool>() ?? Read().ToAsync(); } public async Task SkipAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (TokenType == JsonToken.PropertyName) { await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false) && depth < Depth) { } } } internal async Task ReaderReadAndAssertAsync(CancellationToken cancellationToken) { if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) { throw CreateUnexpectedEndException(); } } public virtual Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<bool?>() ?? Task.FromResult(ReadAsBoolean()); } public virtual Task<byte[]?> ReadAsBytesAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<byte[]>() ?? Task.FromResult(ReadAsBytes()); } internal async Task<byte[]?> ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken) { List<byte> buffer = new List<byte>(); do { if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) { SetToken(JsonToken.None); } } while (!ReadArrayElementIntoByteArrayReportDone(buffer)); byte[] array = buffer.ToArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } public virtual Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<DateTime?>() ?? Task.FromResult(ReadAsDateTime()); } public virtual Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<DateTimeOffset?>() ?? Task.FromResult(ReadAsDateTimeOffset()); } public virtual Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<decimal?>() ?? Task.FromResult(ReadAsDecimal()); } public virtual Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default(CancellationToken)) { return Task.FromResult(ReadAsDouble()); } public virtual Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<int?>() ?? Task.FromResult(ReadAsInt32()); } public virtual Task<string?> ReadAsStringAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<string>() ?? Task.FromResult(ReadAsString()); } internal async Task<bool> ReadAndMoveToContentAsync(CancellationToken cancellationToken) { bool flag = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (flag) { flag = await MoveToContentAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } return flag; } internal Task<bool> MoveToContentAsync(CancellationToken cancellationToken) { JsonToken tokenType = TokenType; if (tokenType == JsonToken.None || tokenType == JsonToken.Comment) { return MoveToContentFromNonContentAsync(cancellationToken); } return AsyncUtils.True; } private async Task<bool> MoveToContentFromNonContentAsync(CancellationToken cancellationToken) { JsonToken tokenType; do { if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) { return false; } tokenType = TokenType; } while (tokenType == JsonToken.None || tokenType == JsonToken.Comment); return true; } internal JsonPosition GetPosition(int depth) { if (_stack != null && depth < _stack.Count) { return _stack[depth]; } return _currentPosition; } protected JsonReader() { _currentState = State.Start; _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; _maxDepth = 64; CloseInput = true; } private void Push(JsonContainerType value) { UpdateScopeWithFinishedValue(); if (_currentPosition.Type == JsonContainerType.None) { _currentPosition = new JsonPosition(value); return; } if (_stack == null) { _stack = new List<JsonPosition>(); } _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); if (!_maxDepth.HasValue || !(Depth + 1 > _maxDepth) || _hasExceededMaxDepth) { return; } _hasExceededMaxDepth = true; throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } private JsonContainerType Pop() { JsonPosition currentPosition; if (_stack != null && _stack.Count > 0) { currentPosition = _currentPosition; _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { currentPosition = _currentPosition; _currentPosition = default(JsonPosition); } if (_maxDepth.HasValue && Depth <= _maxDepth) { _hasExceededMaxDepth = false; } return currentPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } public abstract bool Read(); public virtual int? ReadAsInt32() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is int) { return (int)value; } int num; if (value is BigInteger bigInteger) { num = (int)bigInteger; } else { try { num = Convert.ToInt32(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw JsonReaderException.Create(this, "Could not convert to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex); } } SetToken(JsonToken.Integer, num, updateIndex: false); return num; } case JsonToken.String: { string s = (string)Value; return ReadInt32String(s); } default: throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal int? ReadInt32String(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (int.TryParse(s, NumberStyles.Integer, Culture, out var result)) { SetToken(JsonToken.Integer, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual string? ReadAsString() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.String: return (string)Value; default: if (JsonTokenUtils.IsPrimitiveToken(contentToken)) { object value = Value; if (value != null) { string text = ((!(value is IFormattable formattable)) ? ((value is Uri uri) ? uri.OriginalString : value.ToString()) : formattable.ToString(null, Culture)); SetToken(JsonToken.String, text, updateIndex: false); return text; } } throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } public virtual byte[]? ReadAsBytes() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.StartObject: { ReadIntoWrappedTypeObject(); byte[] array2 = ReadAsBytes(); ReaderReadAndAssert(); if (TokenType != JsonToken.EndObject) { throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } SetToken(JsonToken.Bytes, array2, updateIndex: false); return array2; } case JsonToken.String: { string text = (string)Value; Guid g; byte[] array3 = ((text.Length == 0) ? CollectionUtils.ArrayEmpty<byte>() : ((!ConvertUtils.TryConvertGuid(text, out g)) ? Convert.FromBase64String(text) : g.ToByteArray())); SetToken(JsonToken.Bytes, array3, updateIndex: false); return array3; } case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Bytes: if (Value is Guid guid) { byte[] array = guid.ToByteArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } return (byte[])Value; case JsonToken.StartArray: return ReadArrayIntoByteArray(); default: throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal byte[] ReadArrayIntoByteArray() { List<byte> list = new List<byte>(); do { if (!Read()) { SetToken(JsonToken.None); } } while (!ReadArrayElementIntoByteArrayReportDone(list)); byte[] array = list.ToArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } private bool ReadArrayElementIntoByteArrayReportDone(List<byte> buffer) { switch (TokenType) { case JsonToken.None: throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); case JsonToken.Integer: buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); return false; case JsonToken.EndArray: return true; case JsonToken.Comment: return false; default: throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } public virtual double? ReadAsDouble() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is double) { return (double)value; } double num = ((!(value is BigInteger bigInteger)) ? Convert.ToDouble(value, CultureInfo.InvariantCulture) : ((double)bigInteger)); SetToken(JsonToken.Float, num, updateIndex: false); return num; } case JsonToken.String: return ReadDoubleString((string)Value); default: throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal double? ReadDoubleString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual bool? ReadAsBoolean() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { bool flag = ((!(Value is BigInteger bigInteger)) ? Convert.ToBoolean(Value, CultureInfo.InvariantCulture) : (bigInteger != 0L)); SetToken(JsonToken.Boolean, flag, updateIndex: false); return flag; } case JsonToken.String: return ReadBooleanString((string)Value); case JsonToken.Boolean: return (bool)Value; default: throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal bool? ReadBooleanString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (bool.TryParse(s, out var result)) { SetToken(JsonToken.Boolean, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual decimal? ReadAsDecimal() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is decimal) { return (decimal)value; } decimal num; if (value is BigInteger bigInteger) { num = (decimal)bigInteger; } else { try { num = Convert.ToDecimal(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw JsonReaderException.Create(this, "Could not convert to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex); } } SetToken(JsonToken.Float, num, updateIndex: false); return num; } case JsonToken.String: return ReadDecimalString((string)Value); default: throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal decimal? ReadDecimalString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (decimal.TryParse(s, NumberStyles.Number, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } if (ConvertUtils.DecimalTryParse(s.ToCharArray(), 0, s.Length, out result) == ParseResult.Success) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTime? ReadAsDateTime() { switch (GetContentToken()) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTimeOffset dateTimeOffset) { SetToken(JsonToken.Date, dateTimeOffset.DateTime, updateIndex: false); } return (DateTime)Value; case JsonToken.String: return ReadDateTimeString((string)Value); default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } internal DateTime? ReadDateTimeString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out var dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTimeOffset? ReadAsDateTimeOffset() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTime dateTime) { SetToken(JsonToken.Date, new DateTimeOffset(dateTime), updateIndex: false); } return (DateTimeOffset)Value; case JsonToken.String: { string s = (string)Value; return ReadDateTimeOffsetString(s); } default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal DateTimeOffset? ReadDateTimeOffsetString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out var dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } internal void ReaderReadAndAssert() { if (!Read()) { throw CreateUnexpectedEndException(); } } internal JsonReaderException CreateUnexpectedEndException() { return JsonReaderException.Create(this, "Unexpected end when reading JSON."); } internal void ReadIntoWrappedTypeObject() { ReaderReadAndAssert(); if (Value != null && Value.ToString() == "$type") { ReaderReadAndAssert(); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReaderReadAndAssert(); if (Value.ToString() == "$value") { return; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } public void Skip() { if (TokenType == JsonToken.PropertyName) { Read(); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (Read() && depth < Depth) { } } } protected void SetToken(JsonToken newToken) { SetToken(newToken, null, updateIndex: true); } protected void SetToken(JsonToken newToken, object? value) { SetToken(newToken, value, updateIndex: true); } protected void SetToken(JsonToken newToken, object? value, bool updateIndex) { _tokenType = newToken; _value = value; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JsonContainerType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JsonContainerType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JsonContainerType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); break; case JsonToken.PropertyName: _currentState = State.Property; _currentPosition.PropertyName = (string)value; break; case JsonToken.Raw: case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: SetPostValueState(updateIndex); break; case JsonToken.Comment: break; } } internal void SetPostValueState(bool updateIndex) { if (Peek() != 0 || SupportMultipleContent) { _currentState = State.PostValue; } else { SetFinished(); } if (updateIndex) { UpdateScopeWithFinishedValue(); } } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) { _currentPosition.Position++; } } private void ValidateEnd(JsonToken endToken) { JsonContainerType jsonContainerType = Pop(); if (GetTypeForCloseToken(endToken) != jsonContainerType) { throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, jsonContainerType)); } if (Peek() != 0 || SupportMultipleContent) { _currentState = State.PostValue; } else { SetFinished(); } } protected void SetStateBasedOnCurrent() { JsonContainerType jsonContainerType = Peek(); switch (jsonContainerType) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Constructor; break; case JsonContainerType.None: SetFinished(); break; default: throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContainerType)); } } private void SetFinished() { _currentState = ((!SupportMultipleContent) ? State.Finished : State.Start); } private JsonContainerType GetTypeForCloseToken(JsonToken token) { return token switch { JsonToken.EndObject => JsonContainerType.Object, JsonToken.EndArray => JsonContainerType.Array, JsonToken.EndConstructor => JsonContainerType.Constructor, _ => throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)), }; } void IDisposable.Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) { Close(); } } public virtual void Close() { _currentState = State.Closed; _tokenType = JsonToken.None; _value = null; } internal void ReadAndAssert() { if (!Read()) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal void ReadForTypeAndAssert(JsonContract? contract, bool hasConverter) { if (!ReadForType(contract, hasConverter)) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal bool ReadForType(JsonContract? contract, bool hasConverter) { if (hasConverter) { return Read(); } switch (contract?.InternalReadType ?? ReadType.Read) { case ReadType.Read: return ReadAndMoveToContent(); case ReadType.ReadAsInt32: ReadAsInt32(); break; case ReadType.ReadAsInt64: { bool result = ReadAndMoveToContent(); if (TokenType == JsonToken.Undefined) { throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract?.UnderlyingType ?? typeof(long))); } return result; } case ReadType.ReadAsDecimal: ReadAsDecimal(); break; case ReadType.ReadAsDouble: ReadAsDouble(); break; case ReadType.ReadAsBytes: ReadAsBytes(); break; case ReadType.ReadAsBoolean: ReadAsBoolean(); break; case ReadType.ReadAsString: ReadAsString(); break; case ReadType.ReadAsDateTime: ReadAsDateTime(); break; case ReadType.ReadAsDateTimeOffset: ReadAsDateTimeOffset(); break; default: throw new ArgumentOutOfRangeException(); } return TokenType != JsonToken.None; } internal bool ReadAndMoveToContent() { if (Read()) { return MoveToContent(); } return false; } internal bool MoveToContent() { JsonToken tokenType = TokenType; while (tokenType == JsonToken.None || tokenType == JsonToken.Comment) { if (!Read()) { return false; } tokenType = TokenType; } return true; } private JsonToken GetContentToken() { JsonToken tokenType; do { if (!Read()) { SetToken(JsonToken.None); return JsonToken.None; } tokenType = TokenType; } while (tokenType == JsonToken.Comment); return tokenType; } } [Serializable] public class JsonReaderException : JsonException { public int LineNumber { get; } public int LinePosition { get; } public string? Path { get; } public JsonReaderException() { } public JsonReaderException(string message) : base(message) { } public JsonReaderException(string message, Exception innerException) : base(message, innerException) { } public JsonReaderException(SerializationInfo info, StreamingContext context) : base(info, context) { } public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception? innerException) : base(message, innerException) { Path = path; LineNumber = lineNumber; LinePosition = linePosition; } internal static JsonReaderException Create(JsonReader reader, string message) { return Create(reader, message, null); } internal static JsonReaderException Create(JsonReader reader, string message, Exception? ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } internal static JsonReaderException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); int lineNumber; int linePosition; if (lineInfo != null && lineInfo.HasLineInfo()) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = 0; linePosition = 0; } return new JsonReaderException(message, path, lineNumber, linePosition, ex); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonRequiredAttribute : Attribute { } [Serializable] public class JsonSerializationException : JsonException { public int LineNumber { get; } public int LinePosition { get; } public string? Path { get; } public JsonSerializationException() { } public JsonSerializationException(string message) : base(message) { } public JsonSerializationException(string message, Exception innerException) : base(message, innerException) { } public JsonSerializationException(SerializationInfo info, StreamingContext context) : base(info, context) { } public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception? innerException) : base(message, innerException) { Path = path; LineNumber = lineNumber; LinePosition = linePosition; } internal static JsonSerializationException Create(JsonReader reader, string message) { return Create(reader, message, null); } internal static JsonSerializationException Create(JsonReader reader, string message, Exception? ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } internal static JsonSerializationException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); int lineNumber; int linePosition; if (lineInfo != null && lineInfo.HasLineInfo()) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = 0; linePosition = 0; } return new JsonSerializationException(message, path, lineNumber, linePosition, ex); } } public class JsonSerializer { internal TypeNameHandling _typeNameHandling; internal TypeNameAssemblyFormatHandling _typeNameAssemblyFormatHandling; internal PreserveReferencesHandling _preserveReferencesHandling; internal ReferenceLoopHandling _referenceLoopHandling; internal MissingMemberHandling _missingMemberHandling; internal ObjectCreationHandling _objectCreationHandling; internal NullValueHandling _nullValueHandling; internal DefaultValueHandling _defaultValueHandling; internal ConstructorHandling _constructorHandling; internal MetadataPropertyHandling _metadataPropertyHandling; internal JsonConverterCollection? _converters; internal IContractResolver _contractResolver; internal ITraceWriter? _traceWriter; internal IEqualityComparer? _equalityComparer; internal ISerializationBinder _serializationBinder; internal StreamingContext _context; private IReferenceResolver? _referenceResolver; private Formatting? _formatting; private DateFormatHandling? _dateFormatHandling; private DateTimeZoneHandling? _dateTimeZoneHandling; private DateParseHandling? _dateParseHandling; private FloatFormatHandling? _floatFormatHandling; private FloatParseHandling? _floatParseHandling; private StringEscapeHandling? _stringEscapeHandling; private CultureInfo _culture; private int? _maxDepth; private bool _maxDepthSet; private bool? _checkAdditionalContent; private string? _dateFormatString; private bool _dateFormatStringSet; public virtual IReferenceResolver? ReferenceResolver { get { return GetReferenceResolver(); } set { if (value == null) { throw new ArgumentNullException("value", "Reference resolver cannot be null."); } _referenceResolver = value; } } [Obsolete("Binder is obsolete. Use SerializationBinder instead.")] public virtual SerializationBinder Binder { get { if (_serializationBinder is SerializationBinder result) { return result; } if (_serializationBinder is SerializationBinderAdapter serializationBinderAdapter) { return serializationBinderAdapter.SerializationBinder; } throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set."); } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } _serializationBinder = (value as ISerializationBinder) ?? new SerializationBinderAdapter(value); } } public virtual ISerializationBinder SerializationBinder { get { return _serializationBinder; } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } _serializationBinder = value; } } public virtual ITraceWriter? TraceWriter { get { return _traceWriter; } set { _traceWriter = value; } } public virtual IEqualityComparer? EqualityComparer { get { return _equalityComparer; } set { _equalityComparer = value; } } public virtual TypeNameHandling TypeNameHandling { get { return _typeNameHandling; } set { if (value < TypeNameHandling.None || value > TypeNameHandling.Auto) { throw new ArgumentOutOfRangeException("value"); } _typeNameHandling = value; } } [Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")] public virtual FormatterAssemblyStyle TypeNameAssemblyFormat { get { return (FormatterAssemblyStyle)_typeNameAssemblyFormatHandling; } set { if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full) { throw new ArgumentOutOfRangeException("value"); } _typeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value; } } public virtual TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling { get { return _typeNameAssemblyFormatHandling; } set { if (value < TypeNameAssemblyFormatHandling.Simple || value > TypeNameAssemblyFormatHandling.Full) { throw new ArgumentOutOfRangeException("value"); } _typeNameAssemblyFormatHandling = value; } } public virtual PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling; } set { if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All) { throw new ArgumentOutOfRangeException("value"); } _preserveReferencesHandling = value; } } public virtual ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling; } set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) { throw new ArgumentOutOfRangeException("value"); } _referenceLoopHandling = value; } } public virtual MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling; } set { if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error) { throw new ArgumentOutOfRangeException("value"); } _missingMemberHandling = value; } } public virtual NullValueHandling NullValueHandling { get { return _nullValueHandling; } set { if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _nullValueHandling = value; } } public virtual DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling; } set { if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate) { throw new ArgumentOutOfRangeException("value"); } _defaultValueHandling = value; } } public virtual ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling; } set { if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace) { throw new ArgumentOutOfRangeException("value"); } _objectCreationHandling = value; } } public virtual ConstructorHandling ConstructorHandling { get { return _constructorHandling; } set { if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor) { throw new ArgumentOutOfRangeException("value"); } _constructorHandling = value; } } public virtual MetadataPropertyHandling MetadataPropertyHandling { get { return _metadataPropertyHandling; } set { if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _metadataPropertyHandling = value; } } public virtual JsonConverterCollection Converters { get { if (_converters == null) { _converters = new JsonConverterCollection(); } return _converters; } } public virtual IContractResolver ContractResolver { get { return _contractResolver; } set { _contractResolver = value ?? DefaultContractResolver.Instance; } } public virtual StreamingContext Context { get { return _context; } set { _context = value; } } public virtual Formatting Formatting { get { return _formatting.GetValueOrDefault(); } set { _formatting = value; } } public virtual DateFormatHandling DateFormatHandling { get { return _dateFormatHandling.GetValueOrDefault(); } set { _dateFormatHandling = value; } } public virtual DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling ?? DateTimeZoneHandling.RoundtripKind; } set { _dateTimeZoneHandling = value; } } public virtual DateParseHandling DateParseHandling { get { return _dateParseHandling ?? DateParseHandling.DateTime; } set { _dateParseHandling = value; } } public virtual FloatParseHandling FloatParseHandling { get { return _floatParseHandling.GetValueOrDefault(); } set { _floatParseHandling = value; } } public virtual FloatFormatHandling FloatFormatHandling { get { return _floatFormatHandling.GetValueOrDefault(); } set { _floatFormatHandling = value; } } public virtual StringEscapeHandling StringEscapeHandling { get { return _stringEscapeHandling.GetValueOrDefault(); } set { _stringEscapeHandling = value; } } public virtual string DateFormatString { get { return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; } set { _dateFormatString = value; _dateFormatStringSet = true; } } public virtual CultureInfo Culture { get { return _culture ?? JsonSerializerSettings.DefaultCulture; } set { _culture = value; } } public virtual int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; _maxDepthSet = true; } } public virtual bool CheckAdditionalContent { get { return _checkAdditionalContent.GetValueOrDefault(); } set { _checkAdditionalContent = value; } } public virtual event EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>? Error; internal bool IsCheckAdditionalContentSet() { return _checkAdditionalContent.HasValue; } public JsonSerializer() { _referenceLoopHandling = ReferenceLoopHandling.Error; _missingMemberHandling = MissingMemberHandling.Ignore; _nullValueHandling = NullValueHandling.Include; _defaultValueHandling = DefaultValueHandling.Include; _objectCreationHandling = ObjectCreationHandling.Auto; _preserveReferencesHandling = PreserveReferencesHandling.None; _constructorHandling = ConstructorHandling.Default; _typeNameHandling = TypeNameHandling.None; _metadataPropertyHandling = MetadataPropertyHandling.Default; _context = JsonSerializerSettings.DefaultContext; _serializationBinder = DefaultSerializationBinder.Instance; _culture = JsonSerializerSettings.DefaultCulture; _contractResolver = DefaultContractResolver.Instance; } public static JsonSerializer Create() { return new JsonSerializer(); } public static JsonSerializer Create(JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = Create(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } public static JsonSerializer CreateDefault() { return Create(JsonConvert.DefaultSettings?.Invoke()); } public static JsonSerializer CreateDefault(JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = CreateDefault(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings) { if (!CollectionUtils.IsNullOrEmpty(settings.Converters)) { for (int i = 0; i < settings.Converters.Count; i++) { serializer.Converters.Insert(i, settings.Converters[i]); } } if (settings._typeNameHandling.HasValue) { serializer.TypeNameHandling = settings.TypeNameHandling; } if (settings._metadataPropertyHandling.HasValue) { serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling; } if (settings._typeNameAssemblyFormatHandling.HasValue) { serializer.TypeNameAssemblyFormatHandling = settings.TypeNameAssemblyFormatHandling; } if (settings._preserveReferencesHandling.HasValue) { serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling; } if (settings._referenceLoopHandling.HasValue) { serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; } if (settings._missingMemberHandling.HasValue) { serializer.MissingMemberHandling = settings.MissingMemberHandling; } if (settings._objectCreationHandling.HasValue) { serializer.ObjectCreationHandling = settings.ObjectCreationHandling; } if (settings._nullValueHandling.HasValue) { serializer.NullValueHandling = settings.NullValueHandling; } if (settings._defaultValueHandling.HasValue) { serializer.DefaultValueHandling = settings.DefaultValueHandling; } if (settings._constructorHandling.HasValue) { serializer.ConstructorHandling = settings.ConstructorHandling; } if (settings._context.HasValue) { serializer.Context = settings.Context; } if (settings._checkAdditionalContent.HasValue) { serializer._checkAdditionalContent = settings._checkAdditionalContent; } if (settings.Error != null) { serializer.Error += settings.Error; } if (settings.ContractResolver != null) { serializer.ContractResolver = settings.ContractResolver; } if (settings.ReferenceResolverProvider != null) { serializer.ReferenceResolver = settings.ReferenceResolverProvider(); } if (settings.TraceWriter != null) { serializer.TraceWriter = settings.TraceWriter; } if (settings.EqualityComparer != null) { serializer.EqualityComparer = settings.EqualityComparer; } if (settings.SerializationBinder != null) { serializer.SerializationBinder = settings.SerializationBinder; } if (settings._formatting.HasValue) { serializer._formatting = settings._formatting; } if (settings._dateFormatHandling.HasValue) { serializer._dateFormatHandling = settings._dateFormatHandling; } if (settings._dateTimeZoneHandling.HasValue) { serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling; } if (settings._dateParseHandling.HasValue) { serializer._dateParseHandling = settings._dateParseHandling; } if (settings._dateFormatStringSet) { serializer._dateFormatString = settings._dateFormatString; serializer._dateFormatStringSet = settings._dateFormatStringSet; } if (settings._floatFormatHandling.HasValue) { serializer._floatFormatHandling = settings._floatFormatHandling; } if (settings._floatParseHandling.HasValue) { serializer._floatParseHandling = settings._floatParseHandling; } if (settings._stringEscapeHandling.HasValue) { serializer._stringEscapeHandling = settings._stringEscapeHandling; } if (settings._culture != null) { serializer._culture = settings._culture; } if (settings._maxDepthSet) { serializer._maxDepth = settings._maxDepth; serializer._maxDepthSet = settings._maxDepthSet; } } [DebuggerStepThrough] public void Populate(TextReader reader, object target) { Populate(new JsonTextReader(reader), target); } [DebuggerStepThrough] public void Populate(JsonReader reader, object target) { PopulateInternal(reader, target); } internal virtual void PopulateInternal(JsonReader reader, object target) { ValidationUtils.ArgumentNotNull(reader, "reader"); ValidationUtils.ArgumentNotNull(target, "target"); SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null); new JsonSerializerInternalReader(this).Populate(traceJsonReader ?? reader, target); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); } [DebuggerStepThrough] public object? Deserialize(JsonReader reader) { return Deserialize(reader, null); } [DebuggerStepThrough] public object? Deserialize(TextReader reader, Type objectType) { return Deserialize(new JsonTextReader(reader), objectType); } [DebuggerStepThrough] public T? Deserialize<T>(JsonReader reader) { return (T)Deserialize(reader, typeof(T)); } [DebuggerStepThrough] public object? Deserialize(JsonReader reader, Type? objectType) { return DeserializeInternal(reader, objectType); } internal virtual object? DeserializeInternal(JsonReader reader, Type? objectType) { ValidationUtils.ArgumentNotNull(reader, "reader"); SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null); object? result = new JsonSerializerInternalReader(this).Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); return result; } private void SetupReader(JsonReader reader, out CultureInfo? previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string? previousDateFormatString) { if (_culture != null && !_culture.Equals(reader.Culture)) { previousCulture = reader.Culture; reader.Culture = _culture; } else { previousCulture = null; } if (_dateTimeZoneHandling.HasValue && reader.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = reader.DateTimeZoneHandling; reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } else { previousDateTimeZoneHandling = null; } if (_dateParseHandling.HasValue && reader.DateParseHandling != _dateParseHandling) { previousDateParseHandling = reader.DateParseHandling; reader.DateParseHandling = _dateParseHandling.GetValueOrDefault(); } else { previousDateParseHandling = null; } if (_floatParseHandling.HasValue && reader.FloatParseHandling != _floatParseHandling) { previousFloatParseHandling = reader.FloatParseHandling; reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault(); } else { previousFloatParseHandling = null; } if (_maxDepthSet && reader.MaxDepth != _maxDepth) { previousMaxDepth = reader.MaxDepth; reader.MaxDepth = _maxDepth; } else { previousMaxDepth = null; } if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString) { previousDateFormatString = reader.DateFormatString; reader.DateFormatString = _dateFormatString; } else { previousDateFormatString = null; } if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable == null && _contractResolver is DefaultContractResolver defaultContractResolver) { jsonTextReader.PropertyNameTable = defaultContractResolver.GetNameTable(); } } private void ResetReader(JsonReader reader, CultureInfo? previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string? previousDateFormatString) { if (previousCulture != null) { reader.Culture = previousCulture; } if (previousDateTimeZoneHandling.HasValue) { reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault(); } if (previousDateParseHandling.HasValue) { reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault(); } if (previousFloatParseHandling.HasValue) { reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault(); } if (_maxDepthSet) { reader.MaxDepth = previousMaxDepth; } if (_dateFormatStringSet) { reader.DateFormatString = previousDateFormatString; } if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable != null && _contractResolver is DefaultContractResolver defaultContractResolver && jsonTextReader.PropertyNameTable == defaultContractResolver.GetNameTable()) { jsonTextReader.PropertyNameTable = null; } } public void Serialize(TextWriter textWriter, object? value) { Serialize(new JsonTextWriter(textWriter), value); } public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType) { SerializeInternal(jsonWriter, value, objectType); } public void Serialize(TextWriter textWriter, object? value, Type objectType) { Serialize(new JsonTextWriter(textWriter), value, objectType); } public void Serialize(JsonWriter jsonWriter, object? value) { SerializeInternal(jsonWriter, value, null); } private TraceJsonReader CreateTraceJsonReader(JsonReader reader) { TraceJsonReader traceJsonReader = new TraceJsonReader(reader); if (reader.TokenType != 0) { traceJsonReader.WriteCurrentToken(); } return traceJsonReader; } internal virtual void SerializeInternal(JsonWriter jsonWriter, object? value, Type? objectType) { ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter"); Formatting? formatting = null; if (_formatting.HasValue && jsonWriter.Formatting != _formatting) { formatting = jsonWriter.Formatting; jsonWriter.Formatting = _formatting.GetValueOrDefault(); } DateFormatHandling? dateFormatHandling = null; if (_dateFormatHandling.HasValue && jsonWriter.DateFormatHandling != _dateFormatHandling) { dateFormatHandling = jsonWriter.DateFormatHandling; jsonWriter.DateFormatHandling = _dateFormatHandling.GetValueOrDefault(); } DateTimeZoneHandling? dateTimeZoneHandling = null; if (_dateTimeZoneHandling.HasValue && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling) { dateTimeZoneHandling = jsonWriter.DateTimeZoneHandling; jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } FloatFormatHandling? floatFormatHandling = null; if (_floatFormatHandling.HasValue && jsonWriter.FloatFormatHandling != _floatFormatHandling) { floatFormatHandling = jsonWriter.FloatFormatHandling; jsonWriter.FloatFormatHandling = _floatFormatHandling.GetValueOrDefault(); } StringEscapeHandling? stringEscapeHandling = null; if (_stringEscapeHandling.HasValue && jsonWriter.StringEscapeHandling != _stringEscapeHandling) { stringEscapeHandling = jsonWriter.StringEscapeHandling; jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault(); } CultureInfo cultureInfo = null; if (_culture != null && !_culture.Equals(jsonWriter.Culture)) { cultureInfo = jsonWriter.Culture; jsonWriter.Culture = _culture; } string dateFormatString = null; if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString) { dateFormatString = jsonWriter.DateFormatString; jsonWriter.DateFormatString = _dateFormatString; } TraceJsonWriter traceJsonWriter = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null); new JsonSerializerInternalWriter(this).Serialize(traceJsonWriter ?? jsonWriter, value, objectType); if (traceJsonWriter != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null); } if (formatting.HasValue) { jsonWriter.Formatting = formatting.GetValueOrDefault(); } if (dateFormatHandling.HasValue) { jsonWriter.DateFormatHandling = dateFormatHandling.GetValueOrDefault(); } if (dateTimeZoneHandling.HasValue) { jsonWriter.DateTimeZoneHandling = dateTimeZoneHandling.GetValueOrDefault(); } if (floatFormatHandling.HasValue) { jsonWriter.FloatFormatHandling = floatFormatHandling.GetValueOrDefault(); } if (stringEscapeHandling.HasValue) { jsonWriter.StringEscapeHandling = stringEscapeHandling.GetValueOrDefault(); } if (_dateFormatStringSet) { jsonWriter.DateFormatString = dateFormatString; } if (cultureInfo != null) { jsonWriter.Culture = cultureInfo; } } internal IReferenceResolver GetReferenceResolver() { if (_referenceResolver == null) { _referenceResolver = new DefaultReferenceResolver(); } return _referenceResolver; } internal JsonConverter? GetMatchingConverter(Type type) { return GetMatchingConverter(_converters, type); } internal static JsonConverter? GetMatchingConverter(IList<JsonConverter>? converters, Type objectType) { if (converters != null) { for (int i = 0; i < converters.Count; i++) { JsonConverter jsonConverter = converters[i]; if (jsonConverter.CanConvert(objectType)) { return jsonConverter; } } } return null; } internal void OnError(Newtonsoft.Json.Serialization.ErrorEventArgs e) { this.Error?.Invoke(this, e); } } public class JsonSerializerSettings { internal const ReferenceLoopHandling DefaultReferenceLoopHandling = ReferenceLoopHandling.Error; internal const MissingMemberHandling DefaultMissingMemberHandling = MissingMemberHandling.Ignore; internal const NullValueHandling DefaultNullValueHandling = NullValueHandling.Include; internal const DefaultValueHandling DefaultDefaultValueHandling = DefaultValueHandling.Include; internal const ObjectCreationHandling DefaultObjectCreationHandling = ObjectCreationHandling.Auto; internal const PreserveReferencesHandling DefaultPreserveReferencesHandling = PreserveReferencesHandling.None; internal const ConstructorHandling DefaultConstructorHandling = ConstructorHandling.Default; internal const TypeNameHandling DefaultTypeNameHandling = TypeNameHandling.None; internal const MetadataPropertyHandling DefaultMetadataPropertyHandling = MetadataPropertyHandling.Default; internal static readonly StreamingContext DefaultContext; internal const Formatting DefaultFormatting = Formatting.None; internal const DateFormatHandling DefaultDateFormatHandling = DateFormatHandling.IsoDateFormat; internal const DateTimeZoneHandling DefaultDateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; internal const DateParseHandling DefaultDateParseHandling = DateParseHandling.DateTime; internal const FloatParseHandling DefaultFloatParseHandling = FloatParseHandling.Double; internal const FloatFormatHandling DefaultFloatFormatHandling = FloatFormatHandling.String; internal const StringEscapeHandling DefaultStringEscapeHandling = StringEscapeHandling.Default; internal const TypeNameAssemblyFormatHandling DefaultTypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple; internal static readonly CultureInfo DefaultCulture; internal const bool DefaultCheckAdditionalContent = false; internal const string DefaultDateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; internal const int DefaultMaxDepth = 64; internal Formatting? _formatting; internal DateFormatHandling? _dateFormatHandling; internal DateTimeZoneHandling? _dateTimeZoneHandling; internal DateParseHandling? _dateParseHandling; internal FloatFormatHandling? _floatFormatHandling; internal FloatParseHandling? _floatParseHandling; internal StringEscapeHandling? _stringEscapeHandling; internal CultureInfo? _culture; internal bool? _checkAdditionalContent; internal int? _maxDepth; internal bool _maxDepthSet; internal string? _dateFormatString; internal bool _dateFormatStringSet; internal TypeNameAssemblyFormatHandling? _typeNameAssemblyFormatHandling; internal DefaultValueHandling? _defaultValueHandling; internal PreserveReferencesHandling? _preserveReferencesHandling; internal NullValueHandling? _nullValueHandling; internal ObjectCreationHandling? _objectCreationHandling; internal MissingMemberHandling? _missingMemberHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal StreamingContext? _context; internal ConstructorHandling? _constructorHandling; internal TypeNameHandling? _typeNameHandling; internal MetadataPropertyHandling? _metadataPropertyHandling; public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling.GetValueOrDefault(); } set { _referenceLoopHandling = value; } } public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling.GetValueOrDefault(); } set { _missingMemberHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling.GetValueOrDefault(); } set { _objectCreationHandling = value; } } public NullValueHandling NullValueHandling { get { return _nullValueHandling.GetValueOrDefault(); } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling.GetValueOrDefault(); } set { _defaultValueHandling = value; } } public IList<JsonConverter> Converters { get; set; } public PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling.GetValueOrDefault(); } set { _preserveReferencesHandling = value; } } public TypeNameHandling TypeNameHandling
ReelySpecTackleLure.dll
Decompiled 6 months agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using Newtonsoft.Json; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("ReelySpecTackleLure")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ReelySpecTackleLure")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("9f8a1b6e-6d0e-4dab-bbd8-9ed433836544")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace neobotics.ValheimMods; internal class DebugUtils { public static void ObjectInspector(object o) { if (o == null) { Debug.Log((object)"Object is null"); return; } BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; Type type = o.GetType(); Debug.Log((object)(o.ToString() + " Type " + type.Name)); PropertyInfo[] properties = type.GetProperties(bindingAttr); PropertyInfo[] array = properties; foreach (PropertyInfo propertyInfo in array) { Debug.Log((object)$"{type.Name}.{propertyInfo.Name} = {propertyInfo.GetValue(o)}"); } FieldInfo[] fields = type.GetFields(bindingAttr); FieldInfo[] array2 = fields; foreach (FieldInfo field in array2) { FieldPrinter(o, type, field); } } public static void MethodInspector(object o) { if (o == null) { Debug.Log((object)"Object is null"); return; } BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; Type type = o.GetType(); Debug.Log((object)(o.ToString() + " Type " + type.Name)); MethodInfo[] methods = type.GetMethods(bindingAttr); foreach (MethodInfo methodInfo in methods) { ParameterInfo[] parameters = methodInfo.GetParameters(); string arg = string.Join(", ", (from x in methodInfo.GetParameters() select x.ParameterType?.ToString() + " " + x.Name).ToArray()); Debug.Log((object)$"{methodInfo.ReturnType} {methodInfo.Name} ({arg})"); } } private static void ItemDataInspector(ItemData item) { ObjectInspector(item); ObjectInspector(item.m_shared); } private static void FieldPrinter(object o, Type t, FieldInfo field) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Expected O, but got Unknown //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Expected O, but got Unknown try { if (field.FieldType == typeof(ItemData)) { ItemData val = (ItemData)field.GetValue(o); if (val != null) { ItemDataInspector(val); } else { Debug.Log((object)$"{t.Name}.{field.Name} = {field.GetValue(o)} [null]"); } } else if (field.FieldType == typeof(Transform)) { Transform val2 = (Transform)field.GetValue(o); if ((Object)(object)val2 != (Object)null) { Debug.Log((object)("\tTransform.parent = " + ((Object)val2.parent).name)); } else { Debug.Log((object)$"{t.Name}.{field.Name} = {field.GetValue(o)} [null]"); } } else if (field.FieldType == typeof(EffectList)) { EffectList val3 = (EffectList)field.GetValue(o); if (val3 != null) { Debug.Log((object)$"{t.Name}.{field.Name} = {field.GetValue(o)}:"); EffectData[] effectPrefabs = val3.m_effectPrefabs; foreach (EffectData val4 in effectPrefabs) { Debug.Log((object)("\tEffectData.m_prefab = " + ((Object)val4.m_prefab).name)); } } else { Debug.Log((object)$"{t.Name}.{field.Name} = {field.GetValue(o)} [null]"); } } else { Debug.Log((object)$"{t.Name}.{field.Name} = {field.GetValue(o)}"); } } catch (Exception) { Debug.Log((object)("Exception accessing " + t?.Name + "." + field?.Name)); } } public static void GameObjectInspector(GameObject go) { Debug.Log((object)("\n\nInspecting GameObject " + ((Object)go).name)); ObjectInspector(go); Component[] componentsInChildren = go.GetComponentsInChildren<Component>(); Component[] array = componentsInChildren; foreach (Component val in array) { try { string obj = ((val != null) ? ((Object)val).name : null); object obj2; if (val == null) { obj2 = null; } else { Transform transform = val.transform; if (transform == null) { obj2 = null; } else { Transform parent = transform.parent; obj2 = ((parent != null) ? ((Object)parent).name : null); } } Debug.Log((object)("\n\nInspecting Component " + obj + " with parent " + (string?)obj2)); ObjectInspector(val); } catch (Exception) { } } } public static void ComponentInspector(Component c) { Debug.Log((object)("\n\nInspecting Component " + ((Object)c).name)); ObjectInspector(c); } public static void EffectsInspector(EffectList e) { EffectData[] effectPrefabs = e.m_effectPrefabs; Debug.Log((object)$"Effect list has effects {e.HasEffects()} count {effectPrefabs.Length}"); EffectData[] array = effectPrefabs; foreach (EffectData val in array) { Debug.Log((object)$"Effect Data {val} prefab name {((Object)val.m_prefab).name} prefab GameObject name {((Object)val.m_prefab.gameObject).name}"); } } public static void PrintInventory() { Player localPlayer = Player.m_localPlayer; Inventory inventory = ((Humanoid)localPlayer).GetInventory(); foreach (ItemData allItem in inventory.GetAllItems()) { Debug.Log((object)allItem.m_shared.m_name); } } public static void PrintAllObjects() { ZNetScene.instance.m_prefabs.ForEach(delegate(GameObject x) { Debug.Log((object)("GameObject " + ((Object)x).name)); }); } public static void PrintAllCharacters() { Character.GetAllCharacters().ForEach(delegate(Character x) { Debug.Log((object)("Character " + ((Object)x).name)); }); } public static void PrintAllLayers() { string[] array = (from index in Enumerable.Range(0, 31) select LayerMask.LayerToName(index) into l where !string.IsNullOrEmpty(l) select l).ToArray(); string[] array2 = array; foreach (string text in array2) { Debug.Log((object)("Layer " + text + " " + Convert.ToString(LayerMask.NameToLayer(text), 2).PadLeft(32, '0'))); } } } public class DelegatedConfigEntry<T> : DelegatedConfigEntryBase { private ConfigEntry<T> _entry; private EventHandler rootHandler = null; private Action<object, EventArgs> clientDelegate; private Logging Log; public ConfigEntry<T> ConfigEntry { get { return _entry; } set { _entry = value; if (_entry != null && rootHandler != null) { _entry.SettingChanged += rootHandler; } Name = ((ConfigEntryBase)_entry).Definition.Key; Section = ((ConfigEntryBase)_entry).Definition.Section; ServerValue = ((ConfigEntryBase)_entry).GetSerializedValue(); Log.Trace("Set " + Section + " " + Name + " to serialized value " + ServerValue); } } public T Value { get { return _entry.Value; } set { _entry.Value = value; } } public DelegatedConfigEntry(bool useServerDelegate = false) : this((Action<object, EventArgs>)null, useServerDelegate) { } public DelegatedConfigEntry(Action<object, EventArgs> delegateHandler, bool useServerDelegate = false) { Log = Logging.GetLogger(); Log.Trace("DelegatedConfigEntry"); if (delegateHandler != null) { clientDelegate = delegateHandler; } if (useServerDelegate) { Log.Trace("Configuring server delegate"); rootHandler = delegate(object s, EventArgs e) { ServerDelegate(s, e); }; ServerConfiguration.ServerDelegatedEntries.Add(this); } else if (clientDelegate != null) { rootHandler = delegate(object s, EventArgs e) { clientDelegate(s, e); }; } } private void ServerDelegate(object sender, EventArgs args) { //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Expected O, but got Unknown Logging.GetLogger().Trace("ServerDelegate"); _entry.SettingChanged -= rootHandler; ZNet instance = ZNet.instance; bool? flag = ((instance != null) ? new bool?(instance.IsServer()) : null); if (flag.HasValue) { if (flag == false) { if (ServerValue != null) { ((ConfigEntryBase)_entry).SetSerializedValue(ServerValue); } } else { ServerValue = ((ConfigEntryBase)_entry).GetSerializedValue(); ServerConfiguration.Instance.SendConfigToAllClients(sender, (SettingChangedEventArgs)args); } } if (clientDelegate != null) { clientDelegate(sender, args); } _entry.SettingChanged += rootHandler; } public void EnableHandler(bool setActive) { if (setActive) { _entry.SettingChanged += rootHandler; } else { _entry.SettingChanged -= rootHandler; } } public bool IsKeyPressed() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) if (ConfigEntry is ConfigEntry<KeyboardShortcut> val) { KeyboardShortcut value = val.Value; foreach (KeyCode modifier in ((KeyboardShortcut)(ref value)).Modifiers) { if (!Input.GetKey(modifier)) { return false; } } if (!Input.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey)) { return false; } return true; } Log.Error("Keyboard read attempted on non-KeyboardShortcut config."); return false; } public bool IsKeyDown() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) if (ConfigEntry is ConfigEntry<KeyboardShortcut> val) { KeyboardShortcut value = val.Value; foreach (KeyCode modifier in ((KeyboardShortcut)(ref value)).Modifiers) { if (!Input.GetKey(modifier)) { return false; } } if (!Input.GetKey(((KeyboardShortcut)(ref value)).MainKey)) { return false; } return true; } Log.Error("Keyboard read attempted on non-KeyboardShortcut config."); return false; } public bool IsKeyReleased() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) if (ConfigEntry is ConfigEntry<KeyboardShortcut> val) { KeyboardShortcut value = val.Value; foreach (KeyCode modifier in ((KeyboardShortcut)(ref value)).Modifiers) { if (!Input.GetKeyUp(modifier)) { return false; } } if (!Input.GetKeyUp(((KeyboardShortcut)(ref value)).MainKey)) { return false; } return true; } Log.Error("Keyboard read attempted on non-KeyboardShortcut config."); return false; } } public class DelegatedConfigEntryBase { public string Name = null; public string Section = null; public string ServerValue = null; } public class ServerConfiguration { [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class ZNet_OnNewConnection_Patch { private static void Postfix(ZNet __instance, ZNetPeer peer) { Log.Debug("ZNet OnNewConnection postfix"); if (!__instance.IsServer()) { try { peer.m_rpc.Register<ZPackage>("ClientConfigReceiver." + GetPluginGuid(), (Action<ZRpc, ZPackage>)RPC_ClientConfigReceiver); Log.Debug("PlayerChoice registered RPC_ClientConfigReceiver"); return; } catch (Exception) { Log.Warning("Failed to register RPC"); return; } } try { SendConfigToClient(peer); } catch (Exception) { Log.Warning("Error sending server configuration to client"); } } } public static List<DelegatedConfigEntryBase> ServerDelegatedEntries = new List<DelegatedConfigEntryBase>(); private static ConfigFile LocalConfig; private static BaseUnityPlugin Mod; private static string ConfigFileName; private static ServerConfiguration _instance; private static Logging Log; public static bool IsSetup = false; public FileSystemWatcher ConfigWatcher; private const string NOT_CONFIGURED = "ServerConfiguration not initialized. Setup first."; public static ServerConfiguration Instance { get { if (_instance == null) { _instance = new ServerConfiguration(); } return _instance; } } private ServerConfiguration() { } public void Setup(ConfigFile config, BaseUnityPlugin modInstance) { LocalConfig = config; Log = Logging.GetLogger(); Log.Trace("ServerConfiguration Setup"); Mod = modInstance; ConfigFileName = Path.GetFileName(LocalConfig.ConfigFilePath); IsSetup = true; } public void CreateConfigWatcher() { ConfigWatcher = Utils.CreateFileWatcher(LocalConfig.ConfigFilePath, LoadConfig); } private void LoadConfig(object sender, FileSystemEventArgs e) { if (!File.Exists(LocalConfig.ConfigFilePath)) { return; } try { Log.Debug($"Loading configuration {e.ChangeType}"); LocalConfig.Reload(); } catch { Log.Error("Error loading configuration file " + ConfigFileName); } } public static string GetPluginGuid() { return Mod.Info.Metadata.GUID; } public static void RPC_ClientConfigReceiver(ZRpc zrpc, ZPackage package) { if (!IsSetup) { Log.Error("ServerConfiguration not initialized. Setup first."); return; } Log.Debug("ClientConfigReceiver"); string section; string name; while (package.GetPos() < package.Size()) { section = package.ReadString(); name = package.ReadString(); string text = package.ReadString(); Log.Trace("Reading " + section + " " + name + " value " + text + " from ZPackage"); DelegatedConfigEntryBase delegatedConfigEntryBase = ServerDelegatedEntries.Find((DelegatedConfigEntryBase e) => e.Name == name && e.Section == section); if (delegatedConfigEntryBase != null) { Log.Trace("Found DCEB on client and setting to server value " + text); delegatedConfigEntryBase.ServerValue = text; } ConfigEntryBase val = LocalConfig[section, name]; if (val != null) { Log.Trace("Found local CEB and setting underlying config value " + text); val.SetSerializedValue(text); } } } internal static void WriteConfigEntries(ZPackage zpkg) { foreach (DelegatedConfigEntryBase serverDelegatedEntry in ServerDelegatedEntries) { Log.Trace("Writing " + serverDelegatedEntry.Section + " " + serverDelegatedEntry.Name + " value " + serverDelegatedEntry.ServerValue + " to ZPackage"); zpkg.Write(serverDelegatedEntry.Section); zpkg.Write(serverDelegatedEntry.Name); zpkg.Write(serverDelegatedEntry.ServerValue); } } internal static void SendConfigToClient(ZNetPeer peer) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown if (!IsSetup) { Log.Error("ServerConfiguration not initialized. Setup first."); return; } Log.Debug("SendConfigToClient"); ZPackage val = new ZPackage(); WriteConfigEntries(val); peer.m_rpc.Invoke("ClientConfigReceiver." + GetPluginGuid(), new object[1] { val }); Log.Trace("Invoked ClientConfigReceiver on peer"); } public void SendConfigToAllClients(object o, SettingChangedEventArgs e) { //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown if (!IsSetup) { Log.Error("ServerConfiguration not initialized. Setup first."); } else if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer() && ZNet.instance.GetPeerConnections() > 0) { Log.Debug("SendConfigToAllClients"); ZPackage zpkg = new ZPackage(); WriteConfigEntries(zpkg); ((MonoBehaviour)Mod).StartCoroutine(_instance.Co_BroadcastConfig(zpkg)); } } private IEnumerator Co_BroadcastConfig(ZPackage zpkg) { Log.Debug("Co_BroadcastConfig"); List<ZNetPeer> connectedPeers = ZNet.instance.GetConnectedPeers(); foreach (ZNetPeer peer in connectedPeers) { if (peer != ZNet.instance.GetServerPeer()) { peer.m_rpc.Invoke("ClientConfigReceiver." + GetPluginGuid(), new object[1] { zpkg }); Log.Trace("Invoked ClientConfigReceiver on peer"); } yield return null; } } } internal class Utils { public static TEnum Guardrails<TEnum>(string value, TEnum enumDefault) where TEnum : struct { if (Enum.TryParse<TEnum>(value, ignoreCase: true, out var result)) { return result; } return enumDefault; } public static int Guardrails(int value, int lbound, int ubound) { if (value < lbound) { return lbound; } if (value > ubound) { return ubound; } return value; } public static void GetCharactersInRangeXZ(Vector3 point, float radius, List<Character> characters) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) float num = radius * radius; foreach (Character s_character in Character.s_characters) { if (DistanceSqrXZ(((Component)s_character).transform.position, point) < num) { characters.Add(s_character); } } } public static float DistanceSqr(Vector3 v0, Vector3 v1) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) float num = v1.x - v0.x; float num2 = v1.y - v0.y; float num3 = v1.z - v0.z; return num * num + num2 * num2 + num3 * num3; } public static float DistanceSqrXZ(Vector3 v0, Vector3 v1) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) float num = v1.x - v0.x; float num2 = v1.z - v0.z; return num * num + num2 * num2; } public static float DistanceXZ(Vector3 v0, Vector3 v1) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) float num = v1.x - v0.x; float num2 = v1.z - v0.z; return Mathf.Sqrt(num * num + num2 * num2); } public static float Guardrails(float value, float lbound, float ubound) { if (value < lbound) { return lbound; } if (value > ubound) { return ubound; } return value; } public static string UnClonifiedName(string name) { if (name == null) { return null; } int num = name.IndexOf("(Clone)"); if (num < 1) { return name; } return name.Substring(0, num); } public static void SetTranslator(int id, string idText) { MethodInfo method = typeof(Localization).GetMethod("AddWord", BindingFlags.Instance | BindingFlags.NonPublic); method.Invoke(Localization.instance, new object[2] { "skill_" + id, idText }); } public static string GetTranslated(int id) { Logging.GetLogger().Debug(string.Format("Got translation for id {0} to {1}", id, Localization.instance.Localize("skill_" + id))); return Localization.instance.Localize("$skill_" + id); } public static string GetAssemblyPathedFile(string fileName) { Assembly executingAssembly = Assembly.GetExecutingAssembly(); FileInfo fileInfo = new FileInfo(executingAssembly.Location); string text = fileInfo.DirectoryName.Replace('\\', '/'); return text + "/" + fileName; } public static Sprite GetPrefabIcon(string prefabName) { Sprite result = null; GameObject prefab = GetPrefab(prefabName); ItemDrop val = default(ItemDrop); if ((Object)(object)prefab != (Object)null && prefab.TryGetComponent<ItemDrop>(ref val)) { result = val.m_itemData.GetIcon(); } return result; } public static Player GetPlayerByZDOID(ZDOID zid) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) foreach (Player allPlayer in Player.GetAllPlayers()) { ZDOID zDOID = ((Character)allPlayer).GetZDOID(); if (((ZDOID)(ref zDOID)).Equals(zid)) { return allPlayer; } } return null; } public static Character GetCharacterByZDOID(string cid) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) foreach (Character allCharacter in Character.GetAllCharacters()) { ZDOID zDOID = allCharacter.GetZDOID(); if (((object)(ZDOID)(ref zDOID)).ToString().Equals(cid)) { return allCharacter; } } return null; } public static Character GetCharacterByZDOID(ZDOID cid) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) foreach (Character allCharacter in Character.GetAllCharacters()) { ZDOID zDOID = allCharacter.GetZDOID(); if (((ZDOID)(ref zDOID)).Equals(cid)) { return allCharacter; } } return null; } public static ZNetPeer GetPeerByRPC(ZRpc rpc) { foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { if (peer.m_rpc == rpc) { return peer; } } return null; } public static List<GameObject> GetGameObjectsOfType(Type t) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) List<GameObject> list = new List<GameObject>(); Object[] array = Object.FindObjectsOfType(t); Object[] array2 = array; foreach (Object val in array2) { list.Add(((Component)val).gameObject); } return list; } public static GameObject GetClosestGameObjectOfType(Type t, Vector3 point, float radius) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return GetGameObjectsOfTypeInRangeByDistance(t, point, radius)?[0]; } public static List<GameObject> GetGameObjectsOfTypeInRangeByDistance(Type t, Vector3 point, float radius) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) List<KeyValuePair<GameObject, float>> list = new List<KeyValuePair<GameObject, float>>(); List<GameObject> gameObjectsOfTypeInRange = GetGameObjectsOfTypeInRange(t, point, radius); if (gameObjectsOfTypeInRange.Count > 0) { foreach (GameObject item in gameObjectsOfTypeInRange) { list.Add(new KeyValuePair<GameObject, float>(item, Vector3.Distance(item.transform.position, point))); } list.Sort((KeyValuePair<GameObject, float> pair1, KeyValuePair<GameObject, float> pair2) => pair1.Value.CompareTo(pair2.Value)); return list.ConvertAll((KeyValuePair<GameObject, float> x) => x.Key); } return null; } public static List<GameObject> GetGameObjectsOfTypeInRange(Type t, Vector3 point, float radius) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) return (from x in GetGameObjectsOfType(t) where Vector3.Distance(x.transform.position, point) < radius select x).ToList(); } public static float GetPointDepth(Vector3 p) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) return ZoneSystem.instance.m_waterLevel - GetSolidHeight(p); } public static List<string> GetDelimitedStringAsList(string delimitedString, char delimiter) { List<string> list = new List<string>(); string[] array = delimitedString.Split(new char[1] { delimiter }, StringSplitOptions.RemoveEmptyEntries); foreach (string text in array) { list.Add(text.Trim()); } return list; } public static float GetSolidHeight(Vector3 p) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) int solidRayMask = ZoneSystem.instance.m_solidRayMask; float result = 0f; p.y += 1000f; RaycastHit val = default(RaycastHit); if (Physics.Raycast(p, Vector3.down, ref val, 2000f, solidRayMask) && !Object.op_Implicit((Object)(object)((RaycastHit)(ref val)).collider.attachedRigidbody)) { result = ((RaycastHit)(ref val)).point.y; } return result; } public static Transform FindChild(Transform aParent, string aName) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown foreach (Transform item in aParent) { Transform val = item; if (((Object)val).name == aName) { return val; } Transform val2 = FindChild(val, aName); if ((Object)(object)val2 != (Object)null) { return val2; } } return null; } public static Transform FindParent(Transform go) { while ((Object)(object)go.parent != (Object)null) { go = go.parent; } return go; } public static GameObject GetPrefab(int prefabHash) { return GetPrefabByHash(prefabHash); } public static GameObject GetPrefabByHash(int prefabHash) { GameObject val = ObjectDB.instance.GetItemPrefab(prefabHash); Logging logger = Logging.GetLogger(); if ((Object)(object)val != (Object)null) { logger.Debug("Found prefab in ObjectDB"); } else { ZNetScene instance = ZNetScene.instance; val = ((instance != null) ? instance.GetPrefab(prefabHash) : null); if ((Object)(object)val != (Object)null) { logger.Debug("Found prefab in Scene"); } } return val; } public static GameObject GetPrefab(string prefabName) { GameObject val = ObjectDB.instance.GetItemPrefab(prefabName); Logging logger = Logging.GetLogger(); if ((Object)(object)val != (Object)null) { logger.Debug("Found " + prefabName + " in ObjectDB"); } else { ZNetScene instance = ZNetScene.instance; val = ((instance != null) ? instance.GetPrefab(prefabName) : null); if ((Object)(object)val != (Object)null) { logger.Debug("Found " + prefabName + " in Scene"); } } return val; } public static string SerializeFromDictionary<K, V>(string delimp, string delimc, IDictionary<K, V> dict) { if (dict == null) { return null; } IEnumerable<string> values = dict.Select(delegate(KeyValuePair<K, V> kvp) { KeyValuePair<K, V> keyValuePair = kvp; string? obj = keyValuePair.Key?.ToString(); string text = delimc; keyValuePair = kvp; return obj + text + keyValuePair.Value; }); return string.Join(delimp, values); } public static void DeserializeToDictionary<K, V>(string serializedString, string delimp, string delimc, ref IDictionary<K, V> dict) { if (dict == null) { return; } dict.Clear(); string[] separator = new string[1] { delimp }; string[] separator2 = new string[1] { delimc }; string[] array = serializedString.Split(separator, StringSplitOptions.RemoveEmptyEntries); string[] array2 = array; foreach (string text in array2) { string[] array3 = text.Split(separator2, StringSplitOptions.RemoveEmptyEntries); if (array3.Length == 2) { dict.Add(TypedValue<K>(array3[0]), TypedValue<V>(array3[1])); } } } public static FileSystemWatcher CreateFileWatcher(string fullPath, FileSystemEventHandler handler) { string fileName = Path.GetFileName(fullPath); string path = fullPath.Substring(0, fullPath.Length - fileName.Length); FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(path, fileName); fileSystemWatcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.CreationTime; fileSystemWatcher.Changed += handler; fileSystemWatcher.Created += handler; fileSystemWatcher.IncludeSubdirectories = false; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; return fileSystemWatcher; } public static T TypedValue<T>(object a) { return (T)Convert.ChangeType(a, typeof(T)); } public static float TimeAdjustedRamp(float maxValue, float duration, float elapsedTime, float pctFromStartRise, float pctFromEndFall) { float num = elapsedTime / duration; if (num <= pctFromStartRise) { return maxValue * (num / pctFromStartRise); } if (num >= 1f - pctFromEndFall) { return maxValue * ((1f - num) / pctFromEndFall); } return maxValue; } public static bool CopyComponentToGameObject(Component original, ref GameObject destination) { //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Expected O, but got Unknown Logging logger = Logging.GetLogger(); Type type = ((object)original).GetType(); logger.Debug($"Original Type is {type}"); GameObject obj = destination; logger.Debug("Destination GameObject " + ((obj != null) ? ((Object)obj).name : null)); Component val = destination.GetComponent(type); if ((Object)(object)val == (Object)null) { val = destination.AddComponent(type); } if ((Object)(object)val == (Object)null) { logger.Debug("Destination component is null"); return false; } Component val2 = (Component)Activator.CreateInstance(type); if ((Object)(object)val2 == (Object)null) { logger.Debug("Destination component is null"); return false; } if ((Object)(object)val2 == (Object)null) { logger.Debug("Boxed component is null"); return false; } FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { fieldInfo.SetValue(val2, fieldInfo.GetValue(original)); } val = val2; return true; } public static bool CopyObject(object original, object target) { Logging logger = Logging.GetLogger(); Type type = original.GetType(); Type type2 = target.GetType(); object obj = null; if (type == null) { logger.Warning("Copy Object: Source object is null"); obj = Activator.CreateInstance(type); return false; } if (type2 == null) { logger.Warning("Copy Object: Destination object is null"); return false; } if (type2 != type) { logger.Warning("Copy Object: Source and destination components are different types"); return false; } FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { fieldInfo.SetValue(target, fieldInfo.GetValue(original)); } return true; } } public class FishingBait : ICustomRecipe { public bool CanBeRepaired => false; public string Item => "$item_fishingbait"; public float MaxDurability => 1f; public int MaxQuality => 1; public string RecipeName => "Recipe_FishingBait"; public string Prefab => "FishingBait"; public bool RecoverPieces => false; public bool UseDurability => false; } internal class FishingRod : ICustomRecipe { public bool CanBeRepaired => true; public string Item => "$item_fishingrod"; public float MaxDurability => 100f; public int MaxQuality => 4; public string RecipeName => "Recipe_FishingRod"; public string Prefab => "FishingRod"; public bool RecoverPieces => true; public bool UseDurability => true; } public interface ICustomRecipe { string Item { get; } string RecipeName { get; } string Prefab { get; } bool CanBeRepaired { get; } int MaxQuality { get; } float MaxDurability { get; } bool UseDurability { get; } bool RecoverPieces { get; } } public class Logging { private static Logging _logger; public const int TRACE = 5; public const int DEBUG = 4; public const int INFO = 3; public const int WARNING = 2; public const int ERROR = 1; public const int CRITICAL = 0; public int LogLevel { get; set; } public string ModName { get; set; } private Logging(int level, string name) { LogLevel = level; ModName = name; } public static Logging GetLogger(int level, string name) { if (_logger == null) { _logger = new Logging(level, name); } return _logger; } public static Logging GetLogger() { if (_logger == null) { throw new NullReferenceException("Logger not initialized"); } return _logger; } public void Trace(string msg) { if (LogLevel >= 5) { Debug.Log((object)Message(msg)); } } public void Debug(string msg) { if (LogLevel >= 4) { Debug.Log((object)Message(msg)); } } public void Info(string msg) { if (LogLevel >= 3) { Debug.Log((object)Message(msg)); } } public void Warning(string msg) { if (LogLevel >= 2) { Debug.LogWarning((object)Message(msg)); } } public void Error(string msg) { if (LogLevel >= 1) { Debug.LogWarning((object)Message(msg)); } } public void Error(Exception e) { Error(e, stackTrace: false); } public void Error(Exception e, bool stackTrace) { if (LogLevel >= 1) { Debug.LogWarning((object)Message(e.Message)); if (stackTrace) { Debug.LogWarning((object)e.StackTrace); } } } public void Critical(Exception e) { if (LogLevel >= 0) { Debug.LogError((object)Message(e.Message)); Debug.LogError((object)e.StackTrace); } } private string Message(string msg) { return ModName + ": " + msg; } } public static class RecipeReader { private static string defaultJson = "\r\n{\r\n \"RecipeList\": [\r\n {\r\n \"Name\": \"Recipe_FishingRod\",\r\n\t \"Amount\": 1,\r\n\t \"Enabled\": true,\r\n\t \"CraftingStation\": \"piece_workbench\",\r\n\t \"MinStationLevel\": 2,\r\n \"Requirements\": [\r\n {\r\n \"Item\": \"LinenThread\",\r\n \"Amount\": 0,\r\n\t\t \"AmountPerLevel\": 10\r\n },\r\n {\r\n \"Item\": \"FineWood\",\r\n \"Amount\": 10,\r\n\t\t \"AmountPerLevel\": 5\r\n }\r\n ]\r\n },\r\n {\r\n \"Name\": \"Recipe_FishingBait\",\r\n\t \"Amount\": 20,\r\n\t \"Enabled\": true,\r\n\t \"CraftingStation\": \"piece_cauldron\",\r\n\t \"MinStationLevel\": 2,\r\n \"Requirements\": [\r\n {\r\n \"Item\": \"Entrails\",\r\n \"Amount\": 10\r\n },\r\n {\r\n \"Item\": \"Feathers\",\r\n \"Amount\": 5\r\n }\r\n ]\r\n }\r\n ]\r\n}\r\n"; private static Logging mLog = Logging.GetLogger(); public static Recipes ReadRecipes() { mLog.Debug("ReadRecipes"); Recipes recipes = null; Assembly executingAssembly = Assembly.GetExecutingAssembly(); try { FileInfo fileInfo = new FileInfo(executingAssembly.Location); string directoryName = fileInfo.DirectoryName; string text = File.ReadAllText(directoryName + "\\RSTLrecipes.json"); return JsonConvert.DeserializeObject<Recipes>(text); } catch (Exception) { mLog.Warning("Can't read RSTLrecipies.json. Using default config."); return JsonConvert.DeserializeObject<Recipes>(defaultJson); } } } public class Recipes { public List<RecipeDo> RecipeList { get; set; } } internal class RecipieMaker { private static Logging mLog = Logging.GetLogger(); public static void InitFishingRecipes(Recipes recipes) { ICustomRecipe customRecipe; foreach (RecipeDo recipe in recipes.RecipeList) { string name = recipe.Name; string text = name; if (!(text == "Recipe_FishingRod")) { if (!(text == "Recipe_FishingBait")) { mLog.Error("Recipe " + recipe.Name + " not supported"); break; } customRecipe = new FishingBait(); } else { customRecipe = new FishingRod(); } Recipe val = ObjectDB.instance.m_recipes.Find((Recipe x) => ((Object)x).name.Equals(customRecipe.RecipeName)); if ((Object)(object)val == (Object)null) { mLog.Debug(customRecipe.RecipeName + " recipe not found. Adding..."); val = ScriptableObject.CreateInstance<Recipe>(); if (ConfigFishingRecipe(ref val, customRecipe, recipe)) { ObjectDB.instance.m_recipes.Add(val); } else { mLog.Error("Failed to add recipe " + customRecipe.RecipeName); } } else { mLog.Debug(customRecipe.RecipeName + " recipe already exists"); } } } public static bool ConfigFishingRecipe(ref Recipe recipe, ICustomRecipe customRecipe, RecipeDo rdo) { //IL_0212: Unknown result type (might be due to invalid IL or missing references) //IL_0218: Expected O, but got Unknown GameObject prefab = ZNetScene.instance.GetPrefab(rdo.CraftingStation); if ((Object)(object)prefab == (Object)null) { mLog.Error("Crafting station " + rdo.CraftingStation + " prefab is missing"); return false; } CraftingStation val = default(CraftingStation); if (!prefab.TryGetComponent<CraftingStation>(ref val)) { mLog.Error("Crafting station component " + rdo.CraftingStation + " is missing"); return false; } GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(customRecipe.Prefab); if ((Object)(object)itemPrefab == (Object)null) { mLog.Error("Item " + customRecipe.Prefab + " prefab is missing"); return false; } ItemDrop val2 = default(ItemDrop); if (!itemPrefab.TryGetComponent<ItemDrop>(ref val2)) { mLog.Error("ItemDrop " + customRecipe.Prefab + " component is missing"); return false; } List<RequirementDo> requirements = rdo.Requirements; Requirement[] array = (Requirement[])(object)new Requirement[requirements.Count]; ItemDrop val3 = default(ItemDrop); for (int i = 0; i < requirements.Count; i++) { mLog.Debug("Getting requirement " + requirements[i].Item); GameObject itemPrefab2 = ObjectDB.instance.GetItemPrefab(requirements[i].Item); if ((Object)(object)itemPrefab2 == (Object)null) { mLog.Error("Requirement " + requirements[i].Item + " prefab is missing"); return false; } if (!itemPrefab2.TryGetComponent<ItemDrop>(ref val3)) { mLog.Error("ItemDrop " + requirements[i].Item + " component is missing"); return false; } mLog.Debug($"Requirement item {i} {val3.m_itemData.m_shared.m_name}"); array[i] = new Requirement(); array[i].m_amount = requirements[i].Amount; array[i].m_recover = customRecipe.RecoverPieces; array[i].m_amountPerLevel = requirements[i].AmountPerLevel; array[i].m_resItem = val3; mLog.Debug($"Amount {array[i].m_amount}"); mLog.Debug($"Amount per level {array[i].m_amountPerLevel}"); mLog.Debug($"Recover {array[i].m_recover}"); } val2.m_itemData.m_shared.m_canBeReparied = customRecipe.CanBeRepaired; val2.m_itemData.m_shared.m_maxQuality = customRecipe.MaxQuality; val2.m_itemData.m_shared.m_maxDurability = customRecipe.MaxDurability; val2.m_itemData.m_shared.m_useDurability = customRecipe.UseDurability; recipe.m_craftingStation = val; recipe.m_repairStation = (customRecipe.CanBeRepaired ? val : null); recipe.m_amount = rdo.Amount; recipe.m_enabled = rdo.Enabled; recipe.m_minStationLevel = rdo.MinStationLevel; recipe.m_item = val2; recipe.m_resources = array; ((Object)recipe).name = customRecipe.RecipeName; return true; } } internal interface IMod { } [BepInPlugin("neobotics.valheim_mod.reelyspectacklelure", "ReelySpecTackleLure", "0.2.4")] [BepInProcess("valheim.exe")] [BepInProcess("valheim_server.exe")] public class ReelySpecTackleLure : BaseUnityPlugin { [HarmonyPatch(typeof(Skills), "GetSkillFactor")] private static class Skills_GetSkillFactor_Patch { private static bool Prefix(Skills __instance, SkillType skillType, Player ___m_player, ref float __result) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0004: Invalid comparison between Unknown and I4 //IL_0023: Unknown result type (might be due to invalid IL or missing references) if ((int)skillType != 104 || !useRodBonus.Value) { return true; } float skillLevel = __instance.GetSkillLevel(skillType); ItemData value = Traverse.Create((object)___m_player).Field("m_rightItem").GetValue<ItemData>(); if (value == null) { return true; } float num = (float)(value.m_quality - 1) * 5f; __result = Mathf.Clamp01((skillLevel + num) / 100f); if (Log.LogLevel >= 5) { Log.Trace($"Fishing Skill with Rod Bonus {__result}"); } return false; } } [HarmonyPatch(typeof(FejdStartup), "SetupObjectDB")] private class FejdStartup_SetupObjectDB_Patch { [HarmonyPriority(100)] private static void Postfix(FejdStartup __instance, GameObject ___m_objectDBPrefab) { Log.Debug("FejdStartup SetupObjectDB postfix"); GameObject itemPrefab = ObjectDB.instance.GetItemPrefab("FishingRod"); AdjustFishingRod((itemPrefab == null) ? null : itemPrefab.GetComponent<ItemDrop>()?.m_itemData); } } [HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData) })] private static class Inventory_AddItem_Patch { private static void Postfix(Inventory __instance, ItemData item) { if (item.m_shared.m_name.Equals("$item_fishingrod")) { Log.Debug($"Adding fishing rod of quality {item.m_quality}"); } } } [HarmonyPatch(typeof(Fish), "TestBate")] private static class Fish_TestBate_Patch { [HarmonyPostfix] private static void Fish_TestBate_Postfix(Fish __instance, FishingFloat ff, ref bool __result) { if (!__result && genericBaitChance.Value > 0) { string bait = ff.GetBait(); Log.Debug("Fish testing " + bait); if (bait == "FishingBait" && Random.value < (float)genericBaitChance.Value / 100f) { Log.Debug("Nibbling regular bait"); __result = true; } else { Log.Debug("Ignoring regular bait"); } } } } [HarmonyPatch(typeof(FishingFloat), "Setup")] private static class FishingFloat_Setup_Patch { private static void Postfix(ref FishingFloat __instance) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) Log.Debug("FishingFloat Setup Postfix"); Transform transform = ((Component)__instance).gameObject.transform; transform.localScale *= (float)(floatSize.Value + 1) / 2f; Cast(((Component)__instance).transform.position); } } [HarmonyPatch(typeof(SpawnSystem), "IsSpawnPointGood")] private static class SpawnSystem_SpawnPoint_Patch { private static void Prefix(SpawnData spawn, ref Vector3 spawnPoint) { testingFishSpawnLocation = false; if (spawn != null && noBaseRestriction.Value && spawn.m_name.ToLower().Contains("fish")) { Log.Debug("Detected fish spawner"); testingFishSpawnLocation = true; } } private static void Postfix(bool __result, SpawnData spawn, ref Vector3 spawnPoint) { if (testingFishSpawnLocation) { testingFishSpawnLocation = false; } } } [HarmonyPatch(typeof(EffectArea), "IsPointInsideArea")] private static class EffectArea_PointInside_Patch { private static void Postfix(ref EffectArea __result, Vector3 p, Type type, float radius) { if (testingFishSpawnLocation && (Object)(object)__result != (Object)null) { Log.Info("Overriding fish spawner base restriction"); __result = null; } } } [HarmonyPatch(typeof(PlayerProfile), "LoadPlayerData")] private class PlayerProfile_LoadPlayerData_Patch { private static void Postfix(PlayerProfile __instance, Player player) { Log.Debug("PlayerProfile_LoadPlayerData_Patch"); if ((Object)(object)player == (Object)(object)Player.m_localPlayer && craftableTackle.Value) { RecipieMaker.InitFishingRecipes(rstlRecipes); SetRawFishStation(); } } } private static ReelySpecTackleLure _modinstance; public static Logging Log; private static string Mod = "ReelySpecTackleLure"; private static string lMod = Mod.ToLower(); private static string abbrMod = "RSTL"; private readonly Harmony harmony = new Harmony("neobotics.valheim_mod." + lMod); private static Random rand = new Random(); private static float castSpawnDelaySeconds = 10f; private static int serpentSpawnChanceNight = 15; private static int serpentSpawnChanceDay = 25; private static int leviathanSpawnChance = 100; private static CraftingStation rawFishStation = null; public static ConfigEntry<int> floatSize = null; public static DelegatedConfigEntry<bool> useRodBonus = null; public static DelegatedConfigEntry<bool> noBaseRestriction = null; public static DelegatedConfigEntry<int> debugLevel = null; public static DelegatedConfigEntry<bool> enableSerpentSpawn = null; public static DelegatedConfigEntry<bool> enableLeviathanSpawn = null; public static DelegatedConfigEntry<bool> craftableTackle = null; public static DelegatedConfigEntry<int> genericBaitChance = null; public static DelegatedConfigEntry<bool> noCauldronRawFish = null; public static GameObject serpentPrefab = null; public static GameObject leviathanPrefab = null; public const string rodPrefabName = "FishingRod"; public const string rodItemName = "$item_fishingrod"; private const string rodDescription = "A craftable fishing rod."; private static bool canSpawn = true; public static bool testingFishSpawnLocation = false; public static Recipes rstlRecipes = null; public static ReelySpecTackleLure GetInstance() { return _modinstance; } private void Awake() { _modinstance = this; ConfigureMod(); harmony.PatchAll(Assembly.GetExecutingAssembly()); Log.Info("Awake"); } private void ConfigureMod() { //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Expected O, but got Unknown //IL_01df: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Expected O, but got Unknown Log = Logging.GetLogger(3, Mod); ServerConfiguration.Instance.Setup(((BaseUnityPlugin)this).Config, (BaseUnityPlugin)(object)this); debugLevel = new DelegatedConfigEntry<int>(ChangeLog); debugLevel.ConfigEntry = ((BaseUnityPlugin)this).Config.Bind<int>("Utility", "LogLevel", 3, new ConfigDescription("Controls the level of information contained in the log", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 5), Array.Empty<object>())); Log.LogLevel = debugLevel.Value; useRodBonus = new DelegatedConfigEntry<bool>(useServerDelegate: true); useRodBonus.ConfigEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "UseRodBonus", true, "Allows upgraded fishing rods to add to the fishing skill. Default=true"); floatSize = ((BaseUnityPlugin)this).Config.Bind<int>("General", "FloatSize", 1, new ConfigDescription("The size of the float. Increase to make the float larger and more visible in the water. Default is 1 (the standard Valheim float size)", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 3), Array.Empty<object>())); noBaseRestriction = new DelegatedConfigEntry<bool>(useServerDelegate: true); noBaseRestriction.ConfigEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "NoBaseRestrictedSpawn", false, "Set True to enable fish to spawn near Player base structures such as workbenches and campfires. Set False for Valheim's normal restriction."); enableSerpentSpawn = new DelegatedConfigEntry<bool>(useServerDelegate: true); enableSerpentSpawn.ConfigEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "EnableSerpentSpawn", true, "Set True to enable occasional serpent spawning when fishing in the Ocean."); enableLeviathanSpawn = new DelegatedConfigEntry<bool>(useServerDelegate: true); enableLeviathanSpawn.ConfigEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "EnableLeviathanSpawn", true, "Set True to enable rare Leviathan spawning when fishing in the Ocean."); craftableTackle = new DelegatedConfigEntry<bool>(useServerDelegate: true); craftableTackle.ConfigEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "EnableCraftableTackle", true, "Set True to enable crafting and upgrading (adds to fishing skill) of fishing rods, and craftable bait."); genericBaitChance = new DelegatedConfigEntry<int>(useServerDelegate: true); genericBaitChance.ConfigEntry = ((BaseUnityPlugin)this).Config.Bind<int>("General", "RegularBaitHookChance", 0, new ConfigDescription("Provides a percent chance for basic fishing bait to hook any fish regardless of bait preference. Default is 0. 100 would provide the same chance as the biome-specific bait.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())); noCauldronRawFish = new DelegatedConfigEntry<bool>(ChangeRawFish, useServerDelegate: true); noCauldronRawFish.ConfigEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "SkinFishInField", false, "Set True to allow skinning and cleaning fish in the field without a cauldron. Appears in the non-station crafting menu."); rstlRecipes = RecipeReader.ReadRecipes(); ServerConfiguration.Instance.CreateConfigWatcher(); } private static void ChangeLog(object s, EventArgs e) { SettingChangedEventArgs val = (SettingChangedEventArgs)(object)((e is SettingChangedEventArgs) ? e : null); Log.Debug($"ChangeLog {val.ChangedSetting.Definition.Key} to {val.ChangedSetting.BoxedValue}"); Log.LogLevel = debugLevel.Value; } private static void ChangeRawFish(object s, EventArgs e) { SettingChangedEventArgs val = (SettingChangedEventArgs)(object)((e is SettingChangedEventArgs) ? e : null); Log.Debug($"ChangeRawFish {val.ChangedSetting.Definition.Key} to {val.ChangedSetting.BoxedValue}"); SetRawFishStation(); } private static void SetRawFishStation() { Recipe val = ObjectDB.instance.m_recipes.Find((Recipe x) => ((Object)x).name.Equals("Recipe_Fish1")); if ((Object)(object)val != (Object)null) { if ((Object)(object)rawFishStation == (Object)null) { rawFishStation = val.m_craftingStation; } val.m_craftingStation = (noCauldronRawFish.Value ? null : rawFishStation); Player.m_localPlayer.UpdateKnownRecipesList(); } } private void OnDestroy() { harmony.UnpatchAll(harmony.Id); } private static void Cast(Vector3 position) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Invalid comparison between Unknown and I4 //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) Log.Debug("Cast"); Player localPlayer = Player.m_localPlayer; if ((int)localPlayer.GetCurrentBiome() == 256) { Log.Debug($"Can spawn {canSpawn}"); if ((Object)(object)serpentPrefab == (Object)null) { serpentPrefab = ZNetScene.instance.GetPrefab("Serpent"); } if ((Object)(object)leviathanPrefab == (Object)null) { leviathanPrefab = ZNetScene.instance.GetPrefab("Leviathan"); } int playersInRangeXZ = Player.GetPlayersInRangeXZ(((Component)Player.m_localPlayer).transform.position, 100f); Log.Debug($"Players within range: {playersInRangeXZ}"); if (canSpawn && (Object)(object)serpentPrefab != (Object)null && enableSerpentSpawn.Value) { if (rand.Next(EnvMan.IsNight() ? (serpentSpawnChanceNight * playersInRangeXZ) : (serpentSpawnChanceDay * playersInRangeXZ)) == 0) { ((MonoBehaviour)_modinstance).StartCoroutine(_modinstance.Co_DeepSeaSpawn(position, serpentPrefab, 3f)); } } else if (canSpawn && (Object)(object)leviathanPrefab != (Object)null && enableLeviathanSpawn.Value && rand.Next(leviathanSpawnChance * playersInRangeXZ) == 0) { ((MonoBehaviour)_modinstance).StartCoroutine(_modinstance.Co_DeepSeaSpawn(position, leviathanPrefab, 10f)); } } if (canSpawn) { ((MonoBehaviour)_modinstance).StartCoroutine(_modinstance.Co_SpawnThrottle()); } } private IEnumerator Co_SpawnThrottle() { Log.Trace("Co_SpawnThrottle"); canSpawn = false; Log.Trace($"Spawn {canSpawn} {DateTime.Now}"); yield return (object)new WaitForSeconds(castSpawnDelaySeconds); canSpawn = true; Log.Trace($"Spawn {canSpawn} {DateTime.Now}"); } private IEnumerator Co_DeepSeaSpawn(Vector3 position, GameObject prefab, float depth) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) Log.Trace("Co_DeepSeaSpawn"); yield return (object)new WaitForSeconds((float)rand.NextDouble() * 5f + 3f); float bedDepth = Utils.GetPointDepth(position); if (!(bedDepth > 12f)) { yield break; } Vector3 submerged = position + new Vector3(0f, 0f - depth, 0f); GameObject serpent = Object.Instantiate<GameObject>(prefab, submerged, Quaternion.identity); Character c = default(Character); if (serpent.TryGetComponent<Character>(ref c) && rand.Next(EnvMan.IsNight() ? 5 : 10) == 0) { if (rand.Next(EnvMan.IsNight() ? 5 : 10) == 0) { c.SetLevel(3); Transform transform = ((Component)c).transform; transform.localScale *= 1.5f; } else { c.SetLevel(2); Transform transform2 = ((Component)c).transform; transform2.localScale *= 1.25f; } } } private static void AdjustFishingRod(ItemData item) { if (item == null) { Log.Error("Fishing Rod item not found"); return; } item.m_shared.m_canBeReparied = true; item.m_shared.m_useDurability = true; item.m_shared.m_maxQuality = 4; item.m_shared.m_description = "A craftable fishing rod"; Log.Debug("Adjusted Fishing Rod to be craftable and upgradeable."); } } [Serializable] public class RequirementDo { public string Item { get; set; } public int Amount { get; set; } public int AmountPerLevel { get; set; } public RequirementDo(string i, int a, int apl) { Item = i; Amount = a; AmountPerLevel = apl; } } [Serializable] public class RecipeDo { public string Name { get; set; } public int Amount { get; set; } public bool Enabled { get; set; } public string CraftingStation { get; set; } public int MinStationLevel { get; set; } public List<RequirementDo> Requirements { get; set; } }
System.Data.dll
Decompiled 6 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Configuration; using System.Data; using System.Data.Common; using System.Data.Odbc; using System.Data.OleDb; using System.Data.ProviderBase; using System.Data.Sql; using System.Data.SqlClient; using System.Data.SqlClient.SNI; using System.Data.SqlTypes; using System.Diagnostics; using System.Diagnostics.Tracing; using System.Dynamic; using System.EnterpriseServices; using System.Globalization; using System.IO; using System.IO.Pipes; using System.Linq; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Numerics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Security; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Security.Principal; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Transactions; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Xml.Serialization.Advanced; using System.Xml.XPath; using Microsoft.SqlServer.Server; using Microsoft.Win32.SafeHandles; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: SecurityTransparent] [assembly: AssemblyTitle("System.Data.dll")] [assembly: AssemblyDescription("System.Data.dll")] [assembly: AssemblyDefaultAlias("System.Data.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.6.57.0")] [assembly: CLSCompliant(true)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: ComVisible(false)] [assembly: AllowPartiallyTrustedCallers] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyFileVersion("4.6.57.0")] [assembly: InternalsVisibleTo("System.Design, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: InternalsVisibleTo("System.Web, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.0.0")] [module: UnverifiableCode] internal static class Interop { private static class Libraries { internal const string SystemNative = "System.Native"; internal const string HttpNative = "System.Net.Http.Native"; internal const string NetSecurityNative = "System.Net.Security.Native"; internal const string CryptoNative = "System.Security.Cryptography.Native.OpenSsl"; internal const string GlobalizationNative = "System.Globalization.Native"; internal const string CompressionNative = "System.IO.Compression.Native"; internal const string Libdl = "libdl"; } internal static class NetSecurityNative { internal sealed class GssApiException : Exception { private readonly Status _minorStatus; public Status MinorStatus => _minorStatus; public GssApiException(string message) : base(message) { } public GssApiException(Status majorStatus, Status minorStatus) : base(GetGssApiDisplayStatus(majorStatus, minorStatus)) { base.HResult = (int)majorStatus; _minorStatus = minorStatus; } private static string GetGssApiDisplayStatus(Status majorStatus, Status minorStatus) { string gssApiDisplayStatus = GetGssApiDisplayStatus(majorStatus, isMinor: false); string gssApiDisplayStatus2 = GetGssApiDisplayStatus(minorStatus, isMinor: true); if (gssApiDisplayStatus == null || gssApiDisplayStatus2 == null) { return SR.Format("GSSAPI operation failed with status: {0} (Minor status: {1}).", majorStatus.ToString("x"), minorStatus.ToString("x")); } return SR.Format("GSSAPI operation failed with error - {0} ({1}).", gssApiDisplayStatus, gssApiDisplayStatus2); } private static string GetGssApiDisplayStatus(Status status, bool isMinor) { GssBuffer buffer = default(GssBuffer); try { Status minorStatus; return ((isMinor ? DisplayMinorStatus(out minorStatus, status, ref buffer) : DisplayMajorStatus(out minorStatus, status, ref buffer)) != 0) ? null : Marshal.PtrToStringAnsi(buffer._data); } finally { buffer.Dispose(); } } } internal struct GssBuffer : IDisposable { internal ulong _length; internal IntPtr _data; internal int Copy(byte[] destination, int offset) { if (_data == IntPtr.Zero || _length == 0L) { return 0; } int num = Convert.ToInt32(_length); int num2 = destination.Length - offset; if (num > num2) { throw new GssApiException(SR.Format("Insufficient buffer space. Required: {0} Actual: {1}.", num, num2)); } Marshal.Copy(_data, destination, offset, num); return num; } internal byte[] ToByteArray() { if (_data == IntPtr.Zero || _length == 0L) { return Array.Empty<byte>(); } int num = Convert.ToInt32(_length); byte[] array = new byte[num]; Marshal.Copy(_data, array, 0, num); return array; } public void Dispose() { if (_data != IntPtr.Zero) { ReleaseGssBuffer(_data, _length); _data = IntPtr.Zero; } _length = 0uL; } } internal enum Status : uint { GSS_S_COMPLETE, GSS_S_CONTINUE_NEEDED } [Flags] internal enum GssFlags : uint { GSS_C_DELEG_FLAG = 1u, GSS_C_MUTUAL_FLAG = 2u, GSS_C_REPLAY_FLAG = 4u, GSS_C_SEQUENCE_FLAG = 8u, GSS_C_CONF_FLAG = 0x10u, GSS_C_INTEG_FLAG = 0x20u, GSS_C_ANON_FLAG = 0x40u, GSS_C_PROT_READY_FLAG = 0x80u, GSS_C_TRANS_FLAG = 0x100u, GSS_C_DCE_STYLE = 0x1000u, GSS_C_IDENTIFY_FLAG = 0x2000u, GSS_C_EXTENDED_ERROR_FLAG = 0x4000u, GSS_C_DELEG_POLICY_FLAG = 0x8000u } [DllImport("System.Net.Security.Native", EntryPoint = "NetSecurityNative_ReleaseGssBuffer")] internal static extern void ReleaseGssBuffer(IntPtr bufferPtr, ulong length); [DllImport("System.Net.Security.Native", EntryPoint = "NetSecurityNative_DisplayMinorStatus")] internal static extern Status DisplayMinorStatus(out Status minorStatus, Status statusValue, ref GssBuffer buffer); [DllImport("System.Net.Security.Native", EntryPoint = "NetSecurityNative_DisplayMajorStatus")] internal static extern Status DisplayMajorStatus(out Status minorStatus, Status statusValue, ref GssBuffer buffer); [DllImport("System.Net.Security.Native", EntryPoint = "NetSecurityNative_ImportUserName")] internal static extern Status ImportUserName(out Status minorStatus, string inputName, int inputNameByteCount, out Microsoft.Win32.SafeHandles.SafeGssNameHandle outputName); [DllImport("System.Net.Security.Native", EntryPoint = "NetSecurityNative_ImportPrincipalName")] internal static extern Status ImportPrincipalName(out Status minorStatus, string inputName, int inputNameByteCount, out Microsoft.Win32.SafeHandles.SafeGssNameHandle outputName); [DllImport("System.Net.Security.Native", EntryPoint = "NetSecurityNative_ReleaseName")] internal static extern Status ReleaseName(out Status minorStatus, ref IntPtr inputName); [DllImport("System.Net.Security.Native", EntryPoint = "NetSecurityNative_InitiateCredSpNego")] internal static extern Status InitiateCredSpNego(out Status minorStatus, Microsoft.Win32.SafeHandles.SafeGssNameHandle desiredName, out Microsoft.Win32.SafeHandles.SafeGssCredHandle outputCredHandle); [DllImport("System.Net.Security.Native", EntryPoint = "NetSecurityNative_InitiateCredWithPassword")] internal static extern Status InitiateCredWithPassword(out Status minorStatus, bool isNtlm, Microsoft.Win32.SafeHandles.SafeGssNameHandle desiredName, string password, int passwordLen, out Microsoft.Win32.SafeHandles.SafeGssCredHandle outputCredHandle); [DllImport("System.Net.Security.Native", EntryPoint = "NetSecurityNative_ReleaseCred")] internal static extern Status ReleaseCred(out Status minorStatus, ref IntPtr credHandle); [DllImport("System.Net.Security.Native", EntryPoint = "NetSecurityNative_InitSecContext")] internal static extern Status InitSecContext(out Status minorStatus, Microsoft.Win32.SafeHandles.SafeGssCredHandle initiatorCredHandle, ref Microsoft.Win32.SafeHandles.SafeGssContextHandle contextHandle, bool isNtlmOnly, Microsoft.Win32.SafeHandles.SafeGssNameHandle targetName, uint reqFlags, byte[] inputBytes, int inputLength, ref GssBuffer token, out uint retFlags, out int isNtlmUsed); [DllImport("System.Net.Security.Native", EntryPoint = "NetSecurityNative_AcceptSecContext")] internal static extern Status AcceptSecContext(out Status minorStatus, ref Microsoft.Win32.SafeHandles.SafeGssContextHandle acceptContextHandle, byte[] inputBytes, int inputLength, ref GssBuffer token); [DllImport("System.Net.Security.Native", EntryPoint = "NetSecurityNative_DeleteSecContext")] internal static extern Status DeleteSecContext(out Status minorStatus, ref IntPtr contextHandle); [DllImport("System.Net.Security.Native", EntryPoint = "NetSecurityNative_Wrap")] private static extern Status Wrap(out Status minorStatus, Microsoft.Win32.SafeHandles.SafeGssContextHandle contextHandle, bool isEncrypt, byte[] inputBytes, int offset, int count, ref GssBuffer outBuffer); [DllImport("System.Net.Security.Native", EntryPoint = "NetSecurityNative_Unwrap")] private static extern Status Unwrap(out Status minorStatus, Microsoft.Win32.SafeHandles.SafeGssContextHandle contextHandle, byte[] inputBytes, int offset, int count, ref GssBuffer outBuffer); internal static Status WrapBuffer(out Status minorStatus, Microsoft.Win32.SafeHandles.SafeGssContextHandle contextHandle, bool isEncrypt, byte[] inputBytes, int offset, int count, ref GssBuffer outBuffer) { return Wrap(out minorStatus, contextHandle, isEncrypt, inputBytes, offset, count, ref outBuffer); } internal static Status UnwrapBuffer(out Status minorStatus, Microsoft.Win32.SafeHandles.SafeGssContextHandle contextHandle, byte[] inputBytes, int offset, int count, ref GssBuffer outBuffer) { return Unwrap(out minorStatus, contextHandle, inputBytes, offset, count, ref outBuffer); } } } internal class SqlDependencyProcessDispatcher : MarshalByRefObject { private class SqlConnectionContainer { private SqlConnection _con; private SqlCommand _com; private SqlParameter _conversationGuidParam; private SqlParameter _timeoutParam; private SqlConnectionContainerHashHelper _hashHelper; private string _queue; private string _receiveQuery; private string _beginConversationQuery; private string _endConversationQuery; private string _concatQuery; private readonly int _defaultWaitforTimeout = 60000; private string _escapedQueueName; private string _sprocName; private string _dialogHandle; private string _cachedServer; private string _cachedDatabase; private volatile bool _errorState; private volatile bool _stop; private volatile bool _stopped; private volatile bool _serviceQueueCreated; private int _startCount; private Timer _retryTimer; private Dictionary<string, int> _appDomainKeyHash; internal string Database { get { if (_cachedDatabase == null) { _cachedDatabase = _con.Database; } return _cachedDatabase; } } internal SqlConnectionContainerHashHelper HashHelper => _hashHelper; internal bool InErrorState => _errorState; internal string Queue => _queue; internal string Server => _cachedServer; internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults) { bool flag = false; try { _hashHelper = hashHelper; string text = null; if (useDefaults) { text = Guid.NewGuid().ToString(); _queue = "SqlQueryNotificationService-" + text; _hashHelper.ConnectionStringBuilder.ApplicationName = _queue; } else { _queue = _hashHelper.Queue; } _con = new SqlConnection(_hashHelper.ConnectionStringBuilder.ConnectionString); _ = (SqlConnectionString)_con.ConnectionOptions; _con.Open(); _cachedServer = _con.DataSource; _escapedQueueName = SqlConnection.FixupDatabaseTransactionName(_queue); _appDomainKeyHash = new Dictionary<string, int>(); _com = new SqlCommand { Connection = _con, CommandText = "select is_broker_enabled from sys.databases where database_id=db_id()" }; if (!(bool)_com.ExecuteScalar()) { throw SQL.SqlDependencyDatabaseBrokerDisabled(); } _conversationGuidParam = new SqlParameter("@p1", SqlDbType.UniqueIdentifier); _timeoutParam = new SqlParameter("@p2", SqlDbType.Int) { Value = 0 }; _com.Parameters.Add(_timeoutParam); flag = true; _receiveQuery = "WAITFOR(RECEIVE TOP (1) message_type_name, conversation_handle, cast(message_body AS XML) as message_body from " + _escapedQueueName + "), TIMEOUT @p2;"; if (useDefaults) { _sprocName = SqlConnection.FixupDatabaseTransactionName("SqlQueryNotificationStoredProcedure-" + text); CreateQueueAndService(restart: false); } else { _com.CommandText = _receiveQuery; _endConversationQuery = "END CONVERSATION @p1; "; _concatQuery = _endConversationQuery + _receiveQuery; } IncrementStartCount(appDomainKey, out var _); SynchronouslyQueryServiceBrokerQueue(); _timeoutParam.Value = _defaultWaitforTimeout; AsynchronouslyQueryServiceBrokerQueue(); } catch (Exception e) { if (!ADP.IsCatchableExceptionType(e)) { throw; } ADP.TraceExceptionWithoutRethrow(e); if (flag) { TearDownAndDispose(); } else { if (_com != null) { _com.Dispose(); _com = null; } if (_con != null) { _con.Dispose(); _con = null; } } throw; } } internal bool AppDomainUnload(string appDomainKey) { lock (_appDomainKeyHash) { if (_appDomainKeyHash.ContainsKey(appDomainKey)) { int num = _appDomainKeyHash[appDomainKey]; bool appDomainStop = false; while (num > 0) { Stop(appDomainKey, out appDomainStop); num--; } } } return _stopped; } private void AsynchronouslyQueryServiceBrokerQueue() { AsyncCallback callback = AsyncResultCallback; _com.BeginExecuteReader(CommandBehavior.Default, callback, null); } private void AsyncResultCallback(IAsyncResult asyncResult) { try { using (SqlDataReader reader = _com.EndExecuteReader(asyncResult)) { ProcessNotificationResults(reader); } if (!_stop) { AsynchronouslyQueryServiceBrokerQueue(); } else { TearDownAndDispose(); } } catch (Exception e) { if (!ADP.IsCatchableExceptionType(e)) { _errorState = true; throw; } if (!_stop) { ADP.TraceExceptionWithoutRethrow(e); } if (_stop) { TearDownAndDispose(); return; } _errorState = true; Restart(null); } } private void CreateQueueAndService(bool restart) { SqlCommand sqlCommand = new SqlCommand { Connection = _con }; SqlTransaction sqlTransaction = null; try { sqlTransaction = (sqlCommand.Transaction = _con.BeginTransaction()); string text = SqlServerEscapeHelper.MakeStringLiteral(_queue); sqlCommand.CommandText = "CREATE PROCEDURE " + _sprocName + " AS BEGIN BEGIN TRANSACTION; RECEIVE TOP(0) conversation_handle FROM " + _escapedQueueName + "; IF (SELECT COUNT(*) FROM " + _escapedQueueName + " WHERE message_type_name = 'http://schemas.microsoft.com/SQL/ServiceBroker/DialogTimer') > 0 BEGIN if ((SELECT COUNT(*) FROM sys.services WHERE name = " + text + ") > 0) DROP SERVICE " + _escapedQueueName + "; if (OBJECT_ID(" + text + ", 'SQ') IS NOT NULL) DROP QUEUE " + _escapedQueueName + "; DROP PROCEDURE " + _sprocName + "; END COMMIT TRANSACTION; END"; if (!restart) { sqlCommand.ExecuteNonQuery(); } else { try { sqlCommand.ExecuteNonQuery(); } catch (Exception e) { if (!ADP.IsCatchableExceptionType(e)) { throw; } ADP.TraceExceptionWithoutRethrow(e); try { if (sqlTransaction != null) { sqlTransaction.Rollback(); sqlTransaction = null; } } catch (Exception e2) { if (!ADP.IsCatchableExceptionType(e2)) { throw; } ADP.TraceExceptionWithoutRethrow(e2); } } if (sqlTransaction == null) { sqlTransaction = (sqlCommand.Transaction = _con.BeginTransaction()); } } sqlCommand.CommandText = "IF OBJECT_ID(" + text + ", 'SQ') IS NULL BEGIN CREATE QUEUE " + _escapedQueueName + " WITH ACTIVATION (PROCEDURE_NAME=" + _sprocName + ", MAX_QUEUE_READERS=1, EXECUTE AS OWNER); END; IF (SELECT COUNT(*) FROM sys.services WHERE NAME=" + text + ") = 0 BEGIN CREATE SERVICE " + _escapedQueueName + " ON QUEUE " + _escapedQueueName + " ([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]); IF (SELECT COUNT(*) FROM sys.database_principals WHERE name='sql_dependency_subscriber' AND type='R') <> 0 BEGIN GRANT SEND ON SERVICE::" + _escapedQueueName + " TO sql_dependency_subscriber; END; END; BEGIN DIALOG @dialog_handle FROM SERVICE " + _escapedQueueName + " TO SERVICE " + text; SqlParameter sqlParameter = new SqlParameter { ParameterName = "@dialog_handle", DbType = DbType.Guid, Direction = ParameterDirection.Output }; sqlCommand.Parameters.Add(sqlParameter); sqlCommand.ExecuteNonQuery(); _dialogHandle = ((Guid)sqlParameter.Value).ToString(); _beginConversationQuery = "BEGIN CONVERSATION TIMER ('" + _dialogHandle + "') TIMEOUT = 120; " + _receiveQuery; _com.CommandText = _beginConversationQuery; _endConversationQuery = "END CONVERSATION @p1; "; _concatQuery = _endConversationQuery + _com.CommandText; sqlTransaction.Commit(); sqlTransaction = null; _serviceQueueCreated = true; } finally { if (sqlTransaction != null) { try { sqlTransaction.Rollback(); sqlTransaction = null; } catch (Exception e3) { if (!ADP.IsCatchableExceptionType(e3)) { throw; } ADP.TraceExceptionWithoutRethrow(e3); } } } } internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) { appDomainStart = false; Interlocked.Increment(ref _startCount); lock (_appDomainKeyHash) { if (_appDomainKeyHash.ContainsKey(appDomainKey)) { _appDomainKeyHash[appDomainKey] += 1; return; } _appDomainKeyHash[appDomainKey] = 1; appDomainStart = true; } } private void ProcessNotificationResults(SqlDataReader reader) { Guid guid = Guid.Empty; try { if (_stop) { return; } while (reader.Read()) { string @string = reader.GetString(0); guid = reader.GetGuid(1); if (string.Compare(@string, "http://schemas.microsoft.com/SQL/Notifications/QueryNotification", StringComparison.OrdinalIgnoreCase) == 0) { SqlXml sqlXml = reader.GetSqlXml(2); if (sqlXml == null) { continue; } SqlNotification sqlNotification = SqlNotificationParser.ProcessMessage(sqlXml); if (sqlNotification == null) { continue; } string key = sqlNotification.Key; int num = key.IndexOf(';'); if (num < 0) { continue; } string key2 = key.Substring(0, num); SqlDependencyPerAppDomainDispatcher sqlDependencyPerAppDomainDispatcher; lock (s_staticInstance._sqlDependencyPerAppDomainDispatchers) { sqlDependencyPerAppDomainDispatcher = s_staticInstance._sqlDependencyPerAppDomainDispatchers[key2]; } if (sqlDependencyPerAppDomainDispatcher == null) { continue; } try { sqlDependencyPerAppDomainDispatcher.InvalidateCommandID(sqlNotification); } catch (Exception e) { if (!ADP.IsCatchableExceptionType(e)) { throw; } ADP.TraceExceptionWithoutRethrow(e); } } else { guid = Guid.Empty; } } } finally { if (guid == Guid.Empty) { _com.CommandText = _beginConversationQuery ?? _receiveQuery; if (_com.Parameters.Count > 1) { _com.Parameters.Remove(_conversationGuidParam); } } else { _com.CommandText = _concatQuery; _conversationGuidParam.Value = guid; if (_com.Parameters.Count == 1) { _com.Parameters.Add(_conversationGuidParam); } } } } private void Restart(object unused) { try { lock (this) { if (!_stop) { try { _con.Close(); } catch (Exception e) { if (!ADP.IsCatchableExceptionType(e)) { throw; } ADP.TraceExceptionWithoutRethrow(e); } } } lock (this) { if (!_stop) { _con.Open(); } } lock (this) { if (!_stop && _serviceQueueCreated) { bool flag = false; try { CreateQueueAndService(restart: true); } catch (Exception e2) { if (!ADP.IsCatchableExceptionType(e2)) { throw; } ADP.TraceExceptionWithoutRethrow(e2); flag = true; } if (flag) { s_staticInstance.Invalidate(Server, new SqlNotification(SqlNotificationInfo.Error, SqlNotificationSource.Client, SqlNotificationType.Change, null)); } } } lock (this) { if (!_stop) { _timeoutParam.Value = 0; SynchronouslyQueryServiceBrokerQueue(); _timeoutParam.Value = _defaultWaitforTimeout; AsynchronouslyQueryServiceBrokerQueue(); _errorState = false; _retryTimer = null; } } if (_stop) { TearDownAndDispose(); } } catch (Exception e3) { if (!ADP.IsCatchableExceptionType(e3)) { throw; } ADP.TraceExceptionWithoutRethrow(e3); try { s_staticInstance.Invalidate(Server, new SqlNotification(SqlNotificationInfo.Error, SqlNotificationSource.Client, SqlNotificationType.Change, null)); } catch (Exception e4) { if (!ADP.IsCatchableExceptionType(e4)) { throw; } ADP.TraceExceptionWithoutRethrow(e4); } try { _con.Close(); } catch (Exception e5) { if (!ADP.IsCatchableExceptionType(e5)) { throw; } ADP.TraceExceptionWithoutRethrow(e5); } if (!_stop) { _retryTimer = new Timer(Restart, null, _defaultWaitforTimeout, -1); } } } internal bool Stop(string appDomainKey, out bool appDomainStop) { appDomainStop = false; if (appDomainKey != null) { lock (_appDomainKeyHash) { if (_appDomainKeyHash.ContainsKey(appDomainKey)) { int num = _appDomainKeyHash[appDomainKey]; if (num > 0) { _appDomainKeyHash[appDomainKey] = num - 1; } if (1 == num) { _appDomainKeyHash.Remove(appDomainKey); appDomainStop = true; } } } } if (Interlocked.Decrement(ref _startCount) == 0) { lock (this) { try { _com.Cancel(); } catch (Exception e) { if (!ADP.IsCatchableExceptionType(e)) { throw; } ADP.TraceExceptionWithoutRethrow(e); } _stop = true; } Stopwatch stopwatch = Stopwatch.StartNew(); while (true) { lock (this) { if (!_stopped) { if (!_errorState && stopwatch.Elapsed.Seconds < 30) { goto IL_0127; } Timer retryTimer = _retryTimer; _retryTimer = null; retryTimer?.Dispose(); TearDownAndDispose(); } } break; IL_0127: Thread.Sleep(1); } } return _stopped; } private void SynchronouslyQueryServiceBrokerQueue() { using SqlDataReader reader = _com.ExecuteReader(); ProcessNotificationResults(reader); } private void TearDownAndDispose() { lock (this) { try { if (_con.State == ConnectionState.Closed || ConnectionState.Broken == _con.State) { return; } if (_com.Parameters.Count > 1) { try { _com.CommandText = _endConversationQuery; _com.Parameters.Remove(_timeoutParam); _com.ExecuteNonQuery(); } catch (Exception e) { if (!ADP.IsCatchableExceptionType(e)) { throw; } ADP.TraceExceptionWithoutRethrow(e); } } if (!_serviceQueueCreated || _errorState) { return; } _com.CommandText = "BEGIN TRANSACTION; DROP SERVICE " + _escapedQueueName + "; DROP QUEUE " + _escapedQueueName + "; DROP PROCEDURE " + _sprocName + "; COMMIT TRANSACTION;"; try { _com.ExecuteNonQuery(); } catch (Exception e2) { if (!ADP.IsCatchableExceptionType(e2)) { throw; } ADP.TraceExceptionWithoutRethrow(e2); } } finally { _stopped = true; _con.Dispose(); } } } } private class SqlNotificationParser { [Flags] private enum MessageAttributes { None = 0, Type = 1, Source = 2, Info = 4, All = 7 } private const string RootNode = "QueryNotification"; private const string MessageNode = "Message"; private const string InfoAttribute = "info"; private const string SourceAttribute = "source"; private const string TypeAttribute = "type"; internal static SqlNotification ProcessMessage(SqlXml xmlMessage) { using XmlReader xmlReader = xmlMessage.CreateReader(); _ = string.Empty; MessageAttributes messageAttributes = MessageAttributes.None; SqlNotificationType type = SqlNotificationType.Unknown; SqlNotificationInfo info = SqlNotificationInfo.Unknown; SqlNotificationSource source = SqlNotificationSource.Unknown; string key = string.Empty; xmlReader.Read(); if (XmlNodeType.Element == xmlReader.NodeType && "QueryNotification" == xmlReader.LocalName && 3 <= xmlReader.AttributeCount) { while (MessageAttributes.All != messageAttributes && xmlReader.MoveToNextAttribute()) { try { switch (xmlReader.LocalName) { case "type": try { SqlNotificationType sqlNotificationType = (SqlNotificationType)Enum.Parse(typeof(SqlNotificationType), xmlReader.Value, ignoreCase: true); if (Enum.IsDefined(typeof(SqlNotificationType), sqlNotificationType)) { type = sqlNotificationType; } } catch (Exception e2) { if (!ADP.IsCatchableExceptionType(e2)) { throw; } ADP.TraceExceptionWithoutRethrow(e2); } messageAttributes |= MessageAttributes.Type; break; case "source": try { SqlNotificationSource sqlNotificationSource = (SqlNotificationSource)Enum.Parse(typeof(SqlNotificationSource), xmlReader.Value, ignoreCase: true); if (Enum.IsDefined(typeof(SqlNotificationSource), sqlNotificationSource)) { source = sqlNotificationSource; } } catch (Exception e3) { if (!ADP.IsCatchableExceptionType(e3)) { throw; } ADP.TraceExceptionWithoutRethrow(e3); } messageAttributes |= MessageAttributes.Source; break; case "info": try { string value = xmlReader.Value; switch (value) { case "set options": info = SqlNotificationInfo.Options; break; case "previous invalid": info = SqlNotificationInfo.PreviousFire; break; case "query template limit": info = SqlNotificationInfo.TemplateLimit; break; default: { SqlNotificationInfo sqlNotificationInfo = (SqlNotificationInfo)Enum.Parse(typeof(SqlNotificationInfo), value, ignoreCase: true); if (Enum.IsDefined(typeof(SqlNotificationInfo), sqlNotificationInfo)) { info = sqlNotificationInfo; } break; } } } catch (Exception e) { if (!ADP.IsCatchableExceptionType(e)) { throw; } ADP.TraceExceptionWithoutRethrow(e); } messageAttributes |= MessageAttributes.Info; break; } } catch (ArgumentException e4) { ADP.TraceExceptionWithoutRethrow(e4); return null; } } if (MessageAttributes.All != messageAttributes) { return null; } if (!xmlReader.Read()) { return null; } if (XmlNodeType.Element != xmlReader.NodeType || string.Compare(xmlReader.LocalName, "Message", StringComparison.OrdinalIgnoreCase) != 0) { return null; } if (!xmlReader.Read()) { return null; } if (xmlReader.NodeType != XmlNodeType.Text) { return null; } using (XmlTextReader xmlTextReader = new XmlTextReader(xmlReader.Value, XmlNodeType.Element, null)) { if (!xmlTextReader.Read()) { return null; } if (xmlTextReader.NodeType != XmlNodeType.Text) { return null; } key = xmlTextReader.Value; xmlTextReader.Close(); } return new SqlNotification(info, source, type, key); } return null; } } private class SqlConnectionContainerHashHelper { private DbConnectionPoolIdentity _identity; private string _connectionString; private string _queue; private SqlConnectionStringBuilder _connectionStringBuilder; internal SqlConnectionStringBuilder ConnectionStringBuilder => _connectionStringBuilder; internal DbConnectionPoolIdentity Identity => _identity; internal string Queue => _queue; internal SqlConnectionContainerHashHelper(DbConnectionPoolIdentity identity, string connectionString, string queue, SqlConnectionStringBuilder connectionStringBuilder) { _identity = identity; _connectionString = connectionString; _queue = queue; _connectionStringBuilder = connectionStringBuilder; } public override bool Equals(object value) { SqlConnectionContainerHashHelper sqlConnectionContainerHashHelper = (SqlConnectionContainerHashHelper)value; bool flag = false; if (sqlConnectionContainerHashHelper == null) { return false; } if (this == sqlConnectionContainerHashHelper) { return true; } if ((_identity != null && sqlConnectionContainerHashHelper._identity == null) || (_identity == null && sqlConnectionContainerHashHelper._identity != null)) { return false; } if (_identity == null && sqlConnectionContainerHashHelper._identity == null) { if (sqlConnectionContainerHashHelper._connectionString == _connectionString && string.Equals(sqlConnectionContainerHashHelper._queue, _queue, StringComparison.OrdinalIgnoreCase)) { return true; } return false; } if (sqlConnectionContainerHashHelper._identity.Equals(_identity) && sqlConnectionContainerHashHelper._connectionString == _connectionString && string.Equals(sqlConnectionContainerHashHelper._queue, _queue, StringComparison.OrdinalIgnoreCase)) { return true; } return false; } public override int GetHashCode() { int num = 0; if (_identity != null) { num = _identity.GetHashCode(); } if (_queue != null) { return _connectionString.GetHashCode() + _queue.GetHashCode() + num; } return _connectionString.GetHashCode() + num; } } private static SqlDependencyProcessDispatcher s_staticInstance = new SqlDependencyProcessDispatcher(null); private Dictionary<SqlConnectionContainerHashHelper, SqlConnectionContainer> _connectionContainers; private Dictionary<string, SqlDependencyPerAppDomainDispatcher> _sqlDependencyPerAppDomainDispatchers; internal static SqlDependencyProcessDispatcher SingletonProcessDispatcher => s_staticInstance; private SqlDependencyProcessDispatcher(object dummyVariable) { _connectionContainers = new Dictionary<SqlConnectionContainerHashHelper, SqlConnectionContainer>(); _sqlDependencyPerAppDomainDispatchers = new Dictionary<string, SqlDependencyPerAppDomainDispatcher>(); } public SqlDependencyProcessDispatcher() { } private static SqlConnectionContainerHashHelper GetHashHelper(string connectionString, out SqlConnectionStringBuilder connectionStringBuilder, out DbConnectionPoolIdentity identity, out string user, string queue) { connectionStringBuilder = new SqlConnectionStringBuilder(connectionString) { Pooling = false, Enlist = false, ConnectRetryCount = 0 }; if (queue != null) { connectionStringBuilder.ApplicationName = queue; } if (connectionStringBuilder.IntegratedSecurity) { identity = DbConnectionPoolIdentity.GetCurrent(); user = null; } else { identity = null; user = connectionStringBuilder.UserID; } return new SqlConnectionContainerHashHelper(identity, connectionStringBuilder.ConnectionString, queue, connectionStringBuilder); } public override object InitializeLifetimeService() { return null; } private void Invalidate(string server, SqlNotification sqlNotification) { lock (_sqlDependencyPerAppDomainDispatchers) { foreach (KeyValuePair<string, SqlDependencyPerAppDomainDispatcher> sqlDependencyPerAppDomainDispatcher in _sqlDependencyPerAppDomainDispatchers) { SqlDependencyPerAppDomainDispatcher value = sqlDependencyPerAppDomainDispatcher.Value; try { value.InvalidateServer(server, sqlNotification); } catch (Exception e) { if (!ADP.IsCatchableExceptionType(e)) { throw; } ADP.TraceExceptionWithoutRethrow(e); } } } } internal void QueueAppDomainUnloading(string appDomainKey) { ThreadPool.QueueUserWorkItem(AppDomainUnloading, appDomainKey); } private void AppDomainUnloading(object state) { string text = (string)state; lock (_connectionContainers) { List<SqlConnectionContainerHashHelper> list = new List<SqlConnectionContainerHashHelper>(); foreach (KeyValuePair<SqlConnectionContainerHashHelper, SqlConnectionContainer> connectionContainer in _connectionContainers) { SqlConnectionContainer value = connectionContainer.Value; if (value.AppDomainUnload(text)) { list.Add(value.HashHelper); } } foreach (SqlConnectionContainerHashHelper item in list) { _connectionContainers.Remove(item); } } lock (_sqlDependencyPerAppDomainDispatchers) { _sqlDependencyPerAppDomainDispatchers.Remove(text); } } internal bool StartWithDefault(string connectionString, out string server, out DbConnectionPoolIdentity identity, out string user, out string database, ref string service, string appDomainKey, SqlDependencyPerAppDomainDispatcher dispatcher, out bool errorOccurred, out bool appDomainStart) { return Start(connectionString, out server, out identity, out user, out database, ref service, appDomainKey, dispatcher, out errorOccurred, out appDomainStart, useDefaults: true); } internal bool Start(string connectionString, string queue, string appDomainKey, SqlDependencyPerAppDomainDispatcher dispatcher) { string server; DbConnectionPoolIdentity identity; bool errorOccurred; return Start(connectionString, out server, out identity, out server, out server, ref queue, appDomainKey, dispatcher, out errorOccurred, out errorOccurred, useDefaults: false); } private bool Start(string connectionString, out string server, out DbConnectionPoolIdentity identity, out string user, out string database, ref string queueService, string appDomainKey, SqlDependencyPerAppDomainDispatcher dispatcher, out bool errorOccurred, out bool appDomainStart, bool useDefaults) { server = null; identity = null; user = null; database = null; errorOccurred = false; appDomainStart = false; lock (_sqlDependencyPerAppDomainDispatchers) { if (!_sqlDependencyPerAppDomainDispatchers.ContainsKey(appDomainKey)) { _sqlDependencyPerAppDomainDispatchers[appDomainKey] = dispatcher; } } SqlConnectionStringBuilder connectionStringBuilder; SqlConnectionContainerHashHelper hashHelper = GetHashHelper(connectionString, out connectionStringBuilder, out identity, out user, queueService); bool result = false; SqlConnectionContainer sqlConnectionContainer = null; lock (_connectionContainers) { if (!_connectionContainers.ContainsKey(hashHelper)) { sqlConnectionContainer = new SqlConnectionContainer(hashHelper, appDomainKey, useDefaults); _connectionContainers.Add(hashHelper, sqlConnectionContainer); result = true; appDomainStart = true; } else { sqlConnectionContainer = _connectionContainers[hashHelper]; if (sqlConnectionContainer.InErrorState) { errorOccurred = true; } else { sqlConnectionContainer.IncrementStartCount(appDomainKey, out appDomainStart); } } } if (useDefaults && !errorOccurred) { server = sqlConnectionContainer.Server; database = sqlConnectionContainer.Database; queueService = sqlConnectionContainer.Queue; } return result; } internal bool Stop(string connectionString, out string server, out DbConnectionPoolIdentity identity, out string user, out string database, ref string queueService, string appDomainKey, out bool appDomainStop) { server = null; identity = null; user = null; database = null; appDomainStop = false; SqlConnectionStringBuilder connectionStringBuilder; SqlConnectionContainerHashHelper hashHelper = GetHashHelper(connectionString, out connectionStringBuilder, out identity, out user, queueService); bool result = false; lock (_connectionContainers) { if (_connectionContainers.ContainsKey(hashHelper)) { SqlConnectionContainer sqlConnectionContainer = _connectionContainers[hashHelper]; server = sqlConnectionContainer.Server; database = sqlConnectionContainer.Database; queueService = sqlConnectionContainer.Queue; if (sqlConnectionContainer.Stop(appDomainKey, out appDomainStop)) { result = true; _connectionContainers.Remove(hashHelper); } } } return result; } } internal static class AssemblyRef { internal const string SystemConfiguration = "System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; internal const string System = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string EcmaPublicKey = "b77a5c561934e089"; public const string FrameworkPublicKeyFull = "00000000000000000400000000000000"; public const string FrameworkPublicKeyFull2 = "00000000000000000400000000000000"; public const string MicrosoftPublicKey = "b03f5f7f11d50a3a"; public const string MicrosoftJScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string MicrosoftVSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemData = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string SystemDesign = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemDrawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemWeb = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemWebExtensions = "System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string SystemWindowsForms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } internal static class Consts { public const string MonoVersion = "5.11.0.0"; public const string MonoCompany = "Mono development team"; public const string MonoProduct = "Mono Common Language Infrastructure"; public const string MonoCopyright = "(c) Various Mono authors"; public const int MonoCorlibVersion = 1051100001; public const string FxVersion = "4.0.0.0"; public const string FxFileVersion = "4.6.57.0"; public const string EnvironmentVersion = "4.0.30319.42000"; public const string VsVersion = "0.0.0.0"; public const string VsFileVersion = "11.0.0.0"; private const string PublicKeyToken = "b77a5c561934e089"; public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } internal sealed class Locale { private Locale() { } public static string GetText(string msg) { return msg; } public static string GetText(string fmt, params object[] args) { return string.Format(fmt, args); } } internal static class SR { public const string ADP_CollectionIndexString = "An {0} with {1} '{2}' is not contained by this {3}."; public const string ADP_CollectionInvalidType = "The {0} only accepts non-null {1} type objects, not {2} objects."; public const string ADP_CollectionIsNotParent = "The {0} is already contained by another {1}."; public const string ADP_CollectionNullValue = "The {0} only accepts non-null {1} type objects."; public const string ADP_CollectionRemoveInvalidObject = "Attempted to remove an {0} that is not contained by this {1}."; public const string ADP_CollectionUniqueValue = "The {0}.{1} is required to be unique, '{2}' already exists in the collection."; public const string ADP_ConnectionStateMsg_Closed = "The connection's current state is closed."; public const string ADP_ConnectionStateMsg_Connecting = "The connection's current state is connecting."; public const string ADP_ConnectionStateMsg_Open = "The connection's current state is open."; public const string ADP_ConnectionStateMsg_OpenExecuting = "The connection's current state is executing."; public const string ADP_ConnectionStateMsg_OpenFetching = "The connection's current state is fetching."; public const string ADP_ConnectionStateMsg = "The connection's current state: {0}."; public const string ADP_ConnectionStringSyntax = "Format of the initialization string does not conform to specification starting at index {0}."; public const string ADP_DataReaderClosed = "Invalid attempt to call {0} when reader is closed."; public const string ADP_EmptyString = "Expecting non-empty string for '{0}' parameter."; public const string ADP_InvalidEnumerationValue = "The {0} enumeration value, {1}, is invalid."; public const string ADP_InvalidKey = "Invalid keyword, contain one or more of 'no characters', 'control characters', 'leading or trailing whitespace' or 'leading semicolons'."; public const string ADP_InvalidValue = "The value contains embedded nulls (\\\\u0000)."; public const string Xml_SimpleTypeNotSupported = "DataSet doesn't support 'union' or 'list' as simpleType."; public const string Xml_MissingAttribute = "Invalid {0} syntax: missing required '{1}' attribute."; public const string Xml_ValueOutOfRange = "Value '{1}' is invalid for attribute '{0}'."; public const string Xml_AttributeValues = "The value of attribute '{0}' should be '{1}' or '{2}'."; public const string Xml_RelationParentNameMissing = "Parent table name is missing in relation '{0}'."; public const string Xml_RelationChildNameMissing = "Child table name is missing in relation '{0}'."; public const string Xml_RelationTableKeyMissing = "Parent table key is missing in relation '{0}'."; public const string Xml_RelationChildKeyMissing = "Child table key is missing in relation '{0}'."; public const string Xml_UndefinedDatatype = "Undefined data type: '{0}'."; public const string Xml_DatatypeNotDefined = "Data type not defined."; public const string Xml_InvalidField = "Invalid XPath selection inside field node. Cannot find: {0}."; public const string Xml_InvalidSelector = "Invalid XPath selection inside selector node: {0}."; public const string Xml_InvalidKey = "Invalid 'Key' node inside constraint named: {0}."; public const string Xml_DuplicateConstraint = "The constraint name {0} is already used in the schema."; public const string Xml_CannotConvert = " Cannot convert '{0}' to type '{1}'."; public const string Xml_MissingRefer = "Missing '{0}' part in '{1}' constraint named '{2}'."; public const string Xml_MismatchKeyLength = "Invalid Relation definition: different length keys."; public const string Xml_CircularComplexType = "DataSet doesn't allow the circular reference in the ComplexType named '{0}'."; public const string Xml_CannotInstantiateAbstract = "DataSet cannot instantiate an abstract ComplexType for the node {0}."; public const string Xml_MultipleTargetConverterError = "An error occurred with the multiple target converter while writing an Xml Schema. See the inner exception for details."; public const string Xml_MultipleTargetConverterEmpty = "An error occurred with the multiple target converter while writing an Xml Schema. A null or empty string was returned."; public const string Xml_MergeDuplicateDeclaration = "Duplicated declaration '{0}'."; public const string Xml_MissingTable = "Cannot load diffGram. Table '{0}' is missing in the destination dataset."; public const string Xml_MissingSQL = "Cannot load diffGram. The 'sql' node is missing."; public const string Xml_ColumnConflict = "Column name '{0}' is defined for different mapping types."; public const string Xml_InvalidPrefix = "Prefix '{0}' is not valid, because it contains special characters."; public const string Xml_NestedCircular = "Circular reference in self-nested table '{0}'."; public const string Xml_FoundEntity = "DataSet cannot expand entities. Use XmlValidatingReader and set the EntityHandling property accordingly."; public const string Xml_PolymorphismNotSupported = "Type '{0}' does not implement IXmlSerializable interface therefore can not proceed with serialization."; public const string Xml_CanNotDeserializeObjectType = "Unable to proceed with deserialization. Data does not implement IXMLSerializable, therefore polymorphism is not supported."; public const string Xml_DataTableInferenceNotSupported = "DataTable does not support schema inference from Xml."; public const string Xml_MultipleParentRows = "Cannot proceed with serializing DataTable '{0}'. It contains a DataRow which has multiple parent rows on the same Foreign Key."; public const string Xml_IsDataSetAttributeMissingInSchema = "IsDataSet attribute is missing in input Schema."; public const string Xml_TooManyIsDataSetAtributeInSchema = "Cannot determine the DataSet Element. IsDataSet attribute exist more than once."; public const string Xml_DynamicWithoutXmlSerializable = "DataSet will not serialize types that implement IDynamicMetaObjectProvider but do not also implement IXmlSerializable."; public const string Expr_NYI = "The feature not implemented. {0}."; public const string Expr_MissingOperand = "Syntax error: Missing operand after '{0}' operator."; public const string Expr_TypeMismatch = "Type mismatch in expression '{0}'."; public const string Expr_ExpressionTooComplex = "Expression is too complex."; public const string Expr_UnboundName = "Cannot find column [{0}]."; public const string Expr_InvalidString = "The expression contains an invalid string constant: {0}."; public const string Expr_UndefinedFunction = "The expression contains undefined function call {0}()."; public const string Expr_Syntax = "Syntax error in the expression."; public const string Expr_FunctionArgumentCount = "Invalid number of arguments: function {0}()."; public const string Expr_MissingRightParen = "The expression is missing the closing parenthesis."; public const string Expr_UnknownToken = "Cannot interpret token '{0}' at position {1}."; public const string Expr_UnknownToken1 = "Expected {0}, but actual token at the position {2} is {1}."; public const string Expr_DatatypeConvertion = "Cannot convert from {0} to {1}."; public const string Expr_DatavalueConvertion = "Cannot convert value '{0}' to Type: {1}."; public const string Expr_InvalidName = "Invalid column name [{0}]."; public const string Expr_InvalidDate = "The expression contains invalid date constant '{0}'."; public const string Expr_NonConstantArgument = "Only constant expressions are allowed in the expression list for the IN operator."; public const string Expr_InvalidPattern = "Error in Like operator: the string pattern '{0}' is invalid."; public const string Expr_InWithoutParentheses = "Syntax error: The items following the IN keyword must be separated by commas and be enclosed in parentheses."; public const string Expr_ArgumentType = "Type mismatch in function argument: {0}(), argument {1}, expected {2}."; public const string Expr_ArgumentTypeInteger = "Type mismatch in function argument: {0}(), argument {1}, expected one of the Integer types."; public const string Expr_TypeMismatchInBinop = "Cannot perform '{0}' operation on {1} and {2}."; public const string Expr_AmbiguousBinop = "Operator '{0}' is ambiguous on operands of type '{1}' and '{2}'. Cannot mix signed and unsigned types. Please use explicit Convert() function."; public const string Expr_InWithoutList = "Syntax error: The IN keyword must be followed by a non-empty list of expressions separated by commas, and also must be enclosed in parentheses."; public const string Expr_UnsupportedOperator = "The expression contains unsupported operator '{0}'."; public const string Expr_InvalidNameBracketing = "The expression contains invalid name: '{0}'."; public const string Expr_MissingOperandBefore = "Syntax error: Missing operand before '{0}' operator."; public const string Expr_TooManyRightParentheses = "The expression has too many closing parentheses."; public const string Expr_UnresolvedRelation = "The table [{0}] involved in more than one relation. You must explicitly mention a relation name in the expression '{1}'."; public const string Expr_AggregateArgument = "Syntax error in aggregate argument: Expecting a single column argument with possible 'Child' qualifier."; public const string Expr_AggregateUnbound = "Unbound reference in the aggregate expression '{0}'."; public const string Expr_EvalNoContext = "Cannot evaluate non-constant expression without current row."; public const string Expr_ExpressionUnbound = "Unbound reference in the expression '{0}'."; public const string Expr_ComputeNotAggregate = "Cannot evaluate. Expression '{0}' is not an aggregate."; public const string Expr_FilterConvertion = "Filter expression '{0}' does not evaluate to a Boolean term."; public const string Expr_InvalidType = "Invalid type name '{0}'."; public const string Expr_LookupArgument = "Syntax error in Lookup expression: Expecting keyword 'Parent' followed by a single column argument with possible relation qualifier: Parent[(<relation_name>)].<column_name>."; public const string Expr_InvokeArgument = "Need a row or a table to Invoke DataFilter."; public const string Expr_ArgumentOutofRange = "{0}() argument is out of range."; public const string Expr_IsSyntax = "Syntax error: Invalid usage of 'Is' operator. Correct syntax: <expression> Is [Not] Null."; public const string Expr_Overflow = "Value is either too large or too small for Type '{0}'."; public const string Expr_BindFailure = "Cannot find the parent relation '{0}'."; public const string Expr_InvalidHoursArgument = "'hours' argument is out of range. Value must be between -14 and +14."; public const string Expr_InvalidMinutesArgument = "'minutes' argument is out of range. Value must be between -59 and +59."; public const string Expr_InvalidTimeZoneRange = "Provided range for time one exceeds total of 14 hours."; public const string Expr_MismatchKindandTimeSpan = "Kind property of provided DateTime argument, does not match 'hours' and 'minutes' arguments."; public const string Expr_UnsupportedType = "A DataColumn of type '{0}' does not support expression."; public const string Data_EnforceConstraints = "Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints."; public const string Data_CannotModifyCollection = "Collection itself is not modifiable."; public const string Data_CaseInsensitiveNameConflict = "The given name '{0}' matches at least two names in the collection object with different cases, but does not match either of them with the same case."; public const string Data_NamespaceNameConflict = "The given name '{0}' matches at least two names in the collection object with different namespaces."; public const string Data_InvalidOffsetLength = "Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."; public const string Data_ArgumentOutOfRange = "'{0}' argument is out of range."; public const string Data_ArgumentNull = "'{0}' argument cannot be null."; public const string Data_ArgumentContainsNull = "'{0}' argument contains null value."; public const string DataColumns_OutOfRange = "Cannot find column {0}."; public const string DataColumns_Add1 = "Column '{0}' already belongs to this DataTable."; public const string DataColumns_Add2 = "Column '{0}' already belongs to another DataTable."; public const string DataColumns_Add3 = "Cannot have more than one SimpleContent columns in a DataTable."; public const string DataColumns_Add4 = "Cannot add a SimpleContent column to a table containing element columns or nested relations."; public const string DataColumns_AddDuplicate = "A column named '{0}' already belongs to this DataTable."; public const string DataColumns_AddDuplicate2 = "Cannot add a column named '{0}': a nested table with the same name already belongs to this DataTable."; public const string DataColumns_AddDuplicate3 = "A column named '{0}' already belongs to this DataTable: cannot set a nested table name to the same name."; public const string DataColumns_Remove = "Cannot remove a column that doesn't belong to this table."; public const string DataColumns_RemovePrimaryKey = "Cannot remove this column, because it's part of the primary key."; public const string DataColumns_RemoveChildKey = "Cannot remove this column, because it is part of the parent key for relationship {0}."; public const string DataColumns_RemoveConstraint = "Cannot remove this column, because it is a part of the constraint {0} on the table {1}."; public const string DataColumn_AutoIncrementAndExpression = "Cannot set AutoIncrement property for a computed column."; public const string DataColumn_AutoIncrementAndDefaultValue = "Cannot set AutoIncrement property for a column with DefaultValue set."; public const string DataColumn_DefaultValueAndAutoIncrement = "Cannot set a DefaultValue on an AutoIncrement column."; public const string DataColumn_AutoIncrementSeed = "AutoIncrementStep must be a non-zero value."; public const string DataColumn_NameRequired = "ColumnName is required when it is part of a DataTable."; public const string DataColumn_ChangeDataType = "Cannot change DataType of a column once it has data."; public const string DataColumn_NullDataType = "Column requires a valid DataType."; public const string DataColumn_DefaultValueDataType = "The DefaultValue for column {0} is of type {1} and cannot be converted to {2}."; public const string DataColumn_DefaultValueDataType1 = "The DefaultValue for the column is of type {0} and cannot be converted to {1}."; public const string DataColumn_DefaultValueColumnDataType = "The DefaultValue for column {0} is of type {1}, but the column is of type {2}."; public const string DataColumn_ReadOnlyAndExpression = "Cannot change ReadOnly property for the expression column."; public const string DataColumn_UniqueAndExpression = "Cannot change Unique property for the expression column."; public const string DataColumn_ExpressionAndUnique = "Cannot create an expression on a column that has AutoIncrement or Unique."; public const string DataColumn_ExpressionAndReadOnly = "Cannot set expression because column cannot be made ReadOnly."; public const string DataColumn_ExpressionAndConstraint = "Cannot set Expression property on column {0}, because it is a part of a constraint."; public const string DataColumn_ExpressionInConstraint = "Cannot create a constraint based on Expression column {0}."; public const string DataColumn_ExpressionCircular = "Cannot set Expression property due to circular reference in the expression."; public const string DataColumn_NullKeyValues = "Column '{0}' has null values in it."; public const string DataColumn_NullValues = "Column '{0}' does not allow nulls."; public const string DataColumn_ReadOnly = "Column '{0}' is read only."; public const string DataColumn_NonUniqueValues = "Column '{0}' contains non-unique values."; public const string DataColumn_NotInTheTable = "Column '{0}' does not belong to table {1}."; public const string DataColumn_NotInAnyTable = "Column must belong to a table."; public const string DataColumn_SetFailed = "Couldn't store <{0}> in {1} Column. Expected type is {2}."; public const string DataColumn_CannotSetToNull = "Cannot set Column '{0}' to be null. Please use DBNull instead."; public const string DataColumn_LongerThanMaxLength = "Cannot set column '{0}'. The value violates the MaxLength limit of this column."; public const string DataColumn_HasToBeStringType = "MaxLength applies to string data type only. You cannot set Column '{0}' property MaxLength to be non-negative number."; public const string DataColumn_CannotSetMaxLength = "Cannot set Column '{0}' property MaxLength to '{1}'. There is at least one string in the table longer than the new limit."; public const string DataColumn_CannotSetMaxLength2 = "Cannot set Column '{0}' property MaxLength. The Column is SimpleContent."; public const string DataColumn_CannotSimpleContentType = "Cannot set Column '{0}' property DataType to {1}. The Column is SimpleContent."; public const string DataColumn_CannotSimpleContent = "Cannot set Column '{0}' property MappingType to SimpleContent. The Column DataType is {1}."; public const string DataColumn_ExceedMaxLength = "Column '{0}' exceeds the MaxLength limit."; public const string DataColumn_NotAllowDBNull = "Column '{0}' does not allow DBNull.Value."; public const string DataColumn_CannotChangeNamespace = "Cannot change the Column '{0}' property Namespace. The Column is SimpleContent."; public const string DataColumn_AutoIncrementCannotSetIfHasData = "Cannot change AutoIncrement of a DataColumn with type '{0}' once it has data."; public const string DataColumn_NotInTheUnderlyingTable = "Column '{0}' does not belong to underlying table '{1}'."; public const string DataColumn_InvalidDataColumnMapping = "DataColumn with type '{0}' is a complexType. Can not serialize value of a complex type as Attribute"; public const string DataColumn_CannotSetDateTimeModeForNonDateTimeColumns = "The DateTimeMode can be set only on DataColumns of type DateTime."; public const string DataColumn_DateTimeMode = "Cannot change DateTimeMode from '{0}' to '{1}' once the table has data."; public const string DataColumn_INullableUDTwithoutStaticNull = "Type '{0}' does not contain static Null property or field."; public const string DataColumn_UDTImplementsIChangeTrackingButnotIRevertible = "Type '{0}' does not implement IRevertibleChangeTracking; therefore can not proceed with RejectChanges()."; public const string DataColumn_SetAddedAndModifiedCalledOnNonUnchanged = "SetAdded and SetModified can only be called on DataRows with Unchanged DataRowState."; public const string DataColumn_OrdinalExceedMaximun = "Ordinal '{0}' exceeds the maximum number."; public const string DataColumn_NullableTypesNotSupported = "DataSet does not support System.Nullable<>."; public const string DataConstraint_NoName = "Cannot change the name of a constraint to empty string when it is in the ConstraintCollection."; public const string DataConstraint_Violation = "Cannot enforce constraints on constraint {0}."; public const string DataConstraint_ViolationValue = "Column '{0}' is constrained to be unique. Value '{1}' is already present."; public const string DataConstraint_NotInTheTable = "Constraint '{0}' does not belong to this DataTable."; public const string DataConstraint_OutOfRange = "Cannot find constraint {0}."; public const string DataConstraint_Duplicate = "Constraint matches constraint named {0} already in collection."; public const string DataConstraint_DuplicateName = "A Constraint named '{0}' already belongs to this DataTable."; public const string DataConstraint_UniqueViolation = "These columns don't currently have unique values."; public const string DataConstraint_ForeignTable = "These columns don't point to this table."; public const string DataConstraint_ParentValues = "This constraint cannot be enabled as not all values have corresponding parent values."; public const string DataConstraint_AddFailed = "This constraint cannot be added since ForeignKey doesn't belong to table {0}."; public const string DataConstraint_RemoveFailed = "Cannot remove a constraint that doesn't belong to this table."; public const string DataConstraint_NeededForForeignKeyConstraint = "Cannot remove unique constraint '{0}'. Remove foreign key constraint '{1}' first."; public const string DataConstraint_CascadeDelete = "Cannot delete this row because constraints are enforced on relation {0}, and deleting this row will strand child rows."; public const string DataConstraint_CascadeUpdate = "Cannot make this change because constraints are enforced on relation {0}, and changing this value will strand child rows."; public const string DataConstraint_ClearParentTable = "Cannot clear table {0} because ForeignKeyConstraint {1} enforces constraints and there are child rows in {2}."; public const string DataConstraint_ForeignKeyViolation = "ForeignKeyConstraint {0} requires the child key values ({1}) to exist in the parent table."; public const string DataConstraint_BadObjectPropertyAccess = "Property not accessible because '{0}'."; public const string DataConstraint_RemoveParentRow = "Cannot remove this row because it has child rows, and constraints on relation {0} are enforced."; public const string DataConstraint_AddPrimaryKeyConstraint = "Cannot add primary key constraint since primary key is already set for the table."; public const string DataConstraint_CantAddConstraintToMultipleNestedTable = "Cannot add constraint to DataTable '{0}' which is a child table in two nested relations."; public const string DataKey_TableMismatch = "Cannot create a Key from Columns that belong to different tables."; public const string DataKey_NoColumns = "Cannot have 0 columns."; public const string DataKey_TooManyColumns = "Cannot have more than {0} columns."; public const string DataKey_DuplicateColumns = "Cannot create a Key when the same column is listed more than once: '{0}'"; public const string DataKey_RemovePrimaryKey = "Cannot remove unique constraint since it's the primary key of a table."; public const string DataKey_RemovePrimaryKey1 = "Cannot remove unique constraint since it's the primary key of table {0}."; public const string DataRelation_ColumnsTypeMismatch = "Parent Columns and Child Columns don't have type-matching columns."; public const string DataRelation_KeyColumnsIdentical = "ParentKey and ChildKey are identical."; public const string DataRelation_KeyLengthMismatch = "ParentColumns and ChildColumns should be the same length."; public const string DataRelation_KeyZeroLength = "ParentColumns and ChildColumns must not be zero length."; public const string DataRelation_ForeignRow = "The row doesn't belong to the same DataSet as this relation."; public const string DataRelation_NoName = "RelationName is required when it is part of a DataSet."; public const string DataRelation_ForeignTable = "GetChildRows requires a row whose Table is {0}, but the specified row's Table is {1}."; public const string DataRelation_ForeignDataSet = "This relation should connect two tables in this DataSet to be added to this DataSet."; public const string DataRelation_GetParentRowTableMismatch = "GetParentRow requires a row whose Table is {0}, but the specified row's Table is {1}."; public const string DataRelation_SetParentRowTableMismatch = "SetParentRow requires a child row whose Table is {0}, but the specified row's Table is {1}."; public const string DataRelation_DataSetMismatch = "Cannot have a relationship between tables in different DataSets."; public const string DataRelation_TablesInDifferentSets = "Cannot create a relation between tables in different DataSets."; public const string DataRelation_AlreadyExists = "A relation already exists for these child columns."; public const string DataRelation_DoesNotExist = "This relation doesn't belong to this relation collection."; public const string DataRelation_AlreadyInOtherDataSet = "This relation already belongs to another DataSet."; public const string DataRelation_AlreadyInTheDataSet = "This relation already belongs to this DataSet."; public const string DataRelation_DuplicateName = "A Relation named '{0}' already belongs to this DataSet."; public const string DataRelation_NotInTheDataSet = "Relation {0} does not belong to this DataSet."; public const string DataRelation_OutOfRange = "Cannot find relation {0}."; public const string DataRelation_TableNull = "Cannot create a collection on a null table."; public const string DataRelation_TableWasRemoved = "The table this collection displays relations for has been removed from its DataSet."; public const string DataRelation_ChildTableMismatch = "Cannot add a relation to this table's ParentRelation collection where this table isn't the child table."; public const string DataRelation_ParentTableMismatch = "Cannot add a relation to this table's ChildRelation collection where this table isn't the parent table."; public const string DataRelation_RelationNestedReadOnly = "Cannot set the 'Nested' property to false for this relation."; public const string DataRelation_TableCantBeNestedInTwoTables = "The same table '{0}' cannot be the child table in two nested relations."; public const string DataRelation_LoopInNestedRelations = "The table ({0}) cannot be the child table to itself in nested relations."; public const string DataRelation_CaseLocaleMismatch = "Cannot add a DataRelation or Constraint that has different Locale or CaseSensitive settings between its parent and child tables."; public const string DataRelation_ParentOrChildColumnsDoNotHaveDataSet = "Cannot create a DataRelation if Parent or Child Columns are not in a DataSet."; public const string DataRelation_InValidNestedRelation = "Nested table '{0}' which inherits its namespace cannot have multiple parent tables in different namespaces."; public const string DataRelation_InValidNamespaceInNestedRelation = "Nested table '{0}' with empty namespace cannot have multiple parent tables in different namespaces."; public const string DataRow_NotInTheDataSet = "The row doesn't belong to the same DataSet as this relation."; public const string DataRow_NotInTheTable = "Cannot perform this operation on a row not in the table."; public const string DataRow_ParentRowNotInTheDataSet = "This relation and child row don't belong to same DataSet."; public const string DataRow_EditInRowChanging = "Cannot change a proposed value in the RowChanging event."; public const string DataRow_EndEditInRowChanging = "Cannot call EndEdit() inside an OnRowChanging event."; public const string DataRow_BeginEditInRowChanging = "Cannot call BeginEdit() inside the RowChanging event."; public const string DataRow_CancelEditInRowChanging = "Cannot call CancelEdit() inside an OnRowChanging event. Throw an exception to cancel this update."; public const string DataRow_DeleteInRowDeleting = "Cannot call Delete inside an OnRowDeleting event. Throw an exception to cancel this delete."; public const string DataRow_ValuesArrayLength = "Input array is longer than the number of columns in this table."; public const string DataRow_NoCurrentData = "There is no Current data to access."; public const string DataRow_NoOriginalData = "There is no Original data to access."; public const string DataRow_NoProposedData = "There is no Proposed data to access."; public const string DataRow_RemovedFromTheTable = "This row has been removed from a table and does not have any data. BeginEdit() will allow creation of new data in this row."; public const string DataRow_DeletedRowInaccessible = "Deleted row information cannot be accessed through the row."; public const string DataRow_InvalidVersion = "Version must be Original, Current, or Proposed."; public const string DataRow_OutOfRange = "There is no row at position {0}."; public const string DataRow_RowInsertOutOfRange = "The row insert position {0} is invalid."; public const string DataRow_RowInsertMissing = "Values are missing in the rowOrder sequence for table '{0}'."; public const string DataRow_RowOutOfRange = "The given DataRow is not in the current DataRowCollection."; public const string DataRow_AlreadyInOtherCollection = "This row already belongs to another table."; public const string DataRow_AlreadyInTheCollection = "This row already belongs to this table."; public const string DataRow_AlreadyDeleted = "Cannot delete this row since it's already deleted."; public const string DataRow_Empty = "This row is empty."; public const string DataRow_AlreadyRemoved = "Cannot remove a row that's already been removed."; public const string DataRow_MultipleParents = "A child row has multiple parents."; public const string DataRow_InvalidRowBitPattern = "Unrecognized row state bit pattern."; public const string DataSet_SetNameToEmpty = "Cannot change the name of the DataSet to an empty string."; public const string DataSet_SetDataSetNameConflicting = "The name '{0}' is invalid. A DataSet cannot have the same name of the DataTable."; public const string DataSet_UnsupportedSchema = "The schema namespace is invalid. Please use this one instead: {0}."; public const string DataSet_CannotChangeCaseLocale = "Cannot change CaseSensitive or Locale property. This change would lead to at least one DataRelation or Constraint to have different Locale or CaseSensitive settings between its related tables."; public const string DataSet_CannotChangeSchemaSerializationMode = "SchemaSerializationMode property can be set only if it is overridden by derived DataSet."; public const string DataTable_ForeignPrimaryKey = "PrimaryKey columns do not belong to this table."; public const string DataTable_CannotAddToSimpleContent = "Cannot add a nested relation or an element column to a table containing a SimpleContent column."; public const string DataTable_NoName = "TableName is required when it is part of a DataSet."; public const string DataTable_MultipleSimpleContentColumns = "DataTable already has a simple content column."; public const string DataTable_MissingPrimaryKey = "Table doesn't have a primary key."; public const string DataTable_InvalidSortString = " {0} isn't a valid Sort string entry."; public const string DataTable_CanNotSerializeDataTableHierarchy = "Cannot serialize the DataTable. A DataTable being used in one or more DataColumn expressions is not a descendant of current DataTable."; public const string DataTable_CanNotRemoteDataTable = "This DataTable can only be remoted as part of DataSet. One or more Expression Columns has reference to other DataTable(s)."; public const string DataTable_CanNotSetRemotingFormat = "Cannot have different remoting format property value for DataSet and DataTable."; public const string DataTable_CanNotSerializeDataTableWithEmptyName = "Cannot serialize the DataTable. DataTable name is not set."; public const string DataTable_DuplicateName = "A DataTable named '{0}' already belongs to this DataSet."; public const string DataTable_DuplicateName2 = "A DataTable named '{0}' with the same Namespace '{1}' already belongs to this DataSet."; public const string DataTable_SelfnestedDatasetConflictingName = "The table ({0}) cannot be the child table to itself in a nested relation: the DataSet name conflicts with the table name."; public const string DataTable_DatasetConflictingName = "The name '{0}' is invalid. A DataTable cannot have the same name of the DataSet."; public const string DataTable_AlreadyInOtherDataSet = "DataTable already belongs to another DataSet."; public const string DataTable_AlreadyInTheDataSet = "DataTable already belongs to this DataSet."; public const string DataTable_NotInTheDataSet = "Table {0} does not belong to this DataSet."; public const string DataTable_OutOfRange = "Cannot find table {0}."; public const string DataTable_InRelation = "Cannot remove a table that has existing relations. Remove relations first."; public const string DataTable_InConstraint = "Cannot remove table {0}, because it referenced in ForeignKeyConstraint {1}. Remove the constraint first."; public const string DataTable_TableNotFound = "DataTable '{0}' does not match to any DataTable in source."; public const string DataMerge_MissingDefinition = "Target DataSet missing definition for {0}."; public const string DataMerge_MissingConstraint = "Target DataSet missing {0} {1}."; public const string DataMerge_DataTypeMismatch = "<target>.{0} and <source>.{0} have conflicting properties: DataType property mismatch."; public const string DataMerge_PrimaryKeyMismatch = "<target>.PrimaryKey and <source>.PrimaryKey have different Length."; public const string DataMerge_PrimaryKeyColumnsMismatch = "Mismatch columns in the PrimaryKey : <target>.{0} versus <source>.{1}."; public const string DataMerge_ReltionKeyColumnsMismatch = "Relation {0} cannot be merged, because keys have mismatch columns."; public const string DataMerge_MissingColumnDefinition = "Target table {0} missing definition for column {1}."; public const string DataIndex_RecordStateRange = "The RowStates parameter must be set to a valid combination of values from the DataViewRowState enumeration."; public const string DataIndex_FindWithoutSortOrder = "Find finds a row based on a Sort order, and no Sort order is specified."; public const string DataIndex_KeyLength = "Expecting {0} value(s) for the key being indexed, but received {1} value(s)."; public const string DataStorage_AggregateException = "Invalid usage of aggregate function {0}() and Type: {1}."; public const string DataStorage_InvalidStorageType = "Invalid storage type: {0}."; public const string DataStorage_ProblematicChars = "The DataSet Xml persistency does not support the value '{0}' as Char value, please use Byte storage instead."; public const string DataStorage_SetInvalidDataType = "Type of value has a mismatch with column type"; public const string DataStorage_IComparableNotDefined = " Type '{0}' does not implement IComparable interface. Comparison cannot be done."; public const string DataView_SetFailed = "Cannot set {0}."; public const string DataView_SetDataSetFailed = "Cannot change DataSet on a DataViewManager that's already the default view for a DataSet."; public const string DataView_SetRowStateFilter = "RowStateFilter cannot show ModifiedOriginals and ModifiedCurrents at the same time."; public const string DataView_SetTable = "Cannot change Table property on a DefaultView or a DataView coming from a DataViewManager."; public const string DataView_CanNotSetDataSet = "Cannot change DataSet property once it is set."; public const string DataView_CanNotUseDataViewManager = "DataSet must be set prior to using DataViewManager."; public const string DataView_CanNotSetTable = "Cannot change Table property once it is set."; public const string DataView_CanNotUse = "DataTable must be set prior to using DataView."; public const string DataView_CanNotBindTable = "Cannot bind to DataTable with no name."; public const string DataView_SetIListObject = "Cannot set an object into this list."; public const string DataView_AddNewNotAllowNull = "Cannot call AddNew on a DataView where AllowNew is false."; public const string DataView_NotOpen = "DataView is not open."; public const string DataView_CreateChildView = "The relation is not parented to the table to which this DataView points."; public const string DataView_CanNotDelete = "Cannot delete on a DataSource where AllowDelete is false."; public const string DataView_CanNotEdit = "Cannot edit on a DataSource where AllowEdit is false."; public const string DataView_GetElementIndex = "Index {0} is either negative or above rows count."; public const string DataView_AddExternalObject = "Cannot add external objects to this list."; public const string DataView_CanNotClear = "Cannot clear this list."; public const string DataView_InsertExternalObject = "Cannot insert external objects to this list."; public const string DataView_RemoveExternalObject = "Cannot remove objects not in the list."; public const string DataROWView_PropertyNotFound = "{0} is neither a DataColumn nor a DataRelation for table {1}."; public const string Range_Argument = "Min ({0}) must be less than or equal to max ({1}) in a Range object."; public const string Range_NullRange = "This is a null range."; public const string RecordManager_MinimumCapacity = "MinimumCapacity must be non-negative."; public const string SqlConvert_ConvertFailed = " Cannot convert object of type '{0}' to object of type '{1}'."; public const string DataSet_DefaultDataException = "Data Exception."; public const string DataSet_DefaultConstraintException = "Constraint Exception."; public const string DataSet_DefaultDeletedRowInaccessibleException = "Deleted rows inaccessible."; public const string DataSet_DefaultDuplicateNameException = "Duplicate name not allowed."; public const string DataSet_DefaultInRowChangingEventException = "Operation not supported in the RowChanging event."; public const string DataSet_DefaultInvalidConstraintException = "Invalid constraint."; public const string DataSet_DefaultMissingPrimaryKeyException = "Missing primary key."; public const string DataSet_DefaultNoNullAllowedException = "Null not allowed."; public const string DataSet_DefaultReadOnlyException = "Column is marked read only."; public const string DataSet_DefaultRowNotInTableException = "Row not found in table."; public const string DataSet_DefaultVersionNotFoundException = "Version not found."; public const string Load_ReadOnlyDataModified = "ReadOnly Data is Modified."; public const string DataTableReader_InvalidDataTableReader = "DataTableReader is invalid for current DataTable '{0}'."; public const string DataTableReader_SchemaInvalidDataTableReader = "Schema of current DataTable '{0}' in DataTableReader has changed, DataTableReader is invalid."; public const string DataTableReader_CannotCreateDataReaderOnEmptyDataSet = "DataTableReader Cannot be created. There is no DataTable in DataSet."; public const string DataTableReader_DataTableReaderArgumentIsEmpty = "Cannot create DataTableReader. Argument is Empty."; public const string DataTableReader_ArgumentContainsNullValue = "Cannot create DataTableReader. Arguments contain null value."; public const string DataTableReader_InvalidRowInDataTableReader = "Current DataRow is either in Deleted or Detached state."; public const string DataTableReader_DataTableCleared = "Current DataTable '{0}' is empty. There is no DataRow in DataTable."; public const string RbTree_InvalidState = "DataTable internal index is corrupted: '{0}'."; public const string RbTree_EnumerationBroken = "Collection was modified; enumeration operation might not execute."; public const string NamedSimpleType_InvalidDuplicateNamedSimpleTypeDelaration = "Simple type '{0}' has already be declared with different '{1}'."; public const string DataDom_Foliation = "Invalid foliation."; public const string DataDom_TableNameChange = "Cannot change the table name once the associated DataSet is mapped to a loaded XML document."; public const string DataDom_TableNamespaceChange = "Cannot change the table namespace once the associated DataSet is mapped to a loaded XML document."; public const string DataDom_ColumnNameChange = "Cannot change the column name once the associated DataSet is mapped to a loaded XML document."; public const string DataDom_ColumnNamespaceChange = "Cannot change the column namespace once the associated DataSet is mapped to a loaded XML document."; public const string DataDom_ColumnMappingChange = "Cannot change the ColumnMapping property once the associated DataSet is mapped to a loaded XML document."; public const string DataDom_TableColumnsChange = "Cannot add or remove columns from the table once the DataSet is mapped to a loaded XML document."; public const string DataDom_DataSetTablesChange = "Cannot add or remove tables from the DataSet once the DataSet is mapped to a loaded XML document."; public const string DataDom_DataSetNestedRelationsChange = "Cannot add, remove, or change Nested relations from the DataSet once the DataSet is mapped to a loaded XML document."; public const string DataDom_DataSetNull = "The DataSet parameter is invalid. It cannot be null."; public const string DataDom_DataSetNameChange = "Cannot change the DataSet name once the DataSet is mapped to a loaded XML document."; public const string DataDom_CloneNode = "This type of node cannot be cloned: {0}."; public const string DataDom_MultipleLoad = "Cannot load XmlDataDocument if it already contains data. Please use a new XmlDataDocument."; public const string DataDom_MultipleDataSet = "DataSet can be associated with at most one XmlDataDocument. Cannot associate the DataSet with the current XmlDataDocument because the DataSet is already associated with another XmlDataDocument."; public const string DataDom_NotSupport_GetElementById = "GetElementById() is not supported on DataDocument."; public const string DataDom_NotSupport_EntRef = "Cannot create entity references on DataDocument."; public const string DataDom_NotSupport_Clear = "Clear function on DateSet and DataTable is not supported on XmlDataDocument."; public const string ADP_EmptyArray = "Expecting non-empty array for '{0}' parameter."; public const string SQL_WrongType = "Expecting argument of type {1}, but received type {0}."; public const string ADP_InvalidConnectionOptionValue = "Invalid value for key '{0}'."; public const string ADP_KeywordNotSupported = "Keyword not supported: '{0}'."; public const string ADP_InternalProviderError = "Internal .Net Framework Data Provider error {0}."; public const string ADP_NoQuoteChange = "The QuotePrefix and QuoteSuffix properties cannot be changed once an Insert, Update, or Delete command has been generated."; public const string ADP_MissingSourceCommand = "The DataAdapter.SelectCommand property needs to be initialized."; public const string ADP_MissingSourceCommandConnection = "The DataAdapter.SelectCommand.Connection property needs to be initialized;"; public const string ADP_InvalidMultipartName = "{0} \"{1}\"."; public const string ADP_InvalidMultipartNameQuoteUsage = "{0} \"{1}\", incorrect usage of quotes."; public const string ADP_InvalidMultipartNameToManyParts = "{0} \"{1}\", the current limit of \"{2}\" is insufficient."; public const string ADP_ColumnSchemaExpression = "The column mapping from SourceColumn '{0}' failed because the DataColumn '{1}' is a computed column."; public const string ADP_ColumnSchemaMismatch = "Inconvertible type mismatch between SourceColumn '{0}' of {1} and the DataColumn '{2}' of {3}."; public const string ADP_ColumnSchemaMissing1 = "Missing the DataColumn '{0}' for the SourceColumn '{2}'."; public const string ADP_ColumnSchemaMissing2 = "Missing the DataColumn '{0}' in the DataTable '{1}' for the SourceColumn '{2}'."; public const string ADP_InvalidSourceColumn = "SourceColumn is required to be a non-empty string."; public const string ADP_MissingColumnMapping = "Missing SourceColumn mapping for '{0}'."; public const string ADP_NotSupportedEnumerationValue = "The {0} enumeration value, {1}, is not supported by the {2} method."; public const string ADP_MissingTableSchema = "Missing the '{0}' DataTable for the '{1}' SourceTable."; public const string ADP_InvalidSourceTable = "SourceTable is required to be a non-empty string"; public const string ADP_MissingTableMapping = "Missing SourceTable mapping: '{0}'"; public const string ADP_ConnectionRequired_Insert = "Update requires the InsertCommand to have a connection object. The Connection property of the InsertCommand has not been initialized."; public const string ADP_ConnectionRequired_Update = "Update requires the UpdateCommand to have a connection object. The Connection property of the UpdateCommand has not been initialized."; public const string ADP_ConnectionRequired_Delete = "Update requires the DeleteCommand to have a connection object. The Connection property of the DeleteCommand has not been initialized."; public const string ADP_ConnectionRequired_Batch = "Update requires a connection object. The Connection property has not been initialized."; public const string ADP_ConnectionRequired_Clone = "Update requires the command clone to have a connection object. The Connection property of the command clone has not been initialized."; public const string ADP_OpenConnectionRequired_Insert = "Update requires the {0}Command to have an open connection object. {1}"; public const string ADP_OpenConnectionRequired_Update = "Update requires the {0}Command to have an open connection object. {1}"; public const string ADP_OpenConnectionRequired_Delete = "Update requires the {0}Command to have an open connection object. {1}"; public const string ADP_OpenConnectionRequired_Clone = "Update requires the updating command to have an open connection object. {1}"; public const string ADP_MissingSelectCommand = "The SelectCommand property has not been initialized before calling '{0}'."; public const string ADP_UnwantedStatementType = "The StatementType {0} is not expected here."; public const string ADP_FillSchemaRequiresSourceTableName = "FillSchema: expected a non-empty string for the SourceTable name."; public const string ADP_FillRequiresSourceTableName = "Fill: expected a non-empty string for the SourceTable name."; public const string ADP_FillChapterAutoIncrement = "Hierarchical chapter columns must map to an AutoIncrement DataColumn."; public const string ADP_MissingDataReaderFieldType = "DataReader.GetFieldType({0}) returned null."; public const string ADP_OnlyOneTableForStartRecordOrMaxRecords = "Only specify one item in the dataTables array when using non-zero values for startRecords or maxRecords."; public const string ADP_UpdateRequiresSourceTable = "Update unable to find TableMapping['{0}'] or DataTable '{0}'."; public const string ADP_UpdateRequiresSourceTableName = "Update: expected a non-empty SourceTable name."; public const string ADP_UpdateRequiresCommandClone = "Update requires the command clone to be valid."; public const string ADP_UpdateRequiresCommandSelect = "Auto SQL generation during Update requires a valid SelectCommand."; public const string ADP_UpdateRequiresCommandInsert = "Update requires a valid InsertCommand when passed DataRow collection with new rows."; public const string ADP_UpdateRequiresCommandUpdate = "Update requires a valid UpdateCommand when passed DataRow collection with modified rows."; public const string ADP_UpdateRequiresCommandDelete = "Update requires a valid DeleteCommand when passed DataRow collection with deleted rows."; public const string ADP_UpdateMismatchRowTable = "DataRow[{0}] is from a different DataTable than DataRow[0]."; public const string ADP_RowUpdatedErrors = "RowUpdatedEvent: Errors occurred; no additional is information available."; public const string ADP_RowUpdatingErrors = "RowUpdatingEvent: Errors occurred; no additional is information available."; public const string ADP_ResultsNotAllowedDuringBatch = "When batching, the command's UpdatedRowSource property value of UpdateRowSource.FirstReturnedRecord or UpdateRowSource.Both is invalid."; public const string ADP_UpdateConcurrencyViolation_Update = "Concurrency violation: the UpdateCommand affected {0} of the expected {1} records."; public const string ADP_UpdateConcurrencyViolation_Delete = "Concurrency violation: the DeleteCommand affected {0} of the expected {1} records."; public const string ADP_UpdateConcurrencyViolation_Batch = "Concurrency violation: the batched command affected {0} of the expected {1} records."; public const string ADP_InvalidSourceBufferIndex = "Invalid source buffer (size of {0}) offset: {1}"; public const string ADP_InvalidDestinationBufferIndex = "Invalid destination buffer (size of {0}) offset: {1}"; public const string ADP_StreamClosed = "Invalid attempt to {0} when stream is closed."; public const string ADP_InvalidSeekOrigin = "Specified SeekOrigin value is invalid."; public const string ADP_DynamicSQLJoinUnsupported = "Dynamic SQL generation is not supported against multiple base tables."; public const string ADP_DynamicSQLNoTableInfo = "Dynamic SQL generation is not supported against a SelectCommand that does not return any base table information."; public const string ADP_DynamicSQLNoKeyInfoDelete = "Dynamic SQL generation for the DeleteCommand is not supported against a SelectCommand that does not return any key column information."; public const string ADP_DynamicSQLNoKeyInfoUpdate = "Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information."; public const string ADP_DynamicSQLNoKeyInfoRowVersionDelete = "Dynamic SQL generation for the DeleteCommand is not supported against a SelectCommand that does not contain a row version column."; public const string ADP_DynamicSQLNoKeyInfoRowVersionUpdate = "Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not contain a row version column."; public const string ADP_DynamicSQLNestedQuote = "Dynamic SQL generation not supported against table names '{0}' that contain the QuotePrefix or QuoteSuffix character '{1}'."; public const string SQL_InvalidBufferSizeOrIndex = "Buffer offset '{1}' plus the bytes available '{0}' is greater than the length of the passed in buffer."; public const string SQL_InvalidDataLength = "Data length '{0}' is less than 0."; public const string SqlMisc_NullString = "Null"; public const string SqlMisc_MessageString = "Message"; public const string SqlMisc_ArithOverflowMessage = "Arithmetic Overflow."; public const string SqlMisc_DivideByZeroMessage = "Divide by zero error encountered."; public const string SqlMisc_NullValueMessage = "Data is Null. This method or property cannot be called on Null values."; public const string SqlMisc_TruncationMessage = "Numeric arithmetic causes truncation."; public const string SqlMisc_DateTimeOverflowMessage = "SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM."; public const string SqlMisc_ConcatDiffCollationMessage = "Two strings to be concatenated have different collation."; public const string SqlMisc_CompareDiffCollationMessage = "Two strings to be compared have different collation."; public const string SqlMisc_InvalidFlagMessage = "Invalid flag value."; public const string SqlMisc_NumeToDecOverflowMessage = "Conversion from SqlDecimal to Decimal overflows."; public const string SqlMisc_ConversionOverflowMessage = "Conversion overflows."; public const string SqlMisc_InvalidDateTimeMessage = "Invalid SqlDateTime."; public const string SqlMisc_TimeZoneSpecifiedMessage = "A time zone was specified. SqlDateTime does not support time zones."; public const string SqlMisc_InvalidArraySizeMessage = "Invalid array size."; public const string SqlMisc_InvalidPrecScaleMessage = "Invalid numeric precision/scale."; public const string SqlMisc_FormatMessage = "The input wasn't in a correct format."; public const string SqlMisc_SqlTypeMessage = "SqlType error."; public const string SqlMisc_NoBufferMessage = "There is no buffer. Read or write operation failed."; public const string SqlMisc_BufferInsufficientMessage = "The buffer is insufficient. Read or write operation failed."; public const string SqlMisc_WriteNonZeroOffsetOnNullMessage = "Cannot write to non-zero offset, because current value is Null."; public const string SqlMisc_WriteOffsetLargerThanLenMessage = "Cannot write from an offset that is larger than current length. It would leave uninitialized data in the buffer."; public const string SqlMisc_NotFilledMessage = "SQL Type has not been loaded with data."; public const string SqlMisc_AlreadyFilledMessage = "SQL Type has already been loaded with data."; public const string SqlMisc_ClosedXmlReaderMessage = "Invalid attempt to access a closed XmlReader."; public const string SqlMisc_InvalidOpStreamClosed = "Invalid attempt to call {0} when the stream is closed."; public const string SqlMisc_InvalidOpStreamNonWritable = "Invalid attempt to call {0} when the stream non-writable."; public const string SqlMisc_InvalidOpStreamNonReadable = "Invalid attempt to call {0} when the stream non-readable."; public const string SqlMisc_InvalidOpStreamNonSeekable = "Invalid attempt to call {0} when the stream is non-seekable."; public const string ADP_DBConcurrencyExceptionMessage = "DB concurrency violation."; public const string ADP_InvalidMaxRecords = "The MaxRecords value of {0} is invalid; the value must be >= 0."; public const string ADP_CollectionIndexInt32 = "Invalid index {0} for this {1} with Count={2}."; public const string ADP_MissingTableMappingDestination = "Missing TableMapping when TableMapping.DataSetTable='{0}'."; public const string ADP_InvalidStartRecord = "The StartRecord value of {0} is invalid; the value must be >= 0."; public const string DataDom_EnforceConstraintsShouldBeOff = "Please set DataSet.EnforceConstraints == false before trying to edit XmlDataDocument using XML operations."; public const string DataColumns_RemoveExpression = "Cannot remove this column, because it is part of an expression: {0} = {1}."; public const string DataRow_RowInsertTwice = "The rowOrder value={0} has been found twice for table named '{1}'."; public const string Xml_ElementTypeNotFound = "Cannot find ElementType name='{0}'."; public const string ADP_ConnectionAlreadyOpen = "The connection was not closed. {0}"; public const string ADP_InternalConnectionError = "Internal DbConnection Error: {0}"; public const string ADP_InvalidOffsetValue = "Invalid parameter Offset value '{0}'. The value must be greater than or equal to 0."; public const string ADP_TransactionPresent = "Connection currently has transaction enlisted. Finish current transaction and retry."; public const string ADP_LocalTransactionPresent = "Cannot enlist in the transaction because a local transaction is in progress on the connection. Finish local transaction and retry."; public const string ADP_NoConnectionString = "The ConnectionString property has not been initialized."; public const string ADP_OpenConnectionPropertySet = "Not allowed to change the '{0}' property. {1}"; public const string ADP_PendingAsyncOperation = "Can not start another operation while there is an asynchronous operation pending."; public const string ADP_PooledOpenTimeout = "Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached."; public const string ADP_NonPooledOpenTimeout = "Timeout attempting to open the connection. The time period elapsed prior to attempting to open the connection has been exceeded. This may have occurred because of too many simultaneous non-pooled connection attempts."; public const string ADP_SingleValuedProperty = "The only acceptable value for the property '{0}' is '{1}'."; public const string ADP_DoubleValuedProperty = "The acceptable values for the property '{0}' are '{1}' or '{2}'."; public const string ADP_InvalidPrefixSuffix = "Specified QuotePrefix and QuoteSuffix values do not match."; public const s
System.Runtime.Serialization.dll
Decompiled 6 months ago
The result has been truncated due to the large size, download it to view full contents!
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.Configuration; 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; [assembly: CompilationRelaxations(8)] [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.6.57.0")] [assembly: AssemblyFileVersion("4.6.57.0")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyKeyFile("../ecma.pub")] [assembly: AllowPartiallyTrustedCallers] [assembly: ComCompatibleVersion(1, 0, 3300, 0)] [assembly: SecurityCritical(SecurityCriticalScope.Explicit)] [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<TArgument, TArray> { 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<string, bool> { 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<XmlDictionaryString, bool> { 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<string, short> { 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<XmlDictionaryString, short> { 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<string, int> { 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<XmlDictionaryString, int> { 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<string, long> { 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<XmlDictionaryString, long> { 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<string, float> { 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<XmlDictionaryString, float> { 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<string, double> { 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<XmlDictionaryString, double> { 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<string, decimal> { 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<XmlDictionaryString, decimal> { 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<string, DateTime> { 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<XmlDictionaryString, DateTime> { 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<string, Guid> { 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<XmlDictionaryString, Guid> { 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<string, TimeSpan> { 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<XmlDictionaryString, TimeSpan> { 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<byte> 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<byte>(buffer, offset, count); } CheckUTF8DeclarationEncoding(buffer, offset, count, supportedEncoding2, supportedEncoding); return new ArraySegment<byte>(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<byte>(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 Nam