Decompiled source of Save and Load All Weapons Items and Stats v0.0.7
SaveLoadWeaponsItemsStats.dll
Decompiled 10 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Data.SqlTypes; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Numerics; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Versioning; using System.Security; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using Assets.Scripts.Inventory__Items__Pickups; using Assets.Scripts.Inventory__Items__Pickups.Items; using Assets.Scripts.Inventory__Items__Pickups.Stats; using Assets.Scripts.Inventory__Items__Pickups.Weapons; using Assets.Scripts.Inventory__Items__Pickups.Weapons.WeaponPassives; using Assets.Scripts.Menu.Shop; using Assets.Scripts.UI.InGame.Levelup; using Assets.Scripts.Utility; using Assets.Scripts._Data.Tomes; using BepInEx; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using HarmonyLib; using Il2CppInterop.Runtime; using Il2CppInterop.Runtime.Attributes; using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using Inventory__Items__Pickups.Xp_and_Levels; using MelonLoader; using Microsoft.CodeAnalysis; using Newtonsoft.Json; 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; using SaveLoadWeaponsItemsStats; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("SaveLoadWeapons")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SaveLoadWeapons")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("a052f8b9-b678-40b0-a576-d1c5418579fb")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace SaveLoadWeaponsItemsStats { public static class Il2CppJsonSerializer { public static bool typeIdentified = false; public static bool vanillaJsonType = false; public static Type newtonsoftJsonType = Type.GetType("Newtonsoft.Json.JsonConvert, Newtonsoft.Json"); public static bool IsVanillaJson() { return true; } public static string ToJson(object obj) { return ""; } public static string ToJson(Object obj) { return ""; } public static T FromJson<T>(string json) where T : new() { new T(); return new T(); } } } namespace SaveLoadWeapons { public class WeaponBasic { public bool enabled; public int level; public WeaponPassive passive; public List<List<StatModifier>> upgrades; public float usedWeaponAtTime; public WeaponData weaponData; public Dictionary<EStat, float> weaponStats; public WeaponBasic() { enabled = true; level = 1; passive = null; upgrades = new List<List<StatModifier>>(); usedWeaponAtTime = 0f; weaponData = null; weaponStats = new Dictionary<EStat, float>(); } } public class WeaponBasicIl2Cpp : Object { public bool enabled; public int level; public WeaponPassive passive; public List<List<StatModifier>> upgrades; public float usedWeaponAtTime; public WeaponData weaponData; public Dictionary<EStat, float> weaponStats; public WeaponBasicIl2Cpp(IntPtr ptr) : base(ptr) { } [HideFromIl2Cpp] public static WeaponBasicIl2Cpp FromManaged(WeaponBasic wb) { //IL_018c: Unknown result type (might be due to invalid IL or missing references) WeaponBasicIl2Cpp weaponBasicIl2Cpp = new WeaponBasicIl2Cpp(IL2CPP.il2cpp_object_new(Il2CppClassPointerStore<WeaponBasicIl2Cpp>.NativeClassPtr)); if (wb == null) { MelonLogger.Msg("Initializing null WeaponBasicIl2Cpp."); weaponBasicIl2Cpp.enabled = true; weaponBasicIl2Cpp.level = 1; weaponBasicIl2Cpp.passive = null; weaponBasicIl2Cpp.upgrades = new List<List<StatModifier>>(); weaponBasicIl2Cpp.usedWeaponAtTime = 0f; weaponBasicIl2Cpp.weaponData = null; weaponBasicIl2Cpp.weaponStats = new Dictionary<EStat, float>(); return weaponBasicIl2Cpp; } MelonLogger.Msg("Creating full WeaponBasicIl2Cpp."); weaponBasicIl2Cpp.enabled = wb.enabled; weaponBasicIl2Cpp.level = wb.level; weaponBasicIl2Cpp.passive = wb.passive; if (wb.upgrades != null) { MelonLogger.Msg("Adding upgrades list."); weaponBasicIl2Cpp.upgrades = new List<List<StatModifier>>(); foreach (List<StatModifier> upgrade in wb.upgrades) { if (upgrade != null) { List<StatModifier> val = new List<StatModifier>(); foreach (StatModifier item in upgrade) { val.Add(item); } weaponBasicIl2Cpp.upgrades.Add(val); } else { weaponBasicIl2Cpp.upgrades.Add((List<StatModifier>)null); } } } else { weaponBasicIl2Cpp.upgrades = null; } weaponBasicIl2Cpp.usedWeaponAtTime = wb.usedWeaponAtTime; weaponBasicIl2Cpp.weaponData = wb.weaponData; weaponBasicIl2Cpp.weaponStats = new Dictionary<EStat, float>(); MelonLogger.Msg("Adding weapon stats."); if (wb.weaponStats != null) { foreach (KeyValuePair<EStat, float> weaponStat in wb.weaponStats) { weaponBasicIl2Cpp.weaponStats.Add(weaponStat.Key, weaponStat.Value); } } else { weaponBasicIl2Cpp.weaponStats = null; } return weaponBasicIl2Cpp; } [HideFromIl2Cpp] public WeaponBasicIl2Cpp() { MelonLogger.Msg("Initializing blank WeaponBasicIl2Cpp."); enabled = true; level = 1; passive = null; upgrades = new List<List<StatModifier>>(); usedWeaponAtTime = 0f; weaponData = null; weaponStats = new Dictionary<EStat, float>(); } [HideFromIl2Cpp] public WeaponBasicIl2Cpp(WeaponBasic wb) { //IL_0180: Unknown result type (might be due to invalid IL or missing references) if (wb == null) { MelonLogger.Msg("Initializing null WeaponBasicIl2Cpp."); enabled = true; level = 1; passive = null; upgrades = new List<List<StatModifier>>(); usedWeaponAtTime = 0f; weaponData = null; weaponStats = new Dictionary<EStat, float>(); return; } MelonLogger.Msg("Creating full WeaponBasicIl2Cpp."); enabled = wb.enabled; level = wb.level; passive = wb.passive; if (wb.upgrades != null) { MelonLogger.Msg("Adding upgrades list."); upgrades = new List<List<StatModifier>>(); foreach (List<StatModifier> upgrade in wb.upgrades) { if (upgrade != null) { List<StatModifier> val = new List<StatModifier>(); foreach (StatModifier item in upgrade) { val.Add(item); } upgrades.Add(val); } else { upgrades.Add((List<StatModifier>)null); } } } else { upgrades = null; } usedWeaponAtTime = wb.usedWeaponAtTime; weaponData = wb.weaponData; weaponStats = new Dictionary<EStat, float>(); MelonLogger.Msg("Adding weapon stats."); if (wb.weaponStats != null) { foreach (KeyValuePair<EStat, float> weaponStat in wb.weaponStats) { weaponStats.Add(weaponStat.Key, weaponStat.Value); } return; } weaponStats = null; } } public class GenStatContainer { public Dictionary<EStatModifyType, StatModifier> statContainers; public GenStatContainer() { statContainers = new Dictionary<EStatModifyType, StatModifier>(); } } public class GenStatContainerIl2Cpp { public Dictionary<EStatModifyType, StatModifier> statContainers; public GenStatContainerIl2Cpp(GenStatContainer gsm) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) statContainers = new Dictionary<EStatModifyType, StatModifier>(); foreach (KeyValuePair<EStatModifyType, StatModifier> statContainer in gsm.statContainers) { statContainers.Add(statContainer.Key, statContainer.Value); } } } public class ItemBasic { public int amount; public string damageSource; public ItemInventory itemInventoryRef; public Dictionary<EStat, GenStatContainer> statModifiers; public ItemBasic() { amount = 0; damageSource = ""; itemInventoryRef = null; statModifiers = new Dictionary<EStat, GenStatContainer>(); } } public class ItemBasicIl2Cpp { public int amount; public string damageSource; public ItemInventory itemInventoryRef; public Dictionary<EStat, GenStatContainerIl2Cpp> statModifiers; public ItemBasicIl2Cpp(ItemBasic ib) { //IL_0060: Unknown result type (might be due to invalid IL or missing references) amount = ib.amount; damageSource = ib.damageSource; itemInventoryRef = ib.itemInventoryRef; statModifiers = new Dictionary<EStat, GenStatContainerIl2Cpp>(); foreach (KeyValuePair<EStat, GenStatContainer> statModifier in ib.statModifiers) { GenStatContainerIl2Cpp genStatContainerIl2Cpp = new GenStatContainerIl2Cpp(statModifier.Value); statModifiers.Add(statModifier.Key, genStatContainerIl2Cpp); } } } public class GenTomeInventory { public static Action<ETome, EStat> A_TomeUpgrade; public bool isMaxed; public Dictionary<EStat, HashSet<ETome>> statToTomes; public Dictionary<ETome, int> tomeLevels; public Dictionary<ETome, StatModifier> tomeUpgrade; public GenTomeInventory() { A_TomeUpgrade = null; isMaxed = false; statToTomes = new Dictionary<EStat, HashSet<ETome>>(); tomeLevels = new Dictionary<ETome, int>(); tomeUpgrade = new Dictionary<ETome, StatModifier>(); } } public class GenTomeInventoryIl2Cpp { public static Action<ETome, EStat> A_TomeUpgrade; public bool isMaxed; public Dictionary<EStat, HashSet<ETome>> statToTomes; public Dictionary<ETome, int> tomeLevels; public Dictionary<ETome, StatModifier> tomeUpgrade; public GenTomeInventoryIl2Cpp(GenTomeInventory gti) { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) A_TomeUpgrade = GenTomeInventory.A_TomeUpgrade; isMaxed = gti.isMaxed; statToTomes = new Dictionary<EStat, HashSet<ETome>>(); foreach (KeyValuePair<EStat, HashSet<ETome>> statToTome in gti.statToTomes) { HashSet<ETome> val = new HashSet<ETome>(); foreach (ETome item in statToTome.Value) { val.Add(item); } statToTomes.Add(statToTome.Key, val); } tomeLevels = new Dictionary<ETome, int>(); foreach (KeyValuePair<ETome, int> tomeLevel in gti.tomeLevels) { tomeLevels.Add(tomeLevel.Key, tomeLevel.Value); } tomeUpgrade = new Dictionary<ETome, StatModifier>(); foreach (KeyValuePair<ETome, StatModifier> item2 in gti.tomeUpgrade) { tomeUpgrade.Add(item2.Key, item2.Value); } } } public class GenItemInventory { public Dictionary<EItem, ItemBasic> items; public GenItemInventory() { items = new Dictionary<EItem, ItemBasic>(); } } public class GenItemInventoryIl2Cpp { public Dictionary<EItem, ItemBasicIl2Cpp> items; public GenItemInventoryIl2Cpp(GenItemInventory gii) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) items = new Dictionary<EItem, ItemBasicIl2Cpp>(); foreach (KeyValuePair<EItem, ItemBasic> item in gii.items) { ItemBasicIl2Cpp itemBasicIl2Cpp = new ItemBasicIl2Cpp(item.Value); items.Add(item.Key, itemBasicIl2Cpp); } } } [BepInPlugin("mike9k1.megabonk.saveloadweapons", "Save and Load All Weapons Items and Stats", "0.0.7")] public class SaveLoadWeaponsClass : MelonMod { public new const string PLUGIN_GUID = "mike9k1.megabonk.saveloadweapons"; public new const string PLUGIN_NAME = "Save and Load All Weapons Items and Stats"; public new const string PLUGIN_VERSION = "0.0.7"; public static string savesDirectory = "BepInEx\\plugins\\SavedLoadouts\\"; private string RefreshTypeName = "PlayerInventory"; private string RefreshMethodName = "Update"; private static PlayerInventory currentInventory; private static WeaponInventory savedWeaponInventory; private static TomeInventory savedTomeInventory; private static ItemInventory savedItemInventory; private static Dictionary<EStat, float> savedRawStats; private static Dictionary<EStat, float> savedPlayerStats; private static StatInventory savedStatInventory; private static PlayerStatusEffects savedStatusEffects; private static PlayerXp savedPlayerXp; private static float savedChestPriceMultiplier = 1f; private static LevelupScreen lvlScreen; private static EncounterWindows encWindow; private static int selectedSaveSlot = 0; private static void SavePostfix(PlayerInventory __instance) { currentInventory = __instance; } private static void SaveAllItems() { //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_023d: Unknown result type (might be due to invalid IL or missing references) //IL_025a: Unknown result type (might be due to invalid IL or missing references) //IL_033a: Unknown result type (might be due to invalid IL or missing references) //IL_0509: Unknown result type (might be due to invalid IL or missing references) //IL_04bb: Unknown result type (might be due to invalid IL or missing references) //IL_0494: Unknown result type (might be due to invalid IL or missing references) //IL_0499: Unknown result type (might be due to invalid IL or missing references) //IL_049d: Unknown result type (might be due to invalid IL or missing references) //IL_055c: Unknown result type (might be due to invalid IL or missing references) //IL_0753: Unknown result type (might be due to invalid IL or missing references) //IL_084f: Unknown result type (might be due to invalid IL or missing references) //IL_0884: Unknown result type (might be due to invalid IL or missing references) //IL_0703: Unknown result type (might be due to invalid IL or missing references) //IL_06d1: Unknown result type (might be due to invalid IL or missing references) //IL_08d1: Unknown result type (might be due to invalid IL or missing references) //IL_09c8: Unknown result type (might be due to invalid IL or missing references) if (currentInventory == null) { MelonLogger.Msg("No inventory is loaded. Cancelling save"); return; } savedWeaponInventory = currentInventory.weaponInventory; savedTomeInventory = currentInventory.tomeInventory; savedItemInventory = currentInventory.itemInventory; savedRawStats = new Dictionary<EStat, float>(); Enumerator<EStat, float> enumerator = currentInventory.playerStats.rawStats.GetEnumerator(); while (enumerator.MoveNext()) { KeyValuePair<EStat, float> current = enumerator.Current; savedRawStats.Add(current.Key, current.Value); } savedPlayerStats = new Dictionary<EStat, float>(); enumerator = currentInventory.playerStats.stats.GetEnumerator(); while (enumerator.MoveNext()) { KeyValuePair<EStat, float> current2 = enumerator.Current; savedPlayerStats.Add(current2.Key, current2.Value); } savedStatInventory = currentInventory.statInventory; savedStatusEffects = currentInventory.statusEffects; savedPlayerXp = currentInventory.playerXp; Dictionary<EWeapon, WeaponBasic> dictionary = new Dictionary<EWeapon, WeaponBasic>(); Enumerator<EWeapon, WeaponBase> enumerator2 = savedWeaponInventory.weapons.GetEnumerator(); while (enumerator2.MoveNext()) { KeyValuePair<EWeapon, WeaponBase> current3 = enumerator2.Current; WeaponBasic weaponBasic = new WeaponBasic(); weaponBasic.weaponData = null; weaponBasic.enabled = current3.Value.enabled; weaponBasic.level = current3.Value.level; weaponBasic.passive = null; weaponBasic.usedWeaponAtTime = current3.Value.usedWeaponAtTime; if (current3.Value.upgrades != null) { Enumerator<List<StatModifier>> enumerator3 = current3.Value.upgrades.GetEnumerator(); while (enumerator3.MoveNext()) { List<StatModifier> current4 = enumerator3.Current; List<StatModifier> list = new List<StatModifier>(); if (current4 != null) { Enumerator<StatModifier> enumerator4 = current4.GetEnumerator(); while (enumerator4.MoveNext()) { StatModifier current5 = enumerator4.Current; if (current5 != null) { list.Add(current5); } else { list.Add(null); } } } else { list = null; } weaponBasic.upgrades.Add(list); } } else { weaponBasic.upgrades = null; } weaponBasic.weaponStats = new Dictionary<EStat, float>(); enumerator = current3.Value.weaponStats.GetEnumerator(); while (enumerator.MoveNext()) { KeyValuePair<EStat, float> current6 = enumerator.Current; weaponBasic.weaponStats.Add(current6.Key, current6.Value); } dictionary.Add(current3.Key, weaponBasic); } string text = ""; if (Il2CppJsonSerializer.IsVanillaJson()) { MelonLogger.Msg("Vanilla JSON detected. Using Windows method."); text = JsonConvert.SerializeObject(dictionary); } else { MelonLogger.Msg("Built-in JSON detected. Using Il2Cpp method."); Dictionary<EWeapon, WeaponBasicIl2Cpp> val = new Dictionary<EWeapon, WeaponBasicIl2Cpp>(); foreach (KeyValuePair<EWeapon, WeaponBasic> item in dictionary) { MelonLogger.Msg("Creating new il2cpp object."); WeaponBasicIl2Cpp weaponBasicIl2Cpp = WeaponBasicIl2Cpp.FromManaged(item.Value); MelonLogger.Msg("Adding il2cpp object to dictionary."); MelonLogger.Msg($"newWeaponBasic.Pointer = 0x{((Il2CppObjectBase)weaponBasicIl2Cpp).Pointer.ToInt64():x}"); MelonLogger.Msg($"Key type ptr: {Il2CppClassPointerStore<EWeapon>.NativeClassPtr}"); MelonLogger.Msg($"Val type ptr: {((Il2CppObjectBase)weaponBasicIl2Cpp).Pointer}"); val.Add(item.Key, weaponBasicIl2Cpp); } MelonLogger.Msg("Serializing il2cpp dictionary."); text = Il2CppJsonSerializer.newtonsoftJsonType.GetMethod("SerializeObject", new Type[2] { typeof(Object), typeof(Formatting) }).Invoke(null, new object[2] { val, Formatting.Indented }).ToString(); MelonLogger.Msg("Done serializing. Writing to file."); } Directory.CreateDirectory(savesDirectory + "SavedLoadout" + selectedSaveSlot); File.WriteAllText(savesDirectory + "SavedLoadout" + selectedSaveSlot + "\\SavedLoadout" + selectedSaveSlot + "-weapons.json", text); GenTomeInventory genTomeInventory = new GenTomeInventory(); GenTomeInventory.A_TomeUpgrade = TomeInventory.A_TomeUpgrade; genTomeInventory.isMaxed = savedTomeInventory.isMaxed; if (savedTomeInventory.statToTomes != null) { Enumerator<EStat, HashSet<ETome>> enumerator6 = savedTomeInventory.statToTomes.GetEnumerator(); while (enumerator6.MoveNext()) { KeyValuePair<EStat, HashSet<ETome>> current8 = enumerator6.Current; HashSet<ETome> hashSet = new HashSet<ETome>(); if (current8 != null) { Enumerator<ETome> enumerator7 = current8.Value.GetEnumerator(); while (enumerator7.MoveNext()) { ETome current9 = enumerator7.Current; hashSet.Add(current9); } } else { hashSet = null; } genTomeInventory.statToTomes.Add(current8.Key, hashSet); } } else { genTomeInventory.statToTomes = null; } if (savedTomeInventory.tomeLevels != null) { Enumerator<ETome, int> enumerator8 = savedTomeInventory.tomeLevels.GetEnumerator(); while (enumerator8.MoveNext()) { KeyValuePair<ETome, int> current10 = enumerator8.Current; genTomeInventory.tomeLevels.Add(current10.Key, current10.Value); } } else { genTomeInventory.tomeLevels = null; } if (savedTomeInventory.tomeUpgrade != null) { Enumerator<ETome, StatModifier> enumerator9 = savedTomeInventory.tomeUpgrade.GetEnumerator(); while (enumerator9.MoveNext()) { KeyValuePair<ETome, StatModifier> current11 = enumerator9.Current; genTomeInventory.tomeUpgrade.Add(current11.Key, current11.Value); } } else { genTomeInventory.tomeUpgrade = null; } if (Il2CppJsonSerializer.IsVanillaJson()) { text = JsonConvert.SerializeObject(genTomeInventory); } else { GenTomeInventoryIl2Cpp genTomeInventoryIl2Cpp = new GenTomeInventoryIl2Cpp(genTomeInventory); text = Il2CppJsonSerializer.newtonsoftJsonType.GetMethod("SerializeObject", new Type[2] { typeof(Object), typeof(Formatting) }).Invoke(null, new object[2] { genTomeInventoryIl2Cpp, Formatting.Indented }).ToString(); } File.WriteAllText(savesDirectory + "SavedLoadout" + selectedSaveSlot + "\\SavedLoadout" + selectedSaveSlot + "-tomes.json", text); GenItemInventory genItemInventory = new GenItemInventory(); if (savedItemInventory.items != null) { Enumerator<EItem, ItemBase> enumerator10 = savedItemInventory.items.GetEnumerator(); while (enumerator10.MoveNext()) { KeyValuePair<EItem, ItemBase> current12 = enumerator10.Current; ItemBasic itemBasic = new ItemBasic(); if (current12.Value.statModifiers != null) { Enumerator<EStat, StatModifiersContainer> enumerator11 = current12.Value.statModifiers.GetEnumerator(); while (enumerator11.MoveNext()) { KeyValuePair<EStat, StatModifiersContainer> current13 = enumerator11.Current; GenStatContainer genStatContainer = new GenStatContainer(); if (current13 != null) { Enumerator<EStatModifyType, StatModifier> enumerator12 = current13.Value.statContainers.GetEnumerator(); while (enumerator12.MoveNext()) { KeyValuePair<EStatModifyType, StatModifier> current14 = enumerator12.Current; if (current14 != null) { genStatContainer.statContainers.Add(current14.Key, current14.Value); } else { genStatContainer.statContainers = null; } } } else { genStatContainer = null; } itemBasic.statModifiers.Add(current13.Key, genStatContainer); } } else { itemBasic.statModifiers = null; } itemBasic.amount = current12.Value.amount; itemBasic.damageSource = current12.Value.damageSource; genItemInventory.items.Add(current12.Key, itemBasic); } } else { genItemInventory.items = null; } if (Il2CppJsonSerializer.IsVanillaJson()) { text = JsonConvert.SerializeObject(genItemInventory); } else { GenItemInventoryIl2Cpp genItemInventoryIl2Cpp = new GenItemInventoryIl2Cpp(genItemInventory); text = Il2CppJsonSerializer.newtonsoftJsonType.GetMethod("SerializeObject", new Type[2] { typeof(Object), typeof(Formatting) }).Invoke(null, new object[2] { genItemInventoryIl2Cpp, Formatting.Indented }).ToString(); } File.WriteAllText(savesDirectory + "SavedLoadout" + selectedSaveSlot + "\\SavedLoadout" + selectedSaveSlot + "-items.json", text); Dictionary<EStat, float> dictionary2 = new Dictionary<EStat, float>(); Dictionary<EStat, float> dictionary3 = new Dictionary<EStat, float>(); enumerator = savedRawStats.GetEnumerator(); while (enumerator.MoveNext()) { KeyValuePair<EStat, float> current15 = enumerator.Current; dictionary3.Add(current15.Key, current15.Value); } enumerator = savedPlayerStats.GetEnumerator(); while (enumerator.MoveNext()) { KeyValuePair<EStat, float> current16 = enumerator.Current; dictionary2.Add(current16.Key, current16.Value); } if (Il2CppJsonSerializer.IsVanillaJson()) { text = JsonConvert.SerializeObject(dictionary3); } else { Dictionary<EStat, float> val2 = new Dictionary<EStat, float>(); foreach (KeyValuePair<EStat, float> item2 in dictionary3) { val2.Add(item2.Key, item2.Value); } text = Il2CppJsonSerializer.newtonsoftJsonType.GetMethod("SerializeObject", new Type[2] { typeof(Object), typeof(Formatting) }).Invoke(null, new object[2] { val2, Formatting.Indented }).ToString(); } File.WriteAllText(savesDirectory + "SavedLoadout" + selectedSaveSlot + "\\SavedLoadout" + selectedSaveSlot + "-rawStats.json", text); if (Il2CppJsonSerializer.IsVanillaJson()) { text = JsonConvert.SerializeObject(dictionary2); } else { Dictionary<EStat, float> val3 = new Dictionary<EStat, float>(); foreach (KeyValuePair<EStat, float> item3 in dictionary2) { val3.Add(item3.Key, item3.Value); } text = Il2CppJsonSerializer.newtonsoftJsonType.GetMethod("SerializeObject", new Type[2] { typeof(Object), typeof(Formatting) }).Invoke(null, new object[2] { val3, Formatting.Indented }).ToString(); } File.WriteAllText(savesDirectory + "SavedLoadout" + selectedSaveSlot + "\\SavedLoadout" + selectedSaveSlot + "-playerStats.json", text); File.WriteAllText(savesDirectory + "SavedLoadout" + selectedSaveSlot + "\\SavedLoadout" + selectedSaveSlot + "-statInventory.json", text); text = JsonConvert.SerializeObject(savedStatusEffects, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); File.WriteAllText(savesDirectory + "SavedLoadout" + selectedSaveSlot + "\\SavedLoadout" + selectedSaveSlot + "-statusEffects.json", text); text = JsonConvert.SerializeObject(savedPlayerXp, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); File.WriteAllText(savesDirectory + "SavedLoadout" + selectedSaveSlot + "\\SavedLoadout" + selectedSaveSlot + "-playerXp.json", text); MelonLogger.Msg("Saved all weapons/items/stats to slot " + selectedSaveSlot); selectedSaveSlot = 0; } private static void LoadAllItems() { //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Expected O, but got Unknown //IL_084d: Unknown result type (might be due to invalid IL or missing references) //IL_0290: Unknown result type (might be due to invalid IL or missing references) //IL_029a: Expected O, but got Unknown //IL_02f6: Unknown result type (might be due to invalid IL or missing references) //IL_0300: Expected O, but got Unknown //IL_023b: Unknown result type (might be due to invalid IL or missing references) //IL_0268: Unknown result type (might be due to invalid IL or missing references) //IL_0370: Unknown result type (might be due to invalid IL or missing references) //IL_0375: Unknown result type (might be due to invalid IL or missing references) //IL_0379: Unknown result type (might be due to invalid IL or missing references) //IL_03a6: Unknown result type (might be due to invalid IL or missing references) //IL_03f0: Unknown result type (might be due to invalid IL or missing references) //IL_043f: Unknown result type (might be due to invalid IL or missing references) //IL_09d3: Unknown result type (might be due to invalid IL or missing references) //IL_09d8: Unknown result type (might be due to invalid IL or missing references) //IL_09db: Unknown result type (might be due to invalid IL or missing references) //IL_04ba: Unknown result type (might be due to invalid IL or missing references) //IL_04c4: Expected O, but got Unknown //IL_04f1: Unknown result type (might be due to invalid IL or missing references) //IL_04f8: Expected O, but got Unknown //IL_0a27: Unknown result type (might be due to invalid IL or missing references) //IL_06b5: Unknown result type (might be due to invalid IL or missing references) //IL_0610: Unknown result type (might be due to invalid IL or missing references) //IL_0525: Unknown result type (might be due to invalid IL or missing references) //IL_052c: Expected O, but got Unknown //IL_0751: Unknown result type (might be due to invalid IL or missing references) //IL_05a5: Unknown result type (might be due to invalid IL or missing references) //IL_0565: Unknown result type (might be due to invalid IL or missing references) if (currentInventory == null) { MelonLogger.Msg("No inventory is loaded into memory. Cancelling load"); return; } if (savedWeaponInventory == null || selectedSaveSlot > 0) { if (savedWeaponInventory == null) { MelonLogger.Msg("No weapons/items/stats have been recorded in the current session. Checking for save file..."); } if (!File.Exists(savesDirectory + "SavedLoadout" + selectedSaveSlot + "\\SavedLoadout" + selectedSaveSlot + "-weapons.json")) { MelonLogger.Msg("No save files found for weapons/items/stats in slot " + selectedSaveSlot + ". Loading cancelled."); return; } Dictionary<EWeapon, WeaponBasic>? dictionary = JsonConvert.DeserializeObject<Dictionary<EWeapon, WeaponBasic>>(File.ReadAllText(savesDirectory + "SavedLoadout" + selectedSaveSlot + "\\SavedLoadout" + selectedSaveSlot + "-weapons.json")); Dictionary<EWeapon, WeaponBase> val = new Dictionary<EWeapon, WeaponBase>(); DataManager val2 = Object.FindFirstObjectByType<DataManager>(); foreach (KeyValuePair<EWeapon, WeaponBasic> item in dictionary) { WeaponBase val3 = new WeaponBase(val2.GetWeapon(item.Key)); val3.enabled = item.Value.enabled; val3.level = item.Value.level; val3.usedWeaponAtTime = 0f; val3.weaponStats = new Dictionary<EStat, float>(); if (item.Value.upgrades != null) { foreach (List<StatModifier> upgrade in item.Value.upgrades) { List<StatModifier> val4 = new List<StatModifier>(); if (upgrade != null) { foreach (StatModifier item2 in upgrade) { if (item2 != null) { val4.Add(item2); } else { val4.Add((StatModifier)null); } } } else { val4 = null; } val3.upgrades.Add(val4); } } else { val3.upgrades = null; } foreach (KeyValuePair<EStat, float> weaponStat in item.Value.weaponStats) { val3.weaponStats.Add(weaponStat.Key, weaponStat.Value); } val.Add(item.Key, val3); } savedWeaponInventory = new WeaponInventory(); savedWeaponInventory.weapons = val; GenTomeInventory genTomeInventory = JsonConvert.DeserializeObject<GenTomeInventory>(File.ReadAllText(savesDirectory + "SavedLoadout" + selectedSaveSlot + "\\SavedLoadout" + selectedSaveSlot + "-tomes.json")); savedTomeInventory = new TomeInventory(); savedTomeInventory.isMaxed = genTomeInventory.isMaxed; savedTomeInventory.statToTomes.Clear(); savedTomeInventory.tomeLevels.Clear(); savedTomeInventory.tomeUpgrade.Clear(); foreach (KeyValuePair<EStat, HashSet<ETome>> statToTome in genTomeInventory.statToTomes) { HashSet<ETome> val5 = new HashSet<ETome>(); foreach (ETome item3 in statToTome.Value) { val5.Add(item3); } savedTomeInventory.statToTomes.Add(statToTome.Key, val5); } foreach (KeyValuePair<ETome, int> tomeLevel in genTomeInventory.tomeLevels) { savedTomeInventory.tomeLevels.Add(tomeLevel.Key, tomeLevel.Value); } foreach (KeyValuePair<ETome, StatModifier> item4 in genTomeInventory.tomeUpgrade) { savedTomeInventory.tomeUpgrade.Add(item4.Key, item4.Value); } GenItemInventory genItemInventory = JsonConvert.DeserializeObject<GenItemInventory>(File.ReadAllText(savesDirectory + "SavedLoadout" + selectedSaveSlot + "\\SavedLoadout" + selectedSaveSlot + "-items.json")); savedItemInventory = new ItemInventory(); if (genItemInventory.items != null) { foreach (KeyValuePair<EItem, ItemBasic> item5 in genItemInventory.items) { ItemBase val6 = new ItemBase(savedItemInventory); if (item5.Value != null) { foreach (KeyValuePair<EStat, GenStatContainer> statModifier in item5.Value.statModifiers) { StatModifiersContainer val7 = new StatModifiersContainer(); if (statModifier.Value != null) { foreach (KeyValuePair<EStatModifyType, StatModifier> statContainer in statModifier.Value.statContainers) { if (statContainer.Value != null) { val7.statContainers.Add(statContainer.Key, statContainer.Value); } else { val7.statContainers = null; } } } else { val7 = null; } val6.statModifiers.Add(statModifier.Key, val7); } val6.amount = item5.Value.amount; val6.damageSource = item5.Value.damageSource; val6.itemInventoryRef = savedItemInventory; } else { val6 = null; } savedItemInventory.items.Add(item5.Key, val6); } } else { savedItemInventory.items = null; } Dictionary<EStat, float>? dictionary2 = JsonConvert.DeserializeObject<Dictionary<EStat, float>>(File.ReadAllText(savesDirectory + "SavedLoadout" + selectedSaveSlot + "\\SavedLoadout" + selectedSaveSlot + "-rawStats.json")); savedRawStats = new Dictionary<EStat, float>(); foreach (KeyValuePair<EStat, float> item6 in dictionary2) { savedRawStats.Add(item6.Key, item6.Value); } Dictionary<EStat, float>? dictionary3 = JsonConvert.DeserializeObject<Dictionary<EStat, float>>(File.ReadAllText(savesDirectory + "SavedLoadout" + selectedSaveSlot + "\\SavedLoadout" + selectedSaveSlot + "-playerStats.json")); savedPlayerStats = new Dictionary<EStat, float>(); foreach (KeyValuePair<EStat, float> item7 in dictionary3) { savedPlayerStats.Add(item7.Key, item7.Value); } savedPlayerXp = JsonConvert.DeserializeObject<PlayerXp>(File.ReadAllText(savesDirectory + "SavedLoadout" + selectedSaveSlot + "\\SavedLoadout" + selectedSaveSlot + "-playerXp.json")); MelonLogger.Msg("Saved weapons/items/stats loaded from slot " + selectedSaveSlot); selectedSaveSlot = 0; } currentInventory.weaponInventory = savedWeaponInventory; currentInventory.tomeInventory = savedTomeInventory; currentInventory.itemInventory.items.Clear(); Enumerator<EItem, ItemBase> enumerator12 = savedItemInventory.items.GetEnumerator(); while (enumerator12.MoveNext()) { KeyValuePair<EItem, ItemBase> current14 = enumerator12.Current; for (int i = 1; i <= current14.Value.amount; i++) { currentInventory.itemInventory.AddItem(current14.Key); } } currentInventory.playerStats.rawStats = savedRawStats; currentInventory.playerStats.stats = savedPlayerStats; if (savedStatInventory != null) { currentInventory.statInventory = savedStatInventory; } if (savedStatusEffects != null) { currentInventory.statusEffects = savedStatusEffects; } currentInventory.playerXp = savedPlayerXp; lvlScreen = Object.FindFirstObjectByType<LevelupScreen>(); if ((Object)(object)lvlScreen != (Object)null) { lvlScreen.level = savedPlayerXp.level; lvlScreen.currentLevel = savedPlayerXp.level; } else { MelonLogger.Error("Level Screen instance not found. Player level will be updated on next level-up"); } encWindow = Object.FindFirstObjectByType<EncounterWindows>(); if ((Object)(object)encWindow != (Object)null) { encWindow.currentLevel = savedPlayerXp.level; } else { MelonLogger.Error("Level Screen encounter window object not found. Player level will be updated on next level-up"); } XpBarUI val8 = Object.FindFirstObjectByType<XpBarUI>(); if ((Object)(object)val8 != (Object)null) { val8.Refresh(savedPlayerXp); } else { MelonLogger.Error("XP UI not found. Player XP will show when some is collected"); } InventoryHud val9 = Object.FindFirstObjectByType<InventoryHud>(); if ((Object)(object)val9 != (Object)null) { val9.Refresh(); } else { MelonLogger.Error("Inventory HUD not found. Inventory UI will update on next level-up"); } ItemsHud val10 = Object.FindFirstObjectByType<ItemsHud>(); if ((Object)(object)val10 != (Object)null) { foreach (EItem value in Enum.GetValues(typeof(EItem))) { val10.OnItemRemoved(value, false); } enumerator12 = savedItemInventory.items.GetEnumerator(); while (enumerator12.MoveNext()) { KeyValuePair<EItem, ItemBase> current15 = enumerator12.Current; for (int j = 1; j <= current15.Value.amount; j++) { val10.OnItemAdded(current15.Key); } } } else { MelonLogger.Error("Items HUD not found. Items listed at the bottom will update if level changes"); } } private static Type FindType(string fullName) { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { try { Type type = assembly.GetType(fullName, throwOnError: false); if (type != null) { return type; } } catch { } } return null; } private void TryPatch() { //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Expected O, but got Unknown Type type = FindType(RefreshTypeName); if (type == null) { MelonLogger.Error("Type not found: " + RefreshTypeName); return; } MethodInfo method = type.GetMethod(RefreshMethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (method == null) { MelonLogger.Error("Method not found: " + type.FullName + "." + RefreshMethodName + "()"); } else { HarmonyMethod val = new HarmonyMethod(typeof(SaveLoadWeaponsClass).GetMethod("SavePostfix", BindingFlags.Static | BindingFlags.NonPublic)); HarmonyInstance.Patch((MethodBase)method, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); MelonLogger.Msg("Patched " + type.FullName + "." + RefreshMethodName + "()"); } } public override void OnInitializeMelon() { ClassInjector.RegisterTypeInIl2Cpp<WeaponBasicIl2Cpp>(); new Dictionary<EWeapon, WeaponBasicIl2Cpp>(); TryPatch(); } public override void OnFixedUpdate() { if (Input.GetKeyDown((KeyCode)117)) { MelonLogger.Msg("Save key pressed. Saving all Weapons Items and Stats."); SaveAllItems(); } if (Input.GetKeyDown((KeyCode)108)) { MelonLogger.Msg("Load key pressed. Loading all Weapons Items and Stats."); LoadAllItems(); } if (Input.GetKey((KeyCode)117) && (Input.GetKeyDown((KeyCode)49) || Input.GetKeyDown((KeyCode)257))) { selectedSaveSlot = 1; SaveAllItems(); } if (Input.GetKey((KeyCode)117) && (Input.GetKeyDown((KeyCode)50) || Input.GetKeyDown((KeyCode)258))) { selectedSaveSlot = 2; SaveAllItems(); } if (Input.GetKey((KeyCode)117) && (Input.GetKeyDown((KeyCode)51) || Input.GetKeyDown((KeyCode)259))) { selectedSaveSlot = 3; SaveAllItems(); } if (Input.GetKey((KeyCode)117) && (Input.GetKeyDown((KeyCode)52) || Input.GetKeyDown((KeyCode)260))) { selectedSaveSlot = 4; SaveAllItems(); } if (Input.GetKey((KeyCode)117) && (Input.GetKeyDown((KeyCode)53) || Input.GetKeyDown((KeyCode)261))) { selectedSaveSlot = 5; SaveAllItems(); } if (Input.GetKey((KeyCode)117) && (Input.GetKeyDown((KeyCode)54) || Input.GetKeyDown((KeyCode)262))) { selectedSaveSlot = 6; SaveAllItems(); } if (Input.GetKey((KeyCode)117) && (Input.GetKeyDown((KeyCode)55) || Input.GetKeyDown((KeyCode)263))) { selectedSaveSlot = 7; SaveAllItems(); } if (Input.GetKey((KeyCode)117) && (Input.GetKeyDown((KeyCode)56) || Input.GetKeyDown((KeyCode)264))) { selectedSaveSlot = 8; SaveAllItems(); } if (Input.GetKey((KeyCode)117) && (Input.GetKeyDown((KeyCode)57) || Input.GetKeyDown((KeyCode)265))) { selectedSaveSlot = 9; SaveAllItems(); } if (Input.GetKey((KeyCode)108) && (Input.GetKeyDown((KeyCode)49) || Input.GetKeyDown((KeyCode)257))) { selectedSaveSlot = 1; LoadAllItems(); } if (Input.GetKey((KeyCode)108) && (Input.GetKeyDown((KeyCode)50) || Input.GetKeyDown((KeyCode)258))) { selectedSaveSlot = 2; LoadAllItems(); } if (Input.GetKey((KeyCode)108) && (Input.GetKeyDown((KeyCode)51) || Input.GetKeyDown((KeyCode)259))) { selectedSaveSlot = 3; LoadAllItems(); } if (Input.GetKey((KeyCode)108) && (Input.GetKeyDown((KeyCode)52) || Input.GetKeyDown((KeyCode)260))) { selectedSaveSlot = 4; LoadAllItems(); } if (Input.GetKey((KeyCode)108) && (Input.GetKeyDown((KeyCode)53) || Input.GetKeyDown((KeyCode)261))) { selectedSaveSlot = 5; LoadAllItems(); } if (Input.GetKey((KeyCode)108) && (Input.GetKeyDown((KeyCode)54) || Input.GetKeyDown((KeyCode)262))) { selectedSaveSlot = 6; LoadAllItems(); } if (Input.GetKey((KeyCode)108) && (Input.GetKeyDown((KeyCode)55) || Input.GetKeyDown((KeyCode)263))) { selectedSaveSlot = 7; LoadAllItems(); } if (Input.GetKey((KeyCode)108) && (Input.GetKeyDown((KeyCode)56) || Input.GetKeyDown((KeyCode)264))) { selectedSaveSlot = 8; LoadAllItems(); } if (Input.GetKey((KeyCode)108) && (Input.GetKeyDown((KeyCode)57) || Input.GetKeyDown((KeyCode)265))) { selectedSaveSlot = 9; LoadAllItems(); } } } } namespace MelonLoader { public class MelonMod : BasePlugin { public Harmony HarmonyInstance; public static MelonMod melonModRef; public virtual string PLUGIN_GUID => "author.game.modname"; public virtual string PLUGIN_NAME => "Mod Name Here"; public virtual string PLUGIN_VERSION => "0.0.1"; public MelonMod() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown HarmonyInstance = new Harmony(PLUGIN_GUID); melonModRef = this; } public virtual void OnInitializeMelon() { } public virtual void OnLateInitializeMelon() { } public virtual void OnFixedUpdate() { } public virtual void OnUpdate() { } public override void Load() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown OnInitializeMelon(); HarmonyMethod val = new HarmonyMethod(typeof(MelonMod).GetMethod("FixedUpdate")); HarmonyInstance.Patch((MethodBase)typeof(MyTime).GetMethod("FixedUpdate"), (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); HarmonyMethod val2 = new HarmonyMethod(typeof(MelonMod).GetMethod("Update")); HarmonyInstance.Patch((MethodBase)typeof(MyTime).GetMethod("Update"), (HarmonyMethod)null, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } public void Awake() { OnLateInitializeMelon(); } public static void FixedUpdate() { melonModRef.OnFixedUpdate(); } public static void Update() { melonModRef.OnUpdate(); } } public class MelonLogger { private static ManualLogSource log; private static bool logAdded; public static void Msg(string message) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown if (!logAdded) { log = new ManualLogSource(((AssemblyTitleAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), inherit: false)[0]).Title); Logger.Sources.Add((ILogSource)(object)log); logAdded = true; } log.LogInfo((object)message); } public static void Error(string message) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown if (!logAdded) { log = new ManualLogSource(((AssemblyTitleAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), inherit: false)[0]).Title); Logger.Sources.Add((ILogSource)(object)log); logAdded = true; } log.LogError((object)message); } } } 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; } } } 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 ((BigInteger)(ref value)).ToString((string)null, (IFormatProvider)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 == (Uri)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) { //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Expected O, but got Unknown if (value == null) { return Null; } return ConvertUtils.GetTypeCode(value.GetType()) switch { PrimitiveTypeCode.String => ToString((string)value), PrimitiveTypeCode.Char => ToString((char)value), PrimitiveTypeCode.Boolean => ToString((bool)value), PrimitiveTypeCode.SByte => ToString((sbyte)value), PrimitiveTypeCode.Int16 => ToString((short)value), PrimitiveTypeCode.UInt16 => ToString((ushort)value), PrimitiveTypeCode.Int32 => ToString((int)value), PrimitiveTypeCode.Byte => ToString((byte)value), PrimitiveTypeCode.UInt32 => ToString((uint)value), PrimitiveTypeCode.Int64 => ToString((long)value), PrimitiveTypeCode.UInt64 => ToString((ulong)value), PrimitiveTypeCode.Single => ToString((float)value), PrimitiveTypeCode.Double => ToString((double)value), PrimitiveTypeCode.DateTime => ToString((DateTime)value), PrimitiveTypeCode.Decimal => ToString((decimal)value), PrimitiveTypeCode.DBNull => Null, PrimitiveTypeCode.DateTimeOffset => ToString((DateTimeOffset)value), PrimitiveTypeCode.Guid => ToString((Guid)value), PrimitiveTypeCode.Uri => ToString((Uri)value), PrimitiveTypeCode.TimeSpan => ToString((TimeSpan)value), PrimitiveTypeCode.BigInteger => ToStringInternal((BigInteger)value), _ => throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())), }; } [DebuggerStepThrough] public static string SerializeObject(object? value) { return SerializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting) { return SerializeObject(value, formatting, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static string SerializeObject(object? value, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, JsonSerializerSettings? settings) { return SerializeObject(value, null, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); return SerializeObjectInternal(value, type, jsonSerializer); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings) { return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); jsonSerializer.Formatting = formatting; return SerializeObjectInternal(value, type, jsonSerializer); } private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer) { StringWriter stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture); using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter)) { jsonTextWriter.Formatting = jsonSerializer.Formatting; jsonSerializer.Serialize(jsonTextWriter, value, type); } return stringWriter.ToString(); } [DebuggerStepThrough] public static object? DeserializeObject(string value) { return DeserializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static object? DeserializeObject(string value, JsonSerializerSettings settings) { return DeserializeObject(value, null, settings); } [DebuggerStepThrough] public static object? DeserializeObject(string value, Type type) { return DeserializeObject(value, type, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value) { return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject) { return DeserializeObject<T>(value); } [DebuggerStepThrough] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings) { return DeserializeObject<T>(value, settings); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value, params JsonConverter[] converters) { return (T)DeserializeObject(value, typeof(T), converters); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings) { return (T)DeserializeObject(value, typeof(T), settings); } [DebuggerStepThrough] public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return DeserializeObject(value, type, settings); } public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings) { ValidationUtils.ArgumentNotNull(value, "value"); JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); if (!jsonSerializer.IsCheckAdditionalContentSet()) { jsonSerializer.CheckAdditionalContent = true; } using JsonTextReader reader = new JsonTextReader(new StringReader(value)); return jsonSerializer.Deserialize(reader, type); } [DebuggerStepThrough] public static void PopulateObject(string value, object target) { PopulateObject(value, target, null); } public static void PopulateObject(string value, object target, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); using JsonReader jsonReader = new JsonTextReader(new StringReader(value)); jsonSerializer.Populate(jsonReader, target); if (settings == null || !settings.CheckAdditionalContent) { return; } while (jsonReader.Read()) { if (jsonReader.TokenType != JsonToken.Comment) { throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object."); } } } public static string SerializeXmlNode(XmlNode? node) { return SerializeXmlNode(node, Formatting.None); } public static string SerializeXmlNode(XmlNode? node, Formatting formatting) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); return SerializeObject(node, formatting, xmlNodeConverter); } public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, xmlNodeConverter); } public static XmlDocument? DeserializeXmlNode(string value) { return DeserializeXmlNode(value, null); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute: false); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { //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 (XmlDocument)DeserializeObject(value, typeof(XmlDocument), xmlNodeConverter); } public static string SerializeXNode(XObject? node) { return SerializeXNode(node, Formatting.None); } public static string SerializeXNode(XObject? node, Formatting formatting) { return SerializeXNode(node, formatting, omitRootObject: false); } public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, xmlNodeConverter); } public static XDocument? DeserializeXNode(string value) { return DeserializeXNode(value, null); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute: false); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName; xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute; xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters; return (XDocument)DeserializeObject(value, typeof(XDocument), xmlNodeConverter); } } public abstract class JsonConverter { public virtual bool CanRead => true; public virtual bool CanWrite => true; public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer); public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer); public abstract bool CanConvert(Type objectType); } public abstract class JsonConverter<T> : JsonConverter { public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (!((value != null) ? (value is T) : ReflectionUtils.IsNullable(typeof(T)))) { throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } WriteJson(writer, (T)value, serializer); } public abstract void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer); public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { bool flag = existingValue == null; if (!flag && !(existingValue is T)) { throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } return ReadJson(reader, objectType, flag ? default(T) : ((T)existingValue), !flag, serializer); } public abstract T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer); public sealed override bool CanConvert(Type objectType) { return typeof(T).IsAssignableFrom(objectType); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonConverterAttribute : Attribute { private readonly Type _converterType; public Type ConverterType => _converterType; public object[]? ConverterParameters { get; } public JsonConverterAttribute(Type converterType) { if (converterType == null) { throw new ArgumentNullException("converterType"); } _converterType = converterType; } public JsonConverterAttribute(Type converterType, params object[] converterParameters) : this(converterType) { ConverterParameters = converterParameters; } } public class JsonConverterCollection : Collection<JsonConverter> { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonDictionaryAttribute : JsonContainerAttribute { public JsonDictionaryAttribute() { } public JsonDictionaryAttribute(string id) : base(id) { } } [Serializable] public class JsonException : Exception { public JsonException() { } public JsonException(string message) : base(message) { } public JsonException(string message, Exception? innerException) : base(message, innerException) { } public JsonException(SerializationInfo info, StreamingContext context) : base(info, context) { } internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message) { message = JsonPosition.FormatMessage(lineInfo, path, message); return new JsonException(message); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class JsonExtensionDataAttribute : Attribute { public bool WriteData { get; set; } public bool ReadData { get; set; } public JsonExtensionDataAttribute() { WriteData = true; ReadData = true; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonIgnoreAttribute : Attribute { } public abstract class JsonNameTable { public abstract string? Get(char[] key, int start, int length); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonObjectAttribute : JsonContainerAttribute { private MemberSerialization _memberSerialization; internal MissingMemberHandling? _missingMemberHandling; internal Required? _itemRequired; internal NullValueHandling? _itemNullValueHandling; public MemberSerialization MemberSerialization { get { return _memberSerialization; } set { _memberSerialization = value; } } public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling.GetValueOrDefault(); } set { _missingMemberHandling = value; } } public NullValueHandling ItemNullValueHandling { get { return _itemNullValueHandling.GetValueOrDefault(); } set { _itemNullValueHandling = value; } } public Required ItemRequired { get { return _itemRequired.GetValueOrDefault(); } set { _itemRequired = value; } } public JsonObjectAttribute() { } public JsonObjectAttribute(MemberSerialization memberSerialization) { MemberSerialization = memberSerialization; } public JsonObjectAttribute(string id) : base(id) { } } internal enum JsonContainerType { None, Object, Array, Constructor } internal struct JsonPosition { private static readonly char[] SpecialCharacters = new char[18] { '.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t', '\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029' }; internal JsonContainerType Type; internal int Position; internal string? PropertyName; internal bool HasIndex; public JsonPosition(JsonContainerType type) { Type = type; HasIndex = TypeHasIndex(type); Position = -1; PropertyName = null; } internal int CalculateLength() { switch (Type) { case JsonContainerType.Object: return PropertyName.Length + 5; case JsonContainerType.Array: case JsonContainerType.Constructor: return MathUtils.IntLength((ulong)Position) + 2; default: throw new ArgumentOutOfRangeException("Type"); } } internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer) { switch (Type) { case JsonContainerType.Object: { string propertyName = PropertyName; if (propertyName.IndexOfAny(SpecialCharacters) != -1) { sb.Append("['"); if (writer == null) { writer = new StringWriter(sb); } JavaScriptUtils.WriteEscapedJavaScriptString(writer, propertyName, '\'', appendDelimiters: false, JavaScriptUtils.SingleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer); sb.Append("']"); } else { if (sb.Length > 0) { sb.Append('.'); } sb.Append(propertyName); } break; } case JsonContainerType.Array: case JsonContainerType.Constructor: sb.Append('['); sb.Append(Position); sb.Append(']'); break; } } internal static bool TypeHasIndex(JsonContainerType type) { if (type != JsonContainerType.Array) { return type == JsonContainerType.Constructor; } return true; } internal static string BuildPath(List<JsonPosition> positions, JsonPosition? currentPosition) { int num = 0; if (positions != null) { for (int i = 0; i < positions.Count; i++) { num += positions[i].CalculateLength(); } } if (currentPosition.HasValue) { num += currentPosition.GetValueOrDefault().CalculateLength(); } StringBuilder stringBuilder = new StringBuilder(num); StringWriter writer = null; char[] buffer = null; if (positions != null) { foreach (JsonPosition position in positions) { position.WriteTo(stringBuilder, ref writer, ref buffer); } } currentPosition?.WriteTo(stringBuilder, ref writer, ref buffer); return stringBuilder.ToString(); } internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message) { if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal)) { message = message.Trim(); if (!message.EndsWith('.')) { 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 : IAsyncDisposable, 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; } } ValueTask IAsyncDisposable.DisposeAsync() { try { Dispose(disposing: true); return default(ValueTask); } catch (Exception exception) { return ValueTask.FromException(exception); } } 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() { //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) 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 val) { num = (int)val; } 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; if (value is IFormattable formattable) { text = formattable.ToString(null, Culture); } else { Uri val = (Uri)((value is Uri) ? value : null); text = ((val != null) ? val.OriginalString : value.ToString()); } 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() { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) 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 val)) ? Convert.ToDouble(value, CultureInfo.InvariantCulture) : ((double)val)); 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() { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) 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 val)) ? Convert.ToBoolean(Value, CultureInfo.InvariantCulture) : (val != 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() { //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) 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 val) { num = (decimal)val; } 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, DateTimeZon