Decompiled source of CloverAPI v0.2.1
plugins/CloverAPI.dll
Decompiled 2 weeks 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.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Numerics; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using CloverAPI.Assets; using CloverAPI.Classes; using CloverAPI.Classes.Interfaces; using CloverAPI.Content.Audio; using CloverAPI.Content.Builders; using CloverAPI.Content.Charms; using CloverAPI.Content.Data; using CloverAPI.Content.Settings; using CloverAPI.Content.Strings; using CloverAPI.Content.Textures; using CloverAPI.Internal; using CloverAPI.SaveData; using CloverAPI.Utils; using Cysharp.Threading.Tasks; using Cysharp.Threading.Tasks.CompilerServices; using HarmonyLib; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Panik; using TMPro; using UnityEngine; using UnityEngine.Networking; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyCompany("CloverAPI")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+063ae6889603213608ea6b82b49f8f3dc7dac3f0")] [assembly: AssemblyProduct("CloverAPI")] [assembly: AssemblyTitle("CloverAPI")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace CloverAPI { public static class Logging { public static ManualLogSource Logger => Plugin.Log; public static void Log(LogLevel level, object message) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) Logger.Log(level, message); } public static void LogInfo(object message) { Logger.LogInfo(message); } public static void LogDebug(object message) { Logger.LogDebug(message); } public static void LogWarning(object message) { Logger.LogWarning(message); } public static void LogError(object message) { Logger.LogError(message); } public static void LogFatal(object message) { Logger.LogFatal(message); } } [BepInPlugin("ModdingAPIs.cloverpit.CloverAPI", "Clover API", "0.2.1")] [HarmonyPatch] public class Plugin : BaseUnityPlugin { public const string PluginGuid = "ModdingAPIs.cloverpit.CloverAPI"; public const string PluginName = "Clover API"; public const string PluginVer = "0.2.1"; internal const string MainContentFolder = "CloverAPI_Content"; private const int FONT_SIZE = 16; internal static ManualLogSource Log; internal static readonly Harmony Harmony = new Harmony("ModdingAPIs.cloverpit.CloverAPI"); internal static string PluginPath; internal static ConfigEntry<bool> EnableDebugKeys; internal static ConfigEntry<bool> UseFullQualityTextures; internal static ConfigEntry<string> OverrideOrdering; public static string DataPath { get; private set; } public static string ImagePath { get; private set; } private void Awake() { Log = ((BaseUnityPlugin)this).Logger; PluginPath = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location); DataPath = Path.Combine(PluginPath, "CloverAPI_Content", "Data"); ImagePath = Path.Combine(PluginPath, "CloverAPI_Content", "Images"); MakeConfig(); LoadAssets(); GameUtils.OnGameReady += OnReady; PersistentDataManager.RegisterData("CharmMappings", CharmMappings.Instance); PersistentDataManager.RegisterData("CharmData", AllCharmData.Instance); } private void Update() { if (!EnableDebugKeys.Value) { return; } int num = 1; if (Input.GetKey((KeyCode)304) || Input.GetKey((KeyCode)303)) { num *= 10; } if (Input.GetKey((KeyCode)306) || Input.GetKey((KeyCode)305)) { num *= 100; } if (Input.GetKey((KeyCode)308) || Input.GetKey((KeyCode)307)) { num *= 1000; } if (Input.GetKeyDown((KeyCode)282)) { GameplayData.CoinsAdd((BigInteger)num, false); } if (Input.GetKeyDown((KeyCode)283)) { GameplayData.CloverTicketsAdd((long)num, false); } if (Input.GetKeyDown((KeyCode)284)) { PowerupScript[] array = (from x in CharmManager.CustomCharms.Pick(4) select PowerupScript.GetPowerup_Quick(x.id)).ToArray(); if (array.Length < 4) { array = array.Concat(Enumerable.Repeat<PowerupScript>(null, 4 - array.Length)).ToArray(); } StoreCapsuleScript.Restock(false, true, array, false, false); } } private void OnReady() { LoadData(); } private void OnEnable() { Harmony.PatchAll(); Logging.LogInfo("Loaded Clover API!"); } private void OnDisable() { Harmony.UnpatchSelf(); Logging.LogInfo("Unloaded Clover API!"); } private void MakeConfig() { EnableDebugKeys = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "EnableDebugKeys", false, "If true, enables debug keybinds for testing purposes."); UseFullQualityTextures = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "UseFullQualityTextures", true, "If true, uses full quality textures for modded content. If false, resizes them to match the size of the original texture. Some textures require a restart to take effect."); ModSettingsManager.RegisterPageFromConfig((BaseUnityPlugin)(object)this, "Clover API Settings"); OverrideOrdering = ((BaseUnityPlugin)this).Config.Bind<string>("General", "OverrideOrdering", "", "A comma-separated list of mod GUIDs that specifies the order in which overrides are applied. The leftmost mod in the list has the highest priority. Mods that have conflicting overrides will automatically be added to the end."); ResourceOrdering._ConfigRef(OverrideOrdering); } private void LoadAssets() { string text = Path.Combine(PluginPath, DataPath, "templatemodel"); if (File.Exists(text)) { APIAssets._assetBundle = AssetBundle.LoadFromFile(text); return; } Logging.LogError("AssetBundle not found at " + text + "!"); Logging.LogError("Make sure you have the '" + DataPath + "' folder in the same directory as the plugin DLL with the 'templatemodel' AssetBundle inside it."); } private void LoadData() { LoadTranslations(); } private void LoadTranslations() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) string[] files = Directory.GetFiles(PluginPath, "*.loc", SearchOption.AllDirectories); string[] array = files; for (int i = 0; i < array.Length; i++) { LanguageManager.LoadFromFile(array[i]); } if (files.Length != 0) { Logging.LogInfo($"Loaded {files.Length} translation files."); } } } } namespace CloverAPI.Utils { public static class AssetBundleUtils { private static readonly Dictionary<string, AssetBundle> LoadedAssetBundles = new Dictionary<string, AssetBundle>(); public static GameObject InstantiateCustomModelCharm(string assetBundleName, string prefabName = null) { return Object.Instantiate<GameObject>(AssetBundleUtils.LoadFromAssetBundle<GameObject>(assetBundleName, prefabName)); } public static T LoadFromAssetBundle<T>(string assetBundleName, string assetName = null) where T : Object { string text = FileUtils.FindFile(assetBundleName); AssetBundle val = LoadAssetBundle(text); if ((Object)(object)val == (Object)null) { Logging.LogError("Could not load AssetBundle from path: " + text); return default(T); } if (string.IsNullOrEmpty(assetName)) { T[] array = val.LoadAllAssets<T>(); if (array.Length != 0) { if (array.Length > 1) { Logging.LogWarning($"Multiple assets of type {typeof(T)} found in AssetBundle '{assetBundleName}'. Using the first one found: '{((Object)array[0]).name}'."); } return array[0]; } Logging.LogError($"No assets of type {typeof(T)} found in AssetBundle '{assetBundleName}'."); PrintContentsOfAssetBundle(val); return default(T); } T val2 = val.LoadAsset<T>(assetName); if ((Object)(object)val2 == (Object)null) { Logging.LogError($"Could not find asset '{assetName}' of type {typeof(T)} in AssetBundle '{assetBundleName}'."); PrintContentsOfAssetBundle(val); return default(T); } return val2; } public static AssetBundle LoadAssetBundle(string path) { if (LoadedAssetBundles.TryGetValueNoCase(path, out var value)) { return value; } AssetBundle val = AssetBundle.LoadFromFile(path); if ((Object)(object)val == (Object)null) { Logging.LogError("Failed to load AssetBundle from path: " + path); return null; } LoadedAssetBundles[path] = val; return val; } public static void PrintContentsOfAssetBundle(AssetBundle assetBundle) { string[] allAssetNames = assetBundle.GetAllAssetNames(); Logging.LogInfo("AssetBundle contains the following assets:"); string[] array = allAssetNames; foreach (string text in array) { Logging.LogInfo("- " + text); } } } public static class AudioUtils { public static AudioClip LoadAudioFromFile(string filePath, string onNotFound = "error", string onMultipleFound = "warn") { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Invalid comparison between Unknown and I4 string text = FileUtils.FindFile(filePath, onNotFound, onMultipleFound); if (!File.Exists(text)) { throw new FileNotFoundException("File '" + filePath + "' not found."); } UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip("file://" + text, (AudioType)0); audioClip.SendWebRequest(); while (!audioClip.isDone) { } if ((int)audioClip.result == 1) { AudioClip content = DownloadHandlerAudioClip.GetContent(audioClip); audioClip.Dispose(); return content; } Logging.LogError("Failed to load audio clip from file '" + filePath + "': " + audioClip.error); audioClip.Dispose(); return null; } } public class FileUtils { public static string[] FindFiles(string fileName) { if (Path.IsPathRooted(fileName)) { if (File.Exists(fileName)) { return new string[1] { fileName }; } return Array.Empty<string>(); } return Directory.GetFiles(Paths.PluginPath, fileName, SearchOption.AllDirectories); } public static string FindFile(string fileName, string onNotFound = "error", string onMultipleFound = "warn") { string[] array = FindFiles(fileName); if (array.Length < 1) { if (onNotFound == "error") { throw new FileNotFoundException("File '" + fileName + "' not found in plugin directory."); } if (onNotFound == "warn") { Logging.LogWarning("File '" + fileName + "' not found in plugin directory."); } return null; } if (array.Length > 1) { if (onMultipleFound == "error") { throw new Exception("Multiple files named '" + fileName + "' found in plugin directory."); } if (onMultipleFound == "warn") { Logging.LogWarning("Multiple files named '" + fileName + "' found. Using the first one found at '" + array[0] + "'."); } } return array[0]; } public static byte[] LoadFileBytes(string filePath, string onNotFound = "error", string onMultipleFound = "warn") { string path = FindFile(filePath, onNotFound, onMultipleFound); if (!File.Exists(path)) { throw new FileNotFoundException("File '" + filePath + "' not found."); } return File.ReadAllBytes(path); } } public class GameUtils { public static bool GameReady { get; internal set; } = false; public static event Action OnGameReady; internal static void TriggerGameReady() { GameReady = true; GameUtils.OnGameReady(); } static GameUtils() { GameUtils.OnGameReady = delegate { }; } } public static class LinqExtensions { public static T MaxBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> selector) where TKey : IComparable<TKey> { using IEnumerator<T> enumerator = source.GetEnumerator(); if (!enumerator.MoveNext()) { throw new InvalidOperationException("Sequence contains no elements"); } T val = enumerator.Current; TKey other = selector(val); while (enumerator.MoveNext()) { T current = enumerator.Current; TKey val2 = selector(current); if (val2.CompareTo(other) > 0) { val = current; other = val2; } } return val; } public static bool TryGetValueNoCase<TValue>(this IDictionary<string, TValue> dictionary, string key, out TValue value) { foreach (KeyValuePair<string, TValue> item in dictionary) { if (string.Equals(item.Key, key, StringComparison.OrdinalIgnoreCase)) { value = item.Value; return true; } } value = default(TValue); return false; } } public class MathUtils { public static float RoundToMultipleOf(float value, float multiple) { if (multiple == 0f) { throw new ArgumentException("Multiple cannot be zero.", "multiple"); } return (float)(Math.Round(value / multiple) * (double)multiple); } public static float RoundToNearestSignificantFive(float value, int unroundedSignificantDigits = 1) { if (value == 0f) { return 0f; } float num = (float)Math.Pow(10.0, Math.Floor(Math.Log10(Math.Abs(value))) + 1.0 - (double)unroundedSignificantDigits); return RoundToMultipleOf(value, 0.5f * num); } public static float RoundToNearestSignificant(float value, int significantDigits = 1) { if (value == 0f) { return 0f; } float num = (float)Math.Pow(10.0, Math.Floor(Math.Log10(Math.Abs(value))) + 1.0 - (double)significantDigits); return (float)(Math.Round(value / num) * (double)num); } } public static class RandomUtils { public static IList<T> Pick<T>(this IList<T> list, int count) { if (count == 1) { return new List<T> { list.Pick() }; } if (list == null) { throw new ArgumentNullException("list", "The list cannot be null."); } if (list.Count == 0) { throw new ArgumentException("The list cannot be empty.", "list"); } if (count > list.Count) { count = list.Count; } HashSet<int> hashSet = new HashSet<int>(); while (hashSet.Count < count) { int item = Random.Range(0, list.Count); hashSet.Add(item); } List<T> list2 = new List<T>(); foreach (int item2 in hashSet) { list2.Add(list[item2]); } return list2; } public static T Pick<T>(this IList<T> list) { if (list == null) { throw new ArgumentNullException("list", "The list cannot be null."); } if (list.Count == 0) { throw new ArgumentException("The list cannot be empty.", "list"); } int index = Random.Range(0, list.Count); return list[index]; } } public static class TextureUtils { public static Texture2D LoadTextureFromFile(string filePath, FilterMode filterMode = 0, string onNotFound = "error", string onMultipleFound = "warn") { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Expected O, but got Unknown Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false); byte[] array = FileUtils.LoadFileBytes(filePath, onNotFound, onMultipleFound); if (!ImageConversion.LoadImage(val, array)) { throw new Exception("Failed to load texture from file '" + filePath + "'. The file may not be a valid image."); } ((Texture)val).filterMode = filterMode; ((Object)val).name = Path.GetFileNameWithoutExtension(filePath); return val; } public static Texture2D ResizeTexture(Texture2D original, int width, int height) { //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_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown RenderTexture val = (RenderTexture.active = RenderTexture.GetTemporary(width, height)); Graphics.Blit((Texture)(object)original, val); Texture2D val2 = new Texture2D(width, height); val2.ReadPixels(new Rect(0f, 0f, (float)width, (float)height), 0, 0); val2.Apply(); RenderTexture.active = null; RenderTexture.ReleaseTemporary(val); return val2; } public static Texture2D CopyTexture(Texture2D original) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown //IL_0075: Unknown result type (might be due to invalid IL or missing references) Texture2D val = new Texture2D(((Texture)original).width, ((Texture)original).height, original.format, ((Texture)original).mipmapCount > 1); if (((Texture)original).isReadable) { val.SetPixels(original.GetPixels()); val.Apply(); return val; } RenderTexture val2 = (RenderTexture.active = RenderTexture.GetTemporary(((Texture)original).width, ((Texture)original).height)); Graphics.Blit((Texture)(object)original, val2); val.ReadPixels(new Rect(0f, 0f, (float)((Texture)original).width, (float)((Texture)original).height), 0, 0); val.Apply(); RenderTexture.active = null; RenderTexture.ReleaseTemporary(val2); return val; } } } namespace CloverAPI.SaveData { public class AllCharmData : JsonPersistentData { public static AllCharmData Instance = new AllCharmData(); [JsonProperty] internal Dictionary<string, CharmData> Entries = new Dictionary<string, CharmData>(); public CharmData this[string guid] { get { return GetCharmDataByGUID(guid); } set { SetCharmDataByGuid(guid, value); } } public CharmData this[Identifier id] { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return GetCharmDataByID(id); } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) SetCharmDataById(id, value); } } public CharmData GetCharmDataByGUID(string guid) { if (!Entries.TryGetValueNoCase(guid, out var value)) { value = new CharmData(); Entries[guid] = value; } return value; } public CharmData GetCharmDataByID(Identifier id) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) if (CharmManager.IdToGUID.TryGetValue(id, out var value)) { return GetCharmDataByGUID(value); } return null; } public bool HasCharmDataByGuid(string guid) { return Entries.ContainsKey(guid); } public bool HasCharmDataById(Identifier id) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) if (CharmManager.IdToGUID.TryGetValue(id, out var value)) { return HasCharmDataByGuid(value); } return false; } public void RemoveCharmDataByGuid(string guid) { Entries.Remove(guid); } public void RemoveCharmDataById(Identifier id) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) if (CharmManager.IdToGUID.TryGetValue(id, out var value)) { RemoveCharmDataByGuid(value); } } public void SetCharmDataByGuid(string guid, CharmData data) { Entries[guid] = data; } public void SetCharmDataById(Identifier id, CharmData data) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) if (CharmManager.IdToGUID.TryGetValue(id, out var value)) { SetCharmDataByGuid(value, data); } } public override void OnReset() { Entries.Clear(); } } public class CharmData { [JsonProperty] internal Dictionary<string, object> Data = new Dictionary<string, object>(); public T Get<T>(string key, T defaultValue = default(T)) { if (Data.TryGetValueNoCase(key, out var value)) { if (value is T) { return (T)value; } T val = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(value)); if (val != null) { return val; } return defaultValue; } return defaultValue; } public string GetString(string key, string defaultValue = null) { return Get(key, defaultValue); } public int GetInt(string key, int defaultValue = 0) { return Get(key, defaultValue); } public float GetFloat(string key, float defaultValue = 0f) { return Get(key, defaultValue); } public bool GetBool(string key, bool defaultValue = false) { return Get(key, defaultValue); } public BigInteger GetBigInteger(string key, BigInteger defaultValue = default(BigInteger)) { return Get(key, defaultValue); } public List<T> GetList<T>(string key, List<T> defaultValue = null) { return Get(key, defaultValue ?? new List<T>()); } public T[] GetArray<T>(string key, T[] defaultValue = null) { return Get(key, defaultValue ?? Array.Empty<T>()); } public Dictionary<TKey, TValue> GetDictionary<TKey, TValue>(string key, Dictionary<TKey, TValue> defaultValue = null) { return Get(key, defaultValue ?? new Dictionary<TKey, TValue>()); } public void Set<T>(string key, T value) { Data[key] = value; } public void Remove(string key) { Data.Remove(key); } public bool ContainsKey(string key) { return Data.ContainsKey(key); } } } namespace CloverAPI.Patches { [HarmonyPatch] public class AudioPatcher { [HarmonyPatch(typeof(AssetMaster), "GetSound")] [HarmonyPrefix] internal static bool AssetMaster_GetSound_Prefix(ref AudioClip __result, ref string clipName) { if (AudioManager.TryGetSoundOverride(clipName, out var audioClip)) { __result = audioClip; return false; } return true; } [HarmonyPatch(typeof(AssetMaster), "GetMusic")] [HarmonyPrefix] internal static bool AssetMaster_GetMusic_Prefix(ref AudioClip __result, ref string clipName) { if (AudioManager.TryGetMusicOverride(clipName, out var audioClip)) { __result = audioClip; return false; } return true; } } [HarmonyPatch] internal class CharmPatcher { [CompilerGenerated] private sealed class <PowerupScript_InitializeAll_Transpiler>d__0 : IEnumerable<CodeInstruction>, IEnumerable, IEnumerator<CodeInstruction>, IDisposable, IEnumerator { private int <>1__state; private CodeInstruction <>2__current; private int <>l__initialThreadId; private IEnumerable<CodeInstruction> instructions; public IEnumerable<CodeInstruction> <>3__instructions; private IEnumerator<CodeInstruction> <enumerator>5__2; private bool <done>5__3; private CodeInstruction <instruction>5__4; CodeInstruction IEnumerator<CodeInstruction>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <PowerupScript_InitializeAll_Transpiler>d__0(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { <enumerator>5__2 = null; <instruction>5__4 = null; <>1__state = -2; } private bool MoveNext() { //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Expected O, but got Unknown //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Expected O, but got Unknown switch (<>1__state) { default: return false; case 0: <>1__state = -1; <enumerator>5__2 = instructions.GetEnumerator(); <done>5__3 = false; goto IL_00b9; case 1: <>1__state = -1; if (!(<instruction>5__4.opcode == OpCodes.Ldc_I4) || !(<instruction>5__4.operand is int num) || num != 163) { <instruction>5__4 = null; goto IL_00b9; } goto IL_01ab; case 2: <>1__state = -1; if (<instruction>5__4.opcode == OpCodes.Callvirt && <instruction>5__4.operand is MethodInfo methodInfo && methodInfo == AccessTools.Method(typeof(PowerupScript), "Initialize", (Type[])null, (Type[])null)) { <>2__current = new CodeInstruction(OpCodes.Ldarg_1, (object)null); <>1__state = 3; return true; } <instruction>5__4 = null; goto IL_01ab; case 3: <>1__state = -1; <>2__current = new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(CharmPatcher), "InitCustomCharms", (Type[])null, (Type[])null)); <>1__state = 4; return true; case 4: <>1__state = -1; <done>5__3 = true; break; case 5: { <>1__state = -1; break; } IL_00b9: if (<enumerator>5__2.MoveNext()) { <instruction>5__4 = <enumerator>5__2.Current; <>2__current = <instruction>5__4; <>1__state = 1; return true; } goto IL_01ab; IL_01ab: if (<enumerator>5__2.MoveNext()) { <instruction>5__4 = <enumerator>5__2.Current; <>2__current = <instruction>5__4; <>1__state = 2; return true; } break; } if (<enumerator>5__2.MoveNext()) { <>2__current = <enumerator>5__2.Current; <>1__state = 5; return true; } if (!<done>5__3) { Logging.LogError("Failed to apply PowerupScript.InitializeAll transpiler patch!"); } <enumerator>5__2.Dispose(); return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<CodeInstruction> IEnumerable<CodeInstruction>.GetEnumerator() { <PowerupScript_InitializeAll_Transpiler>d__0 <PowerupScript_InitializeAll_Transpiler>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <PowerupScript_InitializeAll_Transpiler>d__ = this; } else { <PowerupScript_InitializeAll_Transpiler>d__ = new <PowerupScript_InitializeAll_Transpiler>d__0(0); } <PowerupScript_InitializeAll_Transpiler>d__.instructions = <>3__instructions; return <PowerupScript_InitializeAll_Transpiler>d__; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<CodeInstruction>)this).GetEnumerator(); } } [CompilerGenerated] private sealed class <ReplaceILCharmCounts>d__3 : IEnumerable<CodeInstruction>, IEnumerable, IEnumerator<CodeInstruction>, IDisposable, IEnumerator { private int <>1__state; private CodeInstruction <>2__current; private int <>l__initialThreadId; private int replaceAmount; public int <>3__replaceAmount; private int expectedAmountSeen; public int <>3__expectedAmountSeen; private string caller; public string <>3__caller; private IEnumerable<CodeInstruction> instructions; public IEnumerable<CodeInstruction> <>3__instructions; private string onNotFound; public string <>3__onNotFound; private string onMultipleFound; public string <>3__onMultipleFound; private int <seen>5__2; private IEnumerator<CodeInstruction> <>7__wrap2; CodeInstruction IEnumerator<CodeInstruction>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <ReplaceILCharmCounts>d__3(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || (uint)(num - 1) <= 2u) { try { } finally { <>m__Finally1(); } } <>7__wrap2 = null; <>1__state = -2; } private bool MoveNext() { //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Expected O, but got Unknown try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; if (replaceAmount < 1 || expectedAmountSeen < 1) { Logging.LogError("Invalid arguments to ReplaceILCharmCounts in '" + caller + "'. Both replaceAmount and expectedAmountSeen must be at least 1."); replaceAmount = Mathf.Max(1, replaceAmount); expectedAmountSeen = Mathf.Max(1, expectedAmountSeen); } <seen>5__2 = 0; <>7__wrap2 = instructions.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; goto IL_014c; case 2: <>1__state = -3; goto IL_014c; case 3: { <>1__state = -3; break; } IL_014c: <seen>5__2++; break; } if (<>7__wrap2.MoveNext()) { CodeInstruction current = <>7__wrap2.Current; if (current.opcode == OpCodes.Ldc_I4 && current.operand is int num && num == 164) { if (<seen>5__2 < replaceAmount) { <>2__current = new CodeInstruction(OpCodes.Call, (object)AccessTools.PropertyGetter(typeof(CharmManager), "NewCount")); <>1__state = 1; return true; } <>2__current = current; <>1__state = 2; return true; } <>2__current = current; <>1__state = 3; return true; } <>m__Finally1(); <>7__wrap2 = null; if (<seen>5__2 < expectedAmountSeen) { if (expectedAmountSeen == 1) { if (onNotFound == "error") { Logging.LogError($"Transpiler patch in '{caller}' failed to replace any instances of 'ldc.i4 {164}'!"); } else if (onNotFound == "warn") { Logging.LogWarning($"Transpiler patch in '{caller}' failed to replace any instances of 'ldc.i4 {164}'!"); } } else if (onNotFound == "error") { Logging.LogError($"Transpiler patch in '{caller}' replaced only {<seen>5__2} instances of 'ldc.i4 {164}'. Expected to replace exactly {expectedAmountSeen} instances, but could be fine if an update changed this."); } else if (onNotFound == "warn") { Logging.LogWarning($"Transpiler patch in '{caller}' replaced only {<seen>5__2} instances of 'ldc.i4 {164}'. Expected to replace exactly {expectedAmountSeen} instances, but could be fine if an update changed this."); } } if (<seen>5__2 > expectedAmountSeen) { if (onMultipleFound == "error") { Logging.LogError(string.Format("Transpiler patch in '{0}' replaced {1} instances of 'ldc.i4 {2}'. Expected to replace exactly {3} instance{4}!", caller, <seen>5__2, 164, expectedAmountSeen, (expectedAmountSeen == 1) ? "" : "s")); } else if (onMultipleFound == "warn") { Logging.LogWarning(string.Format("Transpiler patch in '{0}' replaced {1} instances of 'ldc.i4 {2}'. Expected to replace exactly {3} instance{4}!", caller, <seen>5__2, 164, expectedAmountSeen, (expectedAmountSeen == 1) ? "" : "s")); } } return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap2 != null) { <>7__wrap2.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<CodeInstruction> IEnumerable<CodeInstruction>.GetEnumerator() { <ReplaceILCharmCounts>d__3 <ReplaceILCharmCounts>d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; <ReplaceILCharmCounts>d__ = this; } else { <ReplaceILCharmCounts>d__ = new <ReplaceILCharmCounts>d__3(0); } <ReplaceILCharmCounts>d__.instructions = <>3__instructions; <ReplaceILCharmCounts>d__.onNotFound = <>3__onNotFound; <ReplaceILCharmCounts>d__.onMultipleFound = <>3__onMultipleFound; <ReplaceILCharmCounts>d__.replaceAmount = <>3__replaceAmount; <ReplaceILCharmCounts>d__.expectedAmountSeen = <>3__expectedAmountSeen; <ReplaceILCharmCounts>d__.caller = <>3__caller; return <ReplaceILCharmCounts>d__; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<CodeInstruction>)this).GetEnumerator(); } } [IteratorStateMachine(typeof(<PowerupScript_InitializeAll_Transpiler>d__0))] [HarmonyPatch(typeof(PowerupScript), "InitializeAll")] [HarmonyTranspiler] internal static IEnumerable<CodeInstruction> PowerupScript_InitializeAll_Transpiler(IEnumerable<CodeInstruction> instructions) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <PowerupScript_InitializeAll_Transpiler>d__0(-2) { <>3__instructions = instructions }; } [HarmonyPatch(typeof(GameplayData), "_EnsurePowerupDataArray")] [HarmonyTranspiler] internal static IEnumerable<CodeInstruction> GameplayData__EnsurePowerupDataArray_Transpiler(IEnumerable<CodeInstruction> instructions) { return ReplaceILCharmCounts(instructions, "error", "warn", 1, 1, "GameplayData._EnsurePowerupDataArray"); } [HarmonyPatch(typeof(TerminalScript), "Initialize")] [HarmonyTranspiler] internal static IEnumerable<CodeInstruction> TerminalScript_Initialize_Transpiler(IEnumerable<CodeInstruction> instructions) { return ReplaceILCharmCounts(instructions, "error", "warn", 1, 2, "TerminalScript.Initialize"); } [IteratorStateMachine(typeof(<ReplaceILCharmCounts>d__3))] private static IEnumerable<CodeInstruction> ReplaceILCharmCounts(IEnumerable<CodeInstruction> instructions, string onNotFound = "error", string onMultipleFound = "warn", int replaceAmount = 1, int expectedAmountSeen = 1, string caller = "unknown") { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <ReplaceILCharmCounts>d__3(-2) { <>3__instructions = instructions, <>3__onNotFound = onNotFound, <>3__onMultipleFound = onMultipleFound, <>3__replaceAmount = replaceAmount, <>3__expectedAmountSeen = expectedAmountSeen, <>3__caller = caller }; } private static void InitCustomCharms(bool isNewGame) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) foreach (CharmBuilder customCharm in CharmManager.CustomCharms) { CharmManager.SpawnCustomCharm(customCharm.id, isNewGame); } } } [HarmonyPatch] public class GamePatcher { [HarmonyPatch(typeof(IntroScript), "Start")] [HarmonyPrefix] internal static void IntroScript_Start_Prefix() { GameUtils.TriggerGameReady(); } [HarmonyPatch(/*Could not decode attribute arguments.*/)] [HarmonyPrefix] internal static bool Master__PlatformKind_Get_Prefix(ref PlatformKind __result) { __result = (PlatformKind)0; return false; } } [HarmonyPatch] internal class SavePatcher { [HarmonyPatch(typeof(Data), "SaveGame")] [HarmonyPrefix] internal static void Data_SaveGame_Postfix() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) UniTaskExtensions.Forget<bool>(PersistentDataManager.SaveData()); } [HarmonyPatch(typeof(Data), "LoadGame")] [HarmonyPostfix] internal static void Data_LoadGame_Postfix() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) UniTaskExtensions.Forget<bool>(PersistentDataManager.LoadData()); } [HarmonyPatch(typeof(GameData), "GameplayDataReset")] [HarmonyPostfix] internal static void Data_GameData_GameplayDataReset_Postfix(GameData __instance) { PersistentDataManager.ResetAll(); } [HarmonyPatch(typeof(PlatformDataMaster), "PathGet_GameDataFile")] [HarmonyPostfix] internal static void PlatformDataMaster_PathGet_GameDataFile_Postfix(ref string __result, string extraAppendix) { string text = PlatformDataMaster.GameFolderPath + "GameDataModded" + extraAppendix + ".json"; if (!File.Exists(text) && File.Exists(__result)) { File.Copy(__result, text); } __result = text; } } internal static class HubState { public enum View { None, HubIndex, Page } public static View Current = View.None; public static int HubPageOffset = 0; public static int PageItemOffset = 0; public static int ActivePage = -1; public static void Reset() { Current = View.None; HubPageOffset = 0; PageItemOffset = 0; ActivePage = -1; } } [HarmonyPatch] internal static class MainMenu_Patches { private readonly struct HubLayout { public int Capacity { get; } public int ListSlots { get; } public int NextRow { get; } public int BackRow { get; } public int Step { get; } public HubLayout(int capacity) { Capacity = capacity; BackRow = capacity - 1; NextRow = ((capacity >= 2) ? (capacity - 2) : (-1)); ListSlots = Mathf.Max(0, capacity - 2); Step = Math.Max(1, ListSlots); } } private const int ModsSlotWithoutTwitch = 4; private const int ModsSlotWithTwitch = 5; private static bool _rowValidationLogged; private static readonly FieldInfo DesiredNavigationIndexField = AccessTools.Field(typeof(MainMenuScript), "desiredNavigationIndex"); private static readonly FieldInfo ControllerElementsField = AccessTools.Field(typeof(DiegeticMenuController), "elements"); private static readonly FieldInfo RightNavigationPressField = AccessTools.Field(typeof(MainMenuScript), "rightNavigationPress"); private static readonly FieldInfo LeftNavigationPressField = AccessTools.Field(typeof(MainMenuScript), "leftNavigationPress"); private static readonly FieldInfo MenuIndexField = AccessTools.Field(typeof(MainMenuScript), "menuIndex"); private static bool IsInHub() { return HubState.Current != HubState.View.None; } private static bool HasPages() { return ModSettingsManager.Pages.Count > 0; } private static int GetModsSlotIndex() { if (!TwitchMaster.IsTwitchSupported()) { return 4; } return 5; } private static int GetBackSlotIndex() { return GetModsSlotIndex() + 1; } private static void SetDesiredNavigationIndex(MainMenuScript menu, int value) { DesiredNavigationIndexField?.SetValue(menu, value); } private static MenuIndex GetMenuIndex(MainMenuScript menu) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) if (MenuIndexField == null) { return (MenuIndex)(-1); } object value = MenuIndexField.GetValue(menu); if (value is MenuIndex) { return (MenuIndex)value; } return (MenuIndex)(-1); } private static void SetMenuIndex(MainMenuScript menu, MenuIndex value) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) MenuIndexField?.SetValue(menu, value); } private static List<DiegeticMenuElement>? GetElementsList(DiegeticMenuController? controller) { if ((Object)(object)controller == (Object)null || ControllerElementsField == null) { return null; } return ControllerElementsField.GetValue(controller) as List<DiegeticMenuElement>; } private static bool GetFlag(FieldInfo field, MainMenuScript menu) { bool flag = default(bool); int num; if (field != null && (Object)(object)menu != (Object)null) { object value = field.GetValue(menu); if (value is bool) { flag = (bool)value; num = 1; } else { num = 0; } } else { num = 0; } return (byte)((uint)num & (flag ? 1u : 0u)) != 0; } private static void SetTextSafe(TextMeshProUGUI[] texts, int index, string? value) { if (texts != null && index >= 0 && index < texts.Length && (Object)(object)texts[index] != (Object)null) { ((TMP_Text)texts[index]).text = value ?? string.Empty; } } private static DiegeticMenuElement? GetMenuElement(MainMenuScript? menu, int index) { if (menu?.menuElements == null || index < 0 || index >= menu.menuElements.Length) { return null; } return menu.menuElements[index]; } private static bool TryGetOptionTexts(MainMenuScript menu, out TextMeshProUGUI[] optionTexts) { if (menu?.optionTexts == null || menu.optionTexts.Length == 0) { optionTexts = Array.Empty<TextMeshProUGUI>(); return false; } optionTexts = menu.optionTexts; return true; } private static bool TryGetHubLayout(MainMenuScript menu, out HubLayout layout) { layout = default(HubLayout); if ((Object)(object)menu == (Object)null) { return false; } int num = VisibleCapacity(menu); if (num <= 0) { return false; } layout = new HubLayout(num); return true; } private static bool TryGetActivePage(out ModSettingsManager.Page page) { int activePage = HubState.ActivePage; if (activePage >= 0 && activePage < ModSettingsManager.Pages.Count) { page = ModSettingsManager.Pages[activePage]; return true; } page = null; return false; } private static void RenderListEntries(TextMeshProUGUI[] optionTexts, int listSlots, int start, int total, Func<int, string> labelSelector) { int i = 0; int num = start; while (num < total && i < listSlots) { SetTextSafe(optionTexts, i, labelSelector(num)); num++; i++; } for (; i < listSlots; i++) { SetTextSafe(optionTexts, i, string.Empty); } } private static void RenderPaginationFooter(TextMeshProUGUI[] optionTexts, HubLayout layout, int renderedEnd, int total) { if (layout.NextRow >= 0) { SetTextSafe(optionTexts, layout.NextRow, (renderedEnd < total) ? "NEXT" : string.Empty); } SetTextSafe(optionTexts, layout.BackRow, "BACK"); } private static int ClampPageOffset(int requested, int total) { if (total <= 0) { return 0; } int num = Math.Max(0, total - 1); return Mathf.Clamp(requested, 0, num); } private static int GetDesiredNavigationIndex(MainMenuScript menu) { if (DesiredNavigationIndexField == null) { return -1; } object value = DesiredNavigationIndexField.GetValue(menu); if (value is int) { return (int)value; } return -1; } private static void EnsureSlotState(MainMenuScript menu, int index, bool enabled) { if ((Object)(object)menu?.menuController == (Object)null) { return; } DiegeticMenuElement menuElement = GetMenuElement(menu, index); if ((Object)(object)menuElement == (Object)null) { return; } Transform transform = ((Component)menuElement).transform; object obj; if (transform == null) { obj = null; } else { Transform parent = transform.parent; obj = ((parent != null) ? ((Component)parent).gameObject : null); } if (obj != null) { ((GameObject)obj).SetActive(enabled); } List<DiegeticMenuElement> elementsList = GetElementsList(menu.menuController); if (elementsList == null) { return; } if (enabled) { if (!elementsList.Contains(menuElement)) { int index2 = Mathf.Clamp(index, 0, elementsList.Count); elementsList.Insert(index2, menuElement); menuElement.SetMyController(menu.menuController); } if (!VirtualCursors.IsCursorVisible(0, true) && GetDesiredNavigationIndex(menu) == index) { menu.menuController.HoveredElement = menuElement; } } else { elementsList.Remove(menuElement); if (menu.menuController.HoveredElement == menuElement) { menu.menuController.HoveredElement = null; } } } private static void EnsureSlotEnabled(MainMenuScript menu, int index) { EnsureSlotState(menu, index, enabled: true); } private static void EnsureSlotDisabled(MainMenuScript menu, int index) { EnsureSlotState(menu, index, enabled: false); } private static bool ValidateMenuRows(MainMenuScript menu, int requiredIndex) { if ((Object)(object)menu == (Object)null) { return false; } DiegeticMenuElement[] menuElements = menu.menuElements; int num = ((menuElements != null) ? menuElements.Length : 0); TextMeshProUGUI[] optionTexts = menu.optionTexts; int num2 = ((optionTexts != null) ? optionTexts.Length : 0); bool num3 = num > requiredIndex; bool flag = num2 > requiredIndex; if ((!num3 || !flag) && !_rowValidationLogged) { _rowValidationLogged = true; Logging.LogFatal($"ModSettingsExtender detected missing menu rows. Expected index {requiredIndex} but found menuElements={num}, optionTexts={num2}. The base menu prefab likely changed; mods menu injection is disabled."); } return num3 && flag; } private static int VisibleCapacity(MainMenuScript menu) { return Mathf.Max(0, GetElementsList(menu?.menuController)?.Count ?? 0); } private static bool InputSuppressed(MainMenuScript menu) { bool num = Controls.MouseButton_PressedGet(0, (MouseElement)1); bool flag = GetFlag(RightNavigationPressField, menu); bool flag2 = GetFlag(LeftNavigationPressField, menu); return num || flag || flag2; } [HarmonyPostfix] [HarmonyPatch(typeof(MainMenuScript), "OptionsUpdateText_Desktop")] private static void OptionsUpdateText_Desktop_Postfix(MainMenuScript __instance) { AfterOptionsUpdateText(__instance); } private static void AfterOptionsUpdateText(MainMenuScript menu) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Invalid comparison between Unknown and I4 if ((Object)(object)menu == (Object)null) { return; } try { if ((int)GetMenuIndex(menu) == 1) { EnsureModsRow(menu); } else { DisableExtraRow(menu); } if (IsInHub()) { RenderHub(menu); } else if (HubState.Current != 0 && !HasPages()) { HubState.Reset(); } } catch (Exception arg) { Logging.LogError($"OptionsUpdate postfix failed: {arg}"); } } private static void DisableExtraRow(MainMenuScript menu) { if (!((Object)(object)menu == (Object)null)) { int backSlotIndex = GetBackSlotIndex(); if (ValidateMenuRows(menu, backSlotIndex)) { SetTextSafe(menu.optionTexts, backSlotIndex, string.Empty); EnsureSlotDisabled(menu, backSlotIndex); } } } private static void EnsureModsRow(MainMenuScript menu) { TextMeshProUGUI[] optionTexts = menu.optionTexts; if (optionTexts == null) { return; } int modsSlotIndex = GetModsSlotIndex(); int backSlotIndex = GetBackSlotIndex(); bool flag = HasPages(); if (!ValidateMenuRows(menu, Math.Max(modsSlotIndex, backSlotIndex))) { return; } if (!flag) { SetTextSafe(optionTexts, modsSlotIndex, Translation.Get("MENU_OPTION_BACK")); SetTextSafe(optionTexts, backSlotIndex, string.Empty); EnsureSlotDisabled(menu, backSlotIndex); } else if (modsSlotIndex < optionTexts.Length && backSlotIndex < optionTexts.Length) { TextMeshProUGUI obj = optionTexts[modsSlotIndex]; string value = ((obj != null) ? ((TMP_Text)obj).text : null) ?? Translation.Get("MENU_OPTION_BACK"); if (string.IsNullOrEmpty(value)) { value = Translation.Get("MENU_OPTION_BACK"); } EnsureSlotEnabled(menu, modsSlotIndex); EnsureSlotEnabled(menu, backSlotIndex); SetTextSafe(optionTexts, backSlotIndex, value); SetTextSafe(optionTexts, modsSlotIndex, "MODS"); } } private static void RenderHub(MainMenuScript menu) { if (TryGetOptionTexts(menu, out TextMeshProUGUI[] optionTexts) && TryGetHubLayout(menu, out var layout)) { ModSettingsManager.Page page; if (HubState.Current == HubState.View.HubIndex) { RenderHubIndex(menu, optionTexts, layout); } else if (HubState.Current == HubState.View.Page && TryGetActivePage(out page)) { RenderHubPage(menu, optionTexts, layout, page); } } } private static void RenderHubIndex(MainMenuScript menu, TextMeshProUGUI[] optionTexts, HubLayout layout) { if ((Object)(object)menu.titleText != (Object)null) { ((TMP_Text)menu.titleText).text = "MOD SETTINGS"; } int hubPageOffset = HubState.HubPageOffset; int count = ModSettingsManager.Pages.Count; int renderedEnd = Mathf.Min(hubPageOffset + layout.ListSlots, count); RenderListEntries(optionTexts, layout.ListSlots, hubPageOffset, count, (int index) => ModSettingsManager.GetDisplayTitle(ModSettingsManager.Pages[index])); RenderPaginationFooter(optionTexts, layout, renderedEnd, count); } private static void RenderHubPage(MainMenuScript menu, TextMeshProUGUI[] optionTexts, HubLayout layout, ModSettingsManager.Page page) { ModSettingsManager.Page page2 = page; if ((Object)(object)menu.titleText != (Object)null) { ((TMP_Text)menu.titleText).text = ModSettingsManager.GetDisplayTitle(page2); } int pageItemOffset = HubState.PageItemOffset; int count = page2.Items.Count; int renderedEnd = Mathf.Min(pageItemOffset + layout.ListSlots, count); RenderListEntries(optionTexts, layout.ListSlots, pageItemOffset, count, (int index) => page2.Items[index].Label?.Invoke() ?? "(item)"); RenderPaginationFooter(optionTexts, layout, renderedEnd, count); } [HarmonyPrefix] [HarmonyPatch(typeof(MainMenuScript), "Select_Desktop")] private static bool Select_Desktop_Prefix(MainMenuScript __instance, MenuIndex _menuIndex, int selectionIndex) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Invalid comparison between Unknown and I4 if (IsInHub() && (int)_menuIndex == 0 && selectionIndex == 0) { if (HubState.Current == HubState.View.Page) { Sound.Play("SoundMenuBack", 1f, 1f); HubState.Current = HubState.View.HubIndex; HubState.PageItemOffset = 0; } else { Sound.Play("SoundMenuBack", 1f, 1f); HubState.Reset(); SetDesiredNavigationIndex(__instance, GetModsSlotIndex()); } __instance.OptionsUpdate(); return false; } if (IsInHub()) { HandleHubSelection(__instance, selectionIndex); __instance.OptionsUpdate(); return false; } if ((int)_menuIndex == 1 && HasPages()) { int modsSlotIndex = GetModsSlotIndex(); int backSlotIndex = GetBackSlotIndex(); bool flag = InputSuppressed(__instance); if (selectionIndex == modsSlotIndex && !flag) { Sound.Play("SoundMenuSelect", 1f, 1f); HubState.Current = HubState.View.HubIndex; HubState.HubPageOffset = 0; HubState.ActivePage = -1; HubState.PageItemOffset = 0; SetDesiredNavigationIndex(__instance, 0); __instance.OptionsUpdate(); return false; } if (selectionIndex == backSlotIndex && !flag) { Sound.Play("SoundMenuBack", 1f, 1f); SetMenuIndex(__instance, (MenuIndex)0); int value = ((!Master.IsDemo) ? 2 : 3); SetDesiredNavigationIndex(__instance, value); HubState.Reset(); __instance.OptionsUpdate(); return false; } } return true; } private static void HandleHubSelection(MainMenuScript menu, int selectionIndex) { if (TryGetHubLayout(menu, out var layout)) { if (HubState.Current == HubState.View.HubIndex) { HandleHubIndexSelection(menu, selectionIndex, layout); } else if (HubState.Current == HubState.View.Page) { int navigationDirection = GetNavigationDirection(menu); HandleHubPageSelection(menu, selectionIndex, layout, navigationDirection); } } } private static void HandleHubIndexSelection(MainMenuScript menu, int selectionIndex, HubLayout layout) { int hubPageOffset = HubState.HubPageOffset; int count = ModSettingsManager.Pages.Count; int num = Mathf.Min(hubPageOffset + layout.ListSlots, count); if (selectionIndex >= 0 && selectionIndex < layout.ListSlots) { int num2 = hubPageOffset + selectionIndex; if (num2 >= hubPageOffset && num2 < num) { Sound.Play("SoundMenuSelect", 1f, 1f); HubState.ActivePage = num2; HubState.PageItemOffset = 0; HubState.Current = HubState.View.Page; SetDesiredNavigationIndex(menu, 0); } } else if (selectionIndex == layout.NextRow && num < count) { Sound.Play("SoundMenuSelect", 1f, 1f); HubState.HubPageOffset = ClampPageOffset(HubState.HubPageOffset + layout.Step, count); } else if (selectionIndex == layout.BackRow) { Sound.Play("SoundMenuBack", 1f, 1f); HubState.Reset(); SetDesiredNavigationIndex(menu, GetModsSlotIndex()); } } private static void HandleHubPageSelection(MainMenuScript menu, int selectionIndex, HubLayout layout, int direction) { if (!TryGetActivePage(out ModSettingsManager.Page page)) { return; } int pageItemOffset = HubState.PageItemOffset; int count = page.Items.Count; int num = Mathf.Min(pageItemOffset + layout.ListSlots, count); if (selectionIndex >= 0 && selectionIndex < layout.ListSlots) { int num2 = pageItemOffset + selectionIndex; if (num2 >= pageItemOffset && num2 < num) { ModSettingsManager.Item item = page.Items[num2]; if ((direction != 0) ? TryInvokeAdjust(page, num2, item, direction) : TryInvokeSelect(page, num2, item)) { Sound.Play("SoundMenuSelect", 1f, 1f); } } } else if (selectionIndex == layout.NextRow && num < count) { Sound.Play("SoundMenuSelect", 1f, 1f); HubState.PageItemOffset = ClampPageOffset(HubState.PageItemOffset + layout.Step, count); } else if (selectionIndex == layout.BackRow) { Sound.Play("SoundMenuBack", 1f, 1f); HubState.Current = HubState.View.HubIndex; HubState.PageItemOffset = 0; HubState.ActivePage = -1; SetDesiredNavigationIndex(menu, 0); } } private static int GetNavigationDirection(MainMenuScript menu) { bool flag = GetFlag(RightNavigationPressField, menu); bool flag2 = GetFlag(LeftNavigationPressField, menu); int num = (flag ? 1 : (flag2 ? (-1) : 0)); if (num == 0 && Controls.MouseButton_PressedGet(0, (MouseElement)1)) { num = -1; } return num; } private static bool TryInvokeSelect(ModSettingsManager.Page page, int itemIndex, ModSettingsManager.Item item) { if (item == null || item.OnSelect == null) { return true; } return TryInvokeItemHandler(page, itemIndex, "OnSelect", item.OnSelect); } private static bool TryInvokeAdjust(ModSettingsManager.Page page, int itemIndex, ModSettingsManager.Item item, int direction) { ModSettingsManager.Item item2 = item; if (item2 == null || item2.OnAdjust == null) { return true; } return TryInvokeItemHandler(page, itemIndex, "OnAdjust", delegate { item2.OnAdjust(direction); }); } private static bool TryInvokeItemHandler(ModSettingsManager.Page page, int itemIndex, string handler, Action invoke) { try { invoke(); return true; } catch (Exception ex) { LogHandlerException(handler, page, itemIndex, ex); return false; } } private static void LogHandlerException(string handler, ModSettingsManager.Page page, int itemIndex, Exception ex) { string text = page?.Name ?? "(unnamed page)"; Logging.LogError($"Exception during {handler} for page '{text}' item index {itemIndex}: {ex}"); } } [HarmonyPatch] public class TexturePatcher { [HarmonyPatch(typeof(Object), "Internal_CloneSingle", new Type[] { typeof(Object) })] [HarmonyPostfix] public static void Object_CloneSingle(ref Object __result) { Object obj = __result; GameObject val = (GameObject)(object)((obj is GameObject) ? obj : null); if (val == null) { return; } Renderer[] componentsInChildren = val.GetComponentsInChildren<Renderer>(true); foreach (Renderer val2 in componentsInChildren) { Material[] materials = val2.materials; foreach (Material val3 in materials) { if (!val3.HasProperty("_MainTex") || (Object)(object)val3.mainTexture == (Object)null) { continue; } string text = ((Object)val3.mainTexture).name.ToLower(); string text2 = ((Object)val).name.Replace("(Clone)", "").Trim().ToLower() + "_" + ((Object)val3.mainTexture).name.ToLower(); string text3 = ((Object)val).name.Replace("(Clone)", "").Trim().ToLower() + "_" + ((Object)val2).name.Trim().ToLower() + "_" + ((Object)val3.mainTexture).name.ToLower(); if (TextureManager.TryGetTextureOverride(out var texture, text, text2, text3)) { if ((val3.mainTexture.width != ((Texture)texture).width || val3.mainTexture.height != ((Texture)texture).height) && !Plugin.UseFullQualityTextures.Value) { texture = TextureUtils.ResizeTexture(texture, val3.mainTexture.width, val3.mainTexture.height); } val3.mainTexture = (Texture)(object)texture; } } } AudioSource[] componentsInChildren2 = val.GetComponentsInChildren<AudioSource>(true); foreach (AudioSource val4 in componentsInChildren2) { if (!((Object)(object)val4.clip == (Object)null) && AudioManager.TryGetSoundOverride(out var audioClip, ((Object)val4.clip).name)) { val4.clip = audioClip; } } } } [HarmonyPatch] internal class TranslationPatcher { [HarmonyPatch(typeof(Translation), "Get")] [HarmonyPrefix] internal static bool Translation_Get_Prefix(ref string key, ref string __result) { if (string.IsNullOrEmpty(key)) { return true; } bool result = true; if (LocalizationManager.TryGetValueNoCase(key, out var value)) { __result = value; result = false; } if (LanguageManager.IsCustomLanguage && LanguageManager.TryGetTerm(key, out var termValue)) { __result = termValue; result = false; } return result; } [HarmonyPatch(typeof(Strings), "Sanitize")] [HarmonyPrefix] internal static void Strings_Sanitize_Prefix(ref string input, SantizationKind santizationKind, SanitizationSubKind subKind) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) StringManager.Sanitize(ref input, santizationKind, subKind); } [HarmonyPatch(typeof(Strings), "Sanitize")] [HarmonyPostfix] internal static void Strings_Sanitize_Postfix(ref string __result, SantizationKind santizationKind, SanitizationSubKind subKind) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) StringManager.SanitizeLate(ref __result, santizationKind, subKind); } [HarmonyPatch(typeof(Translation), "LanguageGet")] [HarmonyPrefix] internal static bool Translation_LanguageGet_Prefix(ref Language __result) { if (LanguageManager.IsCustomLanguage) { __result = (Language)0; return false; } return true; } } } namespace CloverAPI.Internal { internal class CharmMappings : JsonPersistentData { internal static CharmMappings Instance = new CharmMappings(); [JsonProperty] internal Dictionary<string, Identifier> Mappings = new Dictionary<string, Identifier>(); public override void BeforeSave() { Mappings = CharmManager.GUIDToId; } public override void AfterLoad() { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) Dictionary<Identifier, Identifier> dictionary = CharmManager.GenerateRemaps(Mappings); if (dictionary.Count == 0) { Logging.LogInfo("No Charm mappings to apply."); return; } Logging.LogInfo("Current Charm mappings:"); foreach (KeyValuePair<Identifier, Identifier> item in dictionary) { Logging.LogInfo($" {item.Key} -> {item.Value}"); } for (int i = 0; i < GameplayData.Instance.equippedPowerups.Length; i++) { Identifier key = PlatformDataMaster.EnumEntryFromString<Identifier>(GameplayData.Instance.equippedPowerups[i], (Identifier)(-1)); if (dictionary.TryGetValue(key, out var value)) { GameplayData.Instance.equippedPowerups[i] = ((object)(Identifier)(ref value)).ToString(); } } for (int j = 0; j < GameplayData.Instance.equippedPowerups_Skeleton.Length; j++) { Identifier key2 = PlatformDataMaster.EnumEntryFromString<Identifier>(GameplayData.Instance.equippedPowerups_Skeleton[j], (Identifier)(-1)); if (dictionary.TryGetValue(key2, out var value2)) { GameplayData.Instance.equippedPowerups_Skeleton[j] = ((object)(Identifier)(ref value2)).ToString(); } } for (int k = 0; k < GameplayData.Instance.drawerPowerups.Length; k++) { Identifier key3 = PlatformDataMaster.EnumEntryFromString<Identifier>(GameplayData.Instance.drawerPowerups[k], (Identifier)(-1)); if (dictionary.TryGetValue(key3, out var value3)) { GameplayData.Instance.drawerPowerups[k] = ((object)(Identifier)(ref value3)).ToString(); } } } } public static class ResourceOrdering { private static readonly object _lock = new object(); private static ConfigEntry<string> _overrideOrdering; public static List<string> OrderedPluginUuids { get; private set; } = new List<string>(); public static int GetPriority(string pluginUuid) { lock (_lock) { if (!OrderedPluginUuids.Contains(pluginUuid)) { OrderedPluginUuids.Add(pluginUuid); ApplyToConfig(); } return OrderedPluginUuids.IndexOf(pluginUuid); } } internal static void _ConfigRef(ConfigEntry<string> overrideOrdering) { lock (_lock) { if (overrideOrdering == null) { throw new ArgumentNullException("overrideOrdering"); } _overrideOrdering = overrideOrdering; OrderedPluginUuids = new List<string>((from s in overrideOrdering.Value.Split(new char[1] { ',' }) select s.Trim() into s where !string.IsNullOrEmpty(s) select s).ToArray()); } } internal static void ApplyToConfig() { lock (_lock) { if (_overrideOrdering == null) { throw new InvalidOperationException("Config reference not set. Call _ConfigRef first."); } _overrideOrdering.Value = string.Join(", ", OrderedPluginUuids); } } } } namespace CloverAPI.Content.Textures { public class TextureManager { internal class TextureOverride : IPriority { public Texture2D Texture; public string OwnerGuid; public int Priority => ResourceOrdering.GetPriority(OwnerGuid); } internal static ConcurrentDictionary<string, OrderedList<TextureOverride, PriorityComparer>> TextureOverrides = new ConcurrentDictionary<string, OrderedList<TextureOverride, PriorityComparer>>(); public static void RegisterTextureOverride(string name, Texture2D texture, ModGuid guid) { _RegisterOverride(name, TextureOverrides, texture, guid); } private static void _RegisterOverride(string name, ConcurrentDictionary<string, OrderedList<TextureOverride, PriorityComparer>> dict, Texture2D texture, ModGuid guid) { if (!dict.ContainsKey(name)) { dict[name] = new OrderedList<TextureOverride, PriorityComparer>(); } TextureOverride textureOverride = dict[name].FirstOrDefault((TextureOverride o) => o.OwnerGuid == guid); if (textureOverride != null) { textureOverride.Texture = texture; return; } dict[name].Add(new TextureOverride { Texture = texture, OwnerGuid = guid }); } public static bool TryGetTextureOverride(string name, out Texture2D texture) { return _TryGetOverride(name, TextureOverrides, out texture); } public static bool TryGetTextureOverride(out Texture2D texture, params string[] names) { for (int i = 0; i < names.Length; i++) { if (_TryGetOverride(names[i], TextureOverrides, out texture)) { return true; } } texture = null; return false; } private static bool _TryGetOverride(string name, ConcurrentDictionary<string, OrderedList<TextureOverride, PriorityComparer>> dict, out Texture2D texture) { if (dict.TryGetValueNoCase(name, out var value) && value.Count > 0) { TextureOverride textureOverride = value[0]; texture = textureOverride.Texture; return true; } texture = null; return false; } } } namespace CloverAPI.Content.Strings { public static class LanguageManager { internal static List<string> CustomLanguages = new List<string>(); internal static Dictionary<Language, string> LangMap = new Dictionary<Language, string>(); internal static Dictionary<string, Language> LangMapT = new Dictionary<string, Language>(); internal static Dictionary<string, Dictionary<string, string>> TermsByLanguage = new Dictionary<string, Dictionary<string, string>>(); private static int NextId => Enum.GetValues(typeof(Language)).Length + CustomLanguages.Count - 1; public static bool IsCustomLanguage => (int)Data.settings.language >= Enum.GetValues(typeof(Language)).Length - 1; public static Language LoadFromFile(string filePath) { //IL_0115: Unknown result type (might be due to invalid IL or missing references) string[] array = File.ReadAllText(filePath).Replace("\\;", "<SEMICOLON>").Split(new char[2] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); Dictionary<string, string> dictionary = new Dictionary<string, string>(); string text = ""; string[] array2 = array; foreach (string text2 in array2) { if (!text2.StartsWith("#") && !text2.StartsWith("//") && !string.IsNullOrWhiteSpace(text2)) { string[] array3 = text2.Split(new char[1] { ';' }, 2); if (array3.Length == 2) { text = array3[0].Trim(); dictionary[text] = array3[1].Replace("<SEMICOLON>", ";").Trim(); } else { Dictionary<string, string> dictionary2 = dictionary; string key = text; dictionary2[key] = dictionary2[key] + "\n" + text2.Replace("<SEMICOLON>", ";"); } } } if (!dictionary.ContainsKey("YOUR_LANGUAGE_TRANSLATED")) { dictionary["YOUR_LANGUAGE_TRANSLATED"] = Path.GetFileNameWithoutExtension(filePath); } return RegisterLanguage(dictionary); } public static Language RegisterLanguage(params (string termKey, string termValue)[] terms) { //IL_006a: Unknown result type (might be due to invalid IL or missing references) Dictionary<string, string> dictionary = new Dictionary<string, string>(); for (int i = 0; i < terms.Length; i++) { (string termKey, string termValue) tuple = terms[i]; string item = tuple.termKey; string item2 = tuple.termValue; dictionary[item] = item2; } string languageName = $"UnnamedLanguage{CustomLanguages.Count + 1}"; if (dictionary.TryGetValue("YOUR_LANGUAGE_TRANSLATED", out var value)) { languageName = value; } return RegisterLanguage(languageName, dictionary); } public static Language RegisterLanguage(Dictionary<string, string> terms) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) string languageName = $"UnnamedLanguage{CustomLanguages.Count + 1}"; if (terms.TryGetValue("YOUR_LANGUAGE_TRANSLATED", out var value)) { languageName = value; } return RegisterLanguage(languageName, terms); } public static Language RegisterLanguage(string languageName, params (string termKey, string termValue)[] terms) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) Dictionary<string, string> dictionary = new Dictionary<string, string>(); for (int i = 0; i < terms.Length; i++) { (string termKey, string termValue) tuple = terms[i]; string item = tuple.termKey; string item2 = tuple.termValue; dictionary[item] = item2; } return RegisterLanguage(languageName, dictionary); } public static Language RegisterLanguage(string languageName, Dictionary<string, string> terms) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0028: 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) //IL_0093: Unknown result type (might be due to invalid IL or missing references) if (!CustomLanguages.Contains(languageName)) { Language val = (Language)NextId; LangMap[val] = languageName; LangMapT[languageName] = val; TermsByLanguage[languageName] = new Dictionary<string, string>(terms); CustomLanguages.Add(languageName); _ = Translation.LanguagesInOrder; Translation._languagesInOrder = Translation._languagesInOrder.Append(val).ToArray(); Translation.languageNamesTranslated = Translation.languageNamesTranslated.Append(languageName).ToArray(); Translation.languagesI2Names = Translation.languagesI2Names.Append("English").ToArray(); return val; } throw new Exception("Language " + languageName + " is already registered."); } public static bool TryGetTerm(string termKey, out string termValue) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) Language language = Data.settings.language; if (LangMap.TryGetValue(language, out var value) && TermsByLanguage.TryGetValue(value, out var value2)) { return value2.TryGetValue(termKey, out termValue); } termValue = null; return false; } public static Language GetLanguageByName(string languageName) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (LangMapT.TryGetValue(languageName, out var value)) { return value; } throw new Exception("Language " + languageName + " is not registered."); } private static bool TryGetLanguageByName(string languageName, out Language lang) { return LangMapT.TryGetValue(languageName, out lang); } } public static class LocalizationManager { public static Dictionary<string, StringSource> Translations = new Dictionary<string, StringSource>(); public static string RegisterTranslation(string key, StringSource value) { value.SetKey(key); Translations[key] = value; return key; } public static string Get(string key) { if (Translations.TryGetValue(key, out var value)) { return value.GetString(); } return key; } public static bool TryGetValueNoCase(string key, out string value) { if (Translations.TryGetValueNoCase(key, out var value2)) { if (value2 is VanillaLocalizedString) { value = null; return false; } value = value2.GetString(); return true; } value = null; return false; } } public class StringManager { private static readonly Dictionary<string, StringSource> Strings = new Dictionary<string, StringSource>(); private static readonly Dictionary<string, Tuple<StringSource, SantizationKind, SanitizationSubKind>> ConditionalStrings = new Dictionary<string, Tuple<StringSource, SantizationKind, SanitizationSubKind>>(); private static readonly Dictionary<string, StringSource> StringsLate = new Dictionary<string, StringSource>(); private static readonly Dictionary<string, Tuple<StringSource, SantizationKind, SanitizationSubKind>> ConditionalStringsLate = new Dictionary<string, Tuple<StringSource, SantizationKind, SanitizationSubKind>>(); public static void RegisterString(string key, StringSource value, bool late = false) { if (late) { StringsLate[key] = value; } else { Strings[key] = value; } } public static void RegisterConditional(string key, StringSource value, SantizationKind kind, SanitizationSubKind subKind, bool late = false) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) if (late) { ConditionalStringsLate[key] = new Tuple<StringSource, SantizationKind, SanitizationSubKind>(value, kind, subKind); } else { ConditionalStrings[key] = new Tuple<StringSource, SantizationKind, SanitizationSubKind>(value, kind, subKind); } } public static void Sanitize(ref string s, SantizationKind santizationKind, SanitizationSubKind subKind) { //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) StringBuilder stringBuilder = new StringBuilder(s); foreach (string key in Strings.Keys) { stringBuilder.Replace(key, Strings[key].GetString()); } foreach (string key2 in ConditionalStrings.Keys) { var (stringSource2, val3, val4) = ConditionalStrings[key2]; if (((int)santizationKind == 0 || santizationKind == val3) && ((int)subKind == 0 || subKind == val4)) { stringBuilder.Replace(key2, stringSource2.GetString()); } } s = stringBuilder.ToString(); } public static void SanitizeLate(ref string s, SantizationKind santizationKind, SanitizationSubKind subKind) { //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) StringBuilder stringBuilder = new StringBuilder(s); foreach (string key in StringsLate.Keys) { stringBuilder.Replace(key, StringsLate[key].GetString()); } foreach (string key2 in ConditionalStringsLate.Keys) { var (stringSource2, val3, val4) = ConditionalStringsLate[key2]; if (((int)santizationKind == 0 || santizationKind == val3) && ((int)subKind == 0 || subKind == val4)) { stringBuilder.Replace(key2, stringSource2.GetString()); } } s = stringBuilder.ToString(); } } } namespace CloverAPI.Content.Settings { public class ModSettingsManager { public enum ToggleAdjustMode { Toggle, Directional } public sealed class Item { public Func<string>? Label { get; set; } public Action? OnSelect { get; set; } public Action<int>? OnAdjust { get; set; } public Item() { } internal Item(Func<string>? label, Action? onSelect, Action<int>? onAdjust) { Label = label; OnSelect = onSelect; OnAdjust = onAdjust; } } public sealed class Page { private readonly List<Item> items = new List<Item>(); public string Name { get; } internal string OwnerGuid { get; } internal string OwnerName { get; } internal string NormalizedName { get; } public List<Item> Items => items; internal Page(string name, ModGuid ownerGuid, ModName ownerName, string normalizedName) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException("Page name must not be empty.", "name"); } if (string.IsNullOrWhiteSpace(ownerGuid)) { throw new ArgumentException("Page owner GUID must not be empty.", "ownerGuid"); } if (string.IsNullOrWhiteSpace(normalizedName)) { throw new ArgumentException("Normalized page name must not be empty.", "normalizedName"); } Name = name; OwnerGuid = ownerGuid; OwnerName = ownerName; NormalizedName = normalizedName; } internal Item AddItem(Func<string>? label, Action? onSelect, Action<int>? onAdjust) { return AddItem(new Item(label, onSelect, onAdjust)); } internal Item AddItem(Item item) { if (item == null) { throw new ArgumentNullException("item"); } items.Add(item); return item; } } public sealed class PageBuilder { private static readonly IReadOnlyList<float> DefaultMultiplierSteps = Array.AsReadOnly(new float[6] { 0f, 0.5f, 1f, 2f, 3f, 4f }); private readonly Page page; public Page BuiltPage => page; internal PageBuilder(Page page) { this.page = page ?? throw new ArgumentNullException("page"); } public PageBuilder AddItem(Func<string>? label, Action? onSelect = null, Action<int>? onAdjust = null) { page.AddItem(label, onSelect, onAdjust); return this; } public PageBuilder AddToggle(string label, Func<bool> getter, Action<bool> setter, string onLabel = "On", string offLabel = "Off", Action<bool>? onChanged = null, ToggleAdjustMode adjustMode = ToggleAdjustMode.Toggle) { string label2 = label; Func<bool> getter2 = getter; string onLabel2 = onLabel; string offLabel2 = offLabel; Action<bool> setter2 = setter; Action<bool> onChanged2 = onChanged; if (label2 == null) { throw new ArgumentNullException("label"); } if (getter2 == null) { throw new ArgumentNullException("getter"); } if (setter2 == null) { throw new ArgumentNullException("setter"); } return AddItem(Format, delegate { SetValue(!getter2()); }, delegate(int dir) { int num = NormalizeDirection(dir); if (num != 0) { if (adjustMode == ToggleAdjustMode.Directional) { SetValue(num > 0); } else { SetValue(!getter2()); } } }); string Format() { return label2 + ": " + (getter2() ? onLabel2 : offLabel2); } void SetValue(bool value) { UpdateIfChanged(getter2, setter2, value, onChanged2); } } public PageBuilder AddToggle(string label, ConfigEntry<bool> entry, string onLabel = "On", string offLabel = "Off", Action<bool>? onChanged = null, ToggleAdjustMode adjustMode = ToggleAdjustMode.Toggle) { ConfigEntry<bool> entry2 = entry; if (entry2 == null) { throw new ArgumentNullException("entry"); } return AddToggle(label, () => entry2.Value, delegate(bool value) { entry2.Value = value; }, onLabel, offLabel, onChanged, adjustMode); } public PageBuilder OnOff(string label, Func<bool> getter, Action<bool> setter, string onLabel = "On", string offLabel = "Off", Action<bool>? onChanged = null, ToggleAdjustMode adjustMode = ToggleAdjustMode.Toggle) { return AddToggle(label, getter, setter, onLabel, offLabel, onChanged, adjustMode); } public PageBuilder OnOff(string label, ConfigEntry<bool> entry, string onLabel = "On", string offLabel = "Off", Action<bool>? onChanged = null, ToggleAdjustMode adjustMode = ToggleAdjustMode.Toggle) { ConfigEntry<bool> entry2 = entry; return OnOff(label, () => entry2.Value, delegate(bool value) { entry2.Value = value; }, onLabel, offLabel, onChanged, adjustMode); } public PageBuilder AddIntStepper(string label, Func<int> getter, Action<int> setter, int step = 1, int? min = null, int? max = null, bool wrap = false, Func<int, int>? normalizer = null, Func<int, string>? valueFormatter = null, Action<int>? onChanged = null) { Func<int, int> normalizer2 = normalizer; Func<int> getter2 = getter; Action<int> setter2 = setter; Action<int> onChanged2 = onChanged; Func<int, string> valueFormatter2 = valueFormatter; string label2 = label; if (label2 == null) { throw new ArgumentNullException("label"); } if (getter2 == null) { throw new ArgumentNullException("getter"); } if (setter2 == null) { throw new ArgumentNullException("setter"); } if (step <= 0) { throw new ArgumentOutOfRangeException("step", "Step must be positive."); } if (min.HasValue && max.HasValue && min.Value > max.Value) { throw new ArgumentOutOfRangeException("max", "Max must be greater than or equal to min."); } return AddItem(Format, delegate { SetValue(getter2() + step); }, delegate(int dir) { int num5 = NormalizeDirection(dir); if (num5 != 0) { SetValue(getter2() + num5 * step); } }); int ApplyBounds(int value) { if (wrap && min.HasValue && max.HasValue && min.Value <= max.Value) { int num = Math.Max(1, step); int num2 = max.Value - min.Value + num; if (num2 > 0) { int num3 = ((value - min.Value) % num2 + num2) % num2; return min.Value + num3; } } if (min.HasValue && value < min.Value) { value = min.Value; } if (max.HasValue && value > max.Value) { value = max.Value; } return value; } string Format() { int arg = getter2(); string text = valueFormatter2?.Invoke(arg) ?? arg.ToString(); return label2 + ": " + text; } int Normalize(int value) { int num4 = ApplyBounds(value); if (normalizer2 != null) { num4 = ApplyBounds(normalizer2(num4)); } return num4; } void SetValue(int rawValue) { int value2 = Normalize(rawValue); UpdateIfChanged(getter2, setter2, value2, onChanged2); } } public PageBuilder AddIntStepper(string label, ConfigEntry<int> entry, int step = 1, int? min = null, int? max = null, bool wrap = false, Func<int, int>? normalizer = null, Func<int, string>? valueFormatter = null, Action<int>? onChanged = null) { ConfigEntry<int> entry2 = entry; if (entry2 == null) { throw new ArgumentNullException("entry"); } return AddIntStepper(label, () => entry2.Value, delegate(int value) { entry2.Value = value; }, step, min, max, wrap, normalizer, valueFormatter, onChanged); } public PageBuilder Int(string label, Func<int> getter, Action<int> setter, int? min = null, int? max = null, int step = 1, bool wrap = false, Func<int, int>? normalizer = null, Func<int, string>? valueFormatter = null, Action<int>? onChanged = null) { return AddIntStepper(label, getter, setter, step, min, max, wrap, normalizer, valueFormatter, onChanged); } public PageBuilder Int(string label, ConfigEntry<int> entry, int? min = null, int? max = null, int step = 1, bool wrap = false, Func<int, int>? normalizer = null, Func<int, string>? valueFormatter = null, Action<int>? onChanged = null) { ConfigEntry<int> entry2 = entry; if (entry2 == null) { throw new ArgumentNullException("entry"); } return Int(label, () => entry2.Value, delegate(int value) { entry2.Value = value; }, min, max, step, wrap, normalizer, valueFormatter, onChanged); } public PageBuilder Percent(string label, Func<int> getter, Action<int> setter, int minPercent = 0, int maxPercent = 100, int step = 5, bool wrap = false, bool showPercent = true, float scale = 1f, Action<int>? onChanged = null) { if (maxPercent < minPercent) { throw new ArgumentOutOfRangeException("maxPercent", "maxPercent must be greater than or equal to minPercent."); } return AddIntStepper(label, getter, setter, step, minPercent, maxPercent, wrap, null, Formatter, onChanged); string Formatter(int value) { int num = (int)((float)value * scale); if (!showPercent) { return num.ToString(); } return $"{num}%"; } } public PageBuilder Percent(string label, ConfigEntry<int> entry, int minPercent = 0, int maxPercent = 100, int step = 5, bool wrap = false, bool showPercent = true, float scale = 1f, Action<int>? onChanged = null) { ConfigEntry<int> entry2 = entry; if (entry2 == null) { throw new ArgumentNullException("entry"); } return Percent(label, () => entry2.Value, delegate(int value) { entry2.Value = value; }, minPercent, maxPercent, step, wrap, showPercent, scale, onChanged); } public PageBuilder Percent(string label, Func<float> getter, Action<float> setter, float minPercent = 0f, float maxPercent = 100f, float step = 5f, bool wrap = false, int decimalPlaces = 1, bool showPercent = true, float scale = 1f, Action<float>? onChanged = null) { Action<float> onChanged2 = onChanged; Func<float> getter2 = getter; Action<float> setter2 = setter; if (label == null) { throw new ArgumentNullException("label"); } if (getter2 == null) { throw new ArgumentNullException("getter"); } if (setter2 == null) { throw new ArgumentNullException("setter"); } if (step <= 0f) { throw new ArgumentOutOfRangeException("step", "Step must be positive."); } if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces", "decimalPlaces must be zero or greater."); } float num = getter2(); int requiredDecimalPlaces = GetRequiredDecimalPlaces(minPercent, maxPercent, step, num); int effectiveDecimalPlaces = Math.Max(decimalPlaces, requiredDecimalPlaces); int localScale = Pow10(effectiveDecimalPlaces); int num2 = Scale(step); if (num2 <= 0) { throw new ArgumentOutOfRangeException("step", "Step is too small for the configured decimalPlaces."); } int minScaled = Scale(minPercent); int maxScaled = Scale(maxPercent); if (maxScaled < minScaled) { throw new ArgumentOutOfRangeException("maxPercent", "maxPercent must be greater than or equal to minPercent."); } Action<int> onChanged3 = null; if (onChanged2 != null) { onChanged3 = delegate(int value) { onChanged2(Unscale(value)); }; } return AddIntStepper(label, () => Scale(getter2()), delegate(int value) { setter2(Unscale(value)); }, num2, minScaled, maxScaled, wrap, RoundOnNonBounds, FormatPercentLabel, onChanged3); string FormatPercentLabel(int scaledValue) { float num3 = Unscale(scaledValue) * scale; string text = ((effectiveDecimalPlaces > 0) ? $"F{effectiveDecimalPlaces}" : "F0"); string text2 = num3.ToString(text, CultureInfo.InvariantCulture); if (effectiveDecimalPlaces > 0) { text2 = text2.TrimEnd(new char[1] { '0' }).TrimEnd(new char[1] { '.' }); } if (!showPercent) { return text2; } return text2 + "%"; } int RoundOnNonBounds(int value) { if (value == minScaled || value == maxScaled) { return value; } return Scale(MathUtils.RoundToMultipleOf(Unscale(value), step)); } int Scale(float value) { return (int)Math.Round((decimal)value * (decimal)localScale, MidpointRounding.AwayFromZero); } float Unscale(int value) { return (float)value / (float)localScale; } } public PageBuilder Percent(string label, ConfigEntry<float> entry, float minPercent = 0f, float maxPercent = 100f, float step = 5f, bool wrap = false, int decimalPlaces = 1, bool showPercent = true, float scale = 1f, Action<float>? onChanged = null) { ConfigEntry<float> entry2 = entry; if (entry2 == null) { throw new ArgumentNullException("entry"); } return Percent(label, () => entry2.Value, delegate(float value) { entry2.Value = value; }, minPercent, maxPercent, step, wrap, decimalPlaces, showPercent, scale, onChanged); } public PageBuilder Multiplier(string label, Func<float> getter, Action<float> setter, float minMultiplier, float maxMultiplier, float step, bool wrap = false, int decimalPlaces = 2, Func<float, string>? valueFormatter = null, Action<float>? onChanged = null) { Func<float, string> valueFormatter2 = valueFormatter; Action<float> onChanged2 = onChanged; Func<float> getter2 = getter; Action<float> setter2 = setter; if (label == null) { throw new ArgumentNullException("label"); } if (getter2 == null) { throw new ArgumentNullException("getter"); } if (setter2 == null) { throw new ArgumentNullException("setter"); } if (step <= 0f) { throw new ArgumentOutOfRangeException("step", "Step must be positive."); } if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces", "decimalPlaces must be zero or greater."); } float num = getter2(); int requiredDecimalPlaces = GetRequiredDecimalPlaces(minMultiplier, maxMultiplier, step, num); int effectiveDecimalPlaces = Math.Max(decimalPlaces, requiredDecimalPlaces); int scale = Pow10(effectiveDecimalPlaces); int num2 = Scale(step); if (num2 <= 0) { throw new ArgumentOutOfRangeException("step", "Step is too small for the configured decimalPlaces."); } int num3 = Scale(minMultiplier); int num4 = Scale(maxMultiplier); if (num4 < num3) { throw new ArgumentOutOfRangeException("maxMultiplier", "maxMultiplier must be greater than or equal to minMultiplier."); } Action<int> onChanged3 = null; if (onChanged2 != null) { onChanged3 = delegate(int value) { onChanged2(Unscale(value)); }; } return AddIntStepper(label, () => Scale(getter2()), delegate(int value) { setter2(Unscale(value)); }, num2, num3, num4, wrap, null, FormatMultiplierLabel, onChanged3); string FormatMultiplierLabel(int scaledValue) { float arg = Unscale(scaledValue); if (valueFormatter2 != null) { return valueFormatter2(arg); } string text = ((effectiveDecimalPlaces > 0) ? $"F{effectiveDecimalPlaces}" : "F0"); string text2 = arg.ToString(text, CultureInfo.InvariantCulture); if (effectiveDecimalPlaces > 0) { text2 = text2.TrimEnd(new char[1] { '0' }).TrimEnd(new char[1] { '.' }); } return text2 + "x"; } int Scale(float value) { return (int)Math.Round((decimal)value * (decimal)scale, MidpointRounding.AwayFromZero); } float Unscale(int value) { return (float)value / (float)scale; } } public PageBuilder Multiplier(string label, ConfigEntry<float> entry, float minMultiplier, float maxMultiplier, float step, bool wrap = false, int decimalPlaces = 2, Func<float, string>? valueFormatter = null, Action<float>? onChanged = null) { ConfigEntry<float> entry2 = entry; if (entry2 == null) { throw new ArgumentNullException("entry"); } return Multiplier(label, () => entry2.Value, delegate(float value) { entry2.Value = value; }, minMultiplier, maxMultiplier, step, wrap, decimalPlaces, valueFormatter, onChanged); } public PageBuilder Multiplier(string label, Func<float> getter, Action<float> setter, IReadOnlyList<float>? options = null, Func<float, string>? valueFormatter = null, Action<float>? onChanged = null) { Func<float, string> valueFormatter2 = valueFormatter; IReadOnlyList<float> values = options ?? DefaultMultiplierSteps; int optionDecimalPlaces = ((valueFormatter2 == null) ? GetRequiredDecimalPlaces(values) : 0); return Cycle(label, getter, setter, values, formatter, onChanged); string formatter(float value) { if (valueFormatter2 != null) { return valueFormatter2(value); } string text = ((optionDecimalPlaces > 0) ? $"F{optionDecimalPlaces}" : "F0"); string text2 = value.ToString(text, CultureInfo.InvariantCulture); if (optionDecimalPlaces > 0) { text2 = text2.TrimEnd(new char[1] { '0' }).TrimEnd(new char[1] { '.' }); } return text2 + "x"; } } public PageBuilder Multiplier(string label, ConfigEntry<float> entry, IReadOnlyList<float>? options = null, Func<float, string>? valueFormatter = null, Action<float>? onChanged = null) { ConfigEntry<float> entry2 = entry; if (entry2 == null) { throw new ArgumentNullException("entry"); } return Multiplier(label, () => entry2.Value, delegate(float value) { entry2.Value = value; }, options, valueFormatter, onChanged); } public PageBuilder Cycle<T>(string label, Func<T> getter, Action<T> setter, IReadOnlyList<T> values, Func<T, string>? valueFormatter = null, Action<T>? onChanged = null, IEqualityComparer<T>? comparer = null) { return CycleInternal(label, getter, setter, values, valueFormatter, onChanged, comparer); } public PageBuilder Cycle<T>(string label, Func<T> getter, Action<T> setter, params T[] values) { if (values == null) { throw new ArgumentNullException("values"); } return CycleInternal(label, getter, setter, Array.AsReadOnly(values), null, null, null); } public PageBuilder Cycle<T>(string label, ConfigEntry<T> entry, IReadOnlyList<T> values, Func<T, string>? valueFormatter = null, Action<T>? onChanged = null, IEqualityComparer<T>? comparer = null) { ConfigEntry<T> entry2 = entry; if (entry2 == null) { throw new ArgumentNullException("entry"); } return Cycle(label, () => entry2.Value, delegate(T value) { entry2.Value = value; }, values, valueFormatter, onChanged, comparer); } public PageBuilder Cycle<T>(string label, ConfigEntry<T> entry, params T[] values) { if (values == null) { throw new ArgumentNullException("values"); } return Cycle(label, entry, (IReadOnlyList<T>)Array.AsReadOnly(values), (Func<T, string>?)null, (Action<T>?)null, (IEqualityComparer<T>?)null); } public void Build() { } private PageBuilder CycleInternal<T>(string label, Func<T> getter, Action<T> setter, IReadOnlyList<T> values, Func<T, string>? valueFormatter, Action<T>? onChanged, IEqualityComparer<T>? comparer) { IReadOnlyList<T> values2 = values; Func<T, string> valueFormatter2 = valueFormatter; Func<T> getter2 = getter; string label2 = label; Action<T> setter2 = setter; Action<T> onChanged2 = onChanged; if (label2 == null) { throw new ArgumentNullException("label"); } if (getter2 == null) { throw new ArgumentNullException("getter"); } if (setter2 == null) { throw new ArgumentNullException("setter"); } if (values2 == null) { throw new ArgumentNullException("values"); } if (values2.Count == 0) { throw new ArgumentException("At least one value must be supplied.", "values"); } IEqualityComparer<T> equalityComparer = comparer ?? EqualityComparer<T>.Default; return AddItem(Format, delegate { Advance(1); }, delegate(int dir) { Advance(dir); }); void Advance(int direction) { int num = NormalizeDirection(direction); if (num != 0 && values2.Count != 1) { T candidate2 = getter2(); int num2 = FindIndex(candidate2); int index = ((num2 >= 0) ? ((num2 + num + values2.Count) % values2.Count) : ((num <= 0) ? (values2.Count - 1) : 0)); T value2 = values2[index]; UpdateIfChanged(getter2, setter2, value2, onChanged2); } } int FindIndex(T candidate) { for (int i = 0; i < values2.Count; i++) { if (equalityComparer.Equals(values2[i], candidate)) { return i; } } return -1; } string Format() { T value3 = getter2(); return label2 + ": " + RenderValue(value3); } string RenderValue(T value) { if (valueFormatter2 != null) { return valueFormatter2(value); } if (!((object)value is IFormattable formattable)) { object obj = value?.ToString(); if (obj == null) { obj = string.Empty; } return (string)obj; } return formattable.ToString(null, CultureInfo.InvariantCulture); } } private static int NormalizeDirection(int value) { if (value == 0) { return 0; } if (value <= 0) { return -1; } return 1; } private static int Pow10(int exponent) { if (exponent < 0) { throw new ArgumentOutOfRangeException("exponent"); } int num = 1; for (int i = 0; i < exponent; i++) { num = checked(num * 10); } return num; } private static int GetRequiredDecimalPlaces(IReadOnlyList<float> values) { if (values == null || values.Count == 0) { return 0; } int num = 0; for (int i = 0; i < values.Count; i++) { int num2 = CountDecimalPlaces(values[i]); if (num2 > num) { num = num2; } } return num; } private static int GetRequiredDecimalPlaces(params float[] values) { if (values == null || values.Length == 0) { return 0; } int num = 0; for (int i = 0; i < values.Length; i++) { int num2 = CountDecimalPlaces(values[i]); if (num2 > num) { num = num2; } } return num; } private static int CountDecimalPlaces(float value) { decimal value2 = decimal.Round((decimal)value, 6, MidpointRounding.AwayFromZero); value2 = Math.Abs(value2); for (int i = 0; i <= 6; i++) { decimal num = value2 * (decimal)Pow10(i); if (decimal.Truncate(num) == num) { return i; } } return 6; } private static void UpdateIfChanged<T>(Func<T> getter, Action<T> setter, T value, Action<T>? onChanged) { if (getter == null) { throw new ArgumentNullException("getter"); } if (setter == null) { th
plugins/Newtonsoft.Json.dll
Decompiled 2 weeks 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.4.30916")] [assembly: AssemblyInformationalVersion("13.0.4+4e13299d4b0ec96bd4df9954ef646bd2d1b5bf2a")] [assembly: AssemblyProduct("Json.NET")] [assembly: AssemblyTitle("Json.NET .NET 4.5")] [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.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] internal sealed class DynamicallyAccessedMembersAttribute : Attribute { public DynamicallyAccessedMemberTypes MemberTypes { get; } public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } } [Flags] internal enum DynamicallyAccessedMemberTypes { None = 0, PublicParameterlessConstructor = 1, PublicConstructors = 3, NonPublicConstructors = 4, PublicMethods = 8, NonPublicMethods = 0x10, PublicFields = 0x20, NonPublicFields = 0x40, PublicNestedTypes = 0x80, NonPublicNestedTypes = 0x100, PublicProperties = 0x200, NonPublicProperties = 0x400, PublicEvents = 0x800, NonPublicEvents = 0x1000, Interfaces = 0x2000, All = -1 } [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class FeatureGuardAttribute : Attribute { public Type FeatureType { get; } public FeatureGuardAttribute(Type featureType) { FeatureType = featureType; } } [AttributeUsage(AttributeTargets.Property, Inherited = false)] internal sealed class FeatureSwitchDefinitionAttribute : Attribute { public string SwitchName { get; } public FeatureSwitchDefinitionAttribute(string switchName) { SwitchName = switchName; } } [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; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresDynamicCodeAttribute : Attribute { public string Message { get; } public string? Url { get; set; } public RequiresDynamicCodeAttribute(string message) { Message = message; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresUnreferencedCodeAttribute : Attribute { public string Message { get; } public string? Url { get; set; } public RequiresUnreferencedCodeAttribute(string message) { Message = message; } } [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] internal sealed class UnconditionalSuppressMessageAttribute : Attribute { public string Category { get; } public string CheckId { get; } public string? Scope { get; set; } public string? Target { get; set; } public string? MessageId { get; set; } public string? Justification { get; set; } public UnconditionalSuppressMessageAttribute(string category, string checkId) { Category = category; CheckId = checkId; } } } 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 = Volatile.Read(ref _mask); int num4 = num & num3; for (Entry entry = _entries[num4]; 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; Volatile.Write(ref _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) || StringUtils.IndexOf(text, '.') != -1 || StringUtils.IndexOf(text, 'E') != -1 || StringUtils.IndexOf(text, 'e') != -1) { return text; } return text + ".0"; } private static string EnsureDecimalPlace(string text) { if (StringUtils.IndexOf(text, '.') != -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] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeObject(object? value) { return SerializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeObject(object? value, Formatting formatting) { return SerializeObject(value, formatting, (JsonSerializerSettings?)null); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] 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] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] 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] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeObject(object? value, JsonSerializerSettings? settings) { return SerializeObject(value, null, settings); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); return SerializeObjectInternal(value, type, jsonSerializer); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings) { return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] 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); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] 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] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static object? DeserializeObject(string value) { return DeserializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static object? DeserializeObject(string value, JsonSerializerSettings settings) { return DeserializeObject(value, null, settings); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static object? DeserializeObject(string value, Type type) { return DeserializeObject(value, type, (JsonSerializerSettings?)null); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static T? DeserializeObject<T>(string value) { return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings?)null); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject) { return DeserializeObject<T>(value); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings) { return DeserializeObject<T>(value, settings); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static T? DeserializeObject<T>(string value, params JsonConverter[] converters) { return (T)DeserializeObject(value, typeof(T), converters); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings) { return (T)DeserializeObject(value, typeof(T), settings); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] 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); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] 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] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static void PopulateObject(string value, object target) { PopulateObject(value, target, null); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] 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."); } } } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeXmlNode(XmlNode? node) { return SerializeXmlNode(node, Formatting.None); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeXmlNode(XmlNode? node, Formatting formatting) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); return SerializeObject(node, formatting, xmlNodeConverter); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, xmlNodeConverter); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static XmlDocument? DeserializeXmlNode(string value) { return DeserializeXmlNode(value, null); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute: false); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] 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); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeXNode(XObject? node) { return SerializeXNode(node, Formatting.None); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeXNode(XObject? node, Formatting formatting) { return SerializeXNode(node, formatting, omitRootObject: false); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, xmlNodeConverter); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static XDocument? DeserializeXNode(string value) { return DeserializeXNode(value, null); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute: false); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] 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); } } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] 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.GetValueOrDefault(DateTimeZoneHandling.RoundtripKind); } set { _dateTimeZoneHandling = value; } } public virtual DateParseHandling DateParseHandling { get { return _dateParseHandling.GetValueOrDefault(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; } internal 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