Decompiled source of D20Plugin v2.4.0

D20Plugin.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Bounce.ManagedCollections;
using Bounce.Singletons;
using Bounce.Unmanaged;
using Dice;
using GameChat.UI;
using HarmonyLib;
using ModdingTales;
using Newtonsoft.Json;
using RadialUI;
using TMPro;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("D20Plugin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Nth Dimension")]
[assembly: AssemblyProduct("D20Plugin")]
[assembly: AssemblyCopyright("Copyright ©  2026")]
[assembly: AssemblyTrademark("D20Plugin")]
[assembly: ComVisible(false)]
[assembly: Guid("c303405d-e66c-4316-9cdb-4e3ca15c6360")]
[assembly: AssemblyFileVersion("2.4.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("2.4.0.0")]
namespace LordAshes;

[BepInPlugin("org.lordashes.plugins.d20", "D20 Plugin", "2.4.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class PluginD20 : BaseUnityPlugin
{
	public static class Characters
	{
		public class SpecPair
		{
			public string key { get; set; } = "key";


			public string value { get; set; } = "Undefined";


			public SpecPair()
			{
			}

			public SpecPair(string key)
			{
				this.key = key;
				value = "Undefined";
			}

			public SpecPair(string key, string value)
			{
				this.key = key;
				this.value = value;
			}
		}

		public class Spec
		{
			public string name { get; set; } = "Skill";


			public string formula { get; set; } = null;


			public List<SpecPair> extra { get; set; } = null;


			public string menu { get; set; } = null;


			public Spec(string name, string formula, List<SpecPair> extra = null, string menu = null)
			{
				this.name = name;
				this.formula = formula;
				this.extra = extra;
				this.menu = menu;
			}

			public string Extra(string name)
			{
				return extra.Where((SpecPair e) => e.key == name).FirstOrDefault()?.value;
			}
		}

		public class CharacterSpecs
		{
			public string name { get; set; } = "Unnamed";


			public string chainSources { get; set; } = null;


			public List<Spec> specs { get; set; } = new List<Spec>();


			public void AddAbilityScore(string name, string value, string menu = null)
			{
				specs.Add(new Spec(name, ((int.Parse(value) >= 10) ? ((int.Parse(value) - 10) / 2) : ((int.Parse(value) - 11) / 2)).ToString(), new List<SpecPair>
				{
					new SpecPair("type", "ability"),
					new SpecPair("value", value)
				}, menu));
			}

			public void AddValue(string name, string value, string menu = null)
			{
				specs.Add(new Spec(name, value, new List<SpecPair>
				{
					new SpecPair("type", "value")
				}, menu));
			}

			public void AddSave(string name, string formula, string menu = null)
			{
				specs.Add(new Spec(name, formula, new List<SpecPair>
				{
					new SpecPair("type", "save")
				}, menu));
			}

			public void AddSkill(string name, string formula, string menu = null)
			{
				specs.Add(new Spec(name, formula, new List<SpecPair>
				{
					new SpecPair("type", "skill")
				}, menu));
			}

			public void AddSkill(string name, string formula, string opposed, string menu = null)
			{
				specs.Add(new Spec(name, formula, new List<SpecPair>
				{
					new SpecPair("type", "skill"),
					new SpecPair("opposed", opposed)
				}, menu));
			}

			public void AddAttack(string name, string formula, string opposed, string menu = null)
			{
				specs.Add(new Spec(name, formula, new List<SpecPair>
				{
					new SpecPair("type", "attack"),
					new SpecPair("opposed", opposed)
				}, menu));
			}

			public void AddDamage(string name, string formula, string damageType, string menu = null)
			{
				specs.Add(new Spec(name, formula, new List<SpecPair>
				{
					new SpecPair("type", "damage"),
					new SpecPair("damageType", damageType)
				}, menu));
			}

			public void AddHealing(string name, string formula, string menu = null)
			{
				specs.Add(new Spec(name, formula, new List<SpecPair>
				{
					new SpecPair("type", "heal")
				}, menu));
			}

			public void AddResistances(string name, string list, string damageType, string menu = null)
			{
				List<SpecPair> list2 = new List<SpecPair>();
				string[] array = list.Split(new char[1] { ',' });
				foreach (string text in array)
				{
					list2.Add(new SpecPair(text, text));
				}
				specs.Add(new Spec("Resistances", list, list2, menu));
			}

			public void AddImmunities(string name, string list, string damageType, string menu = null)
			{
				List<SpecPair> list2 = new List<SpecPair>();
				string[] array = list.Split(new char[1] { ',' });
				foreach (string text in array)
				{
					list2.Add(new SpecPair(text, text));
				}
				specs.Add(new Spec("Immunities", list, list2, menu));
			}

			public void AddVulnerabilities(string name, string list, string damageType, string menu = null)
			{
				List<SpecPair> list2 = new List<SpecPair>();
				string[] array = list.Split(new char[1] { ',' });
				foreach (string text in array)
				{
					list2.Add(new SpecPair(text, text));
				}
				specs.Add(new Spec("Resistances", list, list2, menu));
			}

			public void AddOrModifyValue(string name, string value, string menu = null)
			{
				Spec spec = FindFirst(name);
				if (spec == null)
				{
					specs.Add(new Spec(name, value, new List<SpecPair>
					{
						new SpecPair("type", "value")
					}, menu));
				}
				else
				{
					spec.formula = value;
				}
			}

			public string Resolve(string formula, int replacements = 0)
			{
				LoggingPlugin.LogTrace("Processing Resolve: Formula=" + (formula ?? "Empty Formula") + ", Max Replacements=" + replacements);
				if (formula == null || formula.Trim() == "")
				{
					return "";
				}
				int num = 0;
				string text = "";
				for (int i = 0; i < nestedResolve; i++)
				{
					foreach (Spec spec in specs)
					{
						foreach (SpecPair item in spec.extra)
						{
							LoggingPlugin.LogTrace("Processing Resolve: Replacing [" + spec.name + "." + item.key + "] With " + item.value);
							text = formula;
							formula = formula.Replace("[" + spec.name + "." + item.key + "]", item.value);
							if (text != formula)
							{
								num++;
							}
							if (replacements > 0 && num >= replacements)
							{
								LoggingPlugin.LogTrace("Processing Resolve: Max Replacement " + replacements + " Resolve: " + formula);
								return formula;
							}
							LoggingPlugin.LogTrace("Processing Resolve: Formula=" + formula + ", Replacements Count=" + num);
						}
						LoggingPlugin.LogTrace("Processing Resolve: Replacing [" + spec.name + "] With " + spec.formula.ToString());
						text = formula;
						formula = formula.Replace("[" + spec.name + "]", spec.formula.ToString());
						formula = formula.Replace("+-", "-").Replace("-+", "-").Replace("--", "+")
							.Replace("++", "+");
						if (text != formula)
						{
							num++;
						}
						if (replacements > 0 && num >= replacements)
						{
							LoggingPlugin.LogTrace("Processing Resolve: Max Replacement " + replacements + " Resolve: " + formula);
							return formula;
						}
						LoggingPlugin.LogTrace("Processing Resolve: Formula=" + formula + ", Replacements Count=" + num);
					}
				}
				LoggingPlugin.LogTrace("Processing Resolve: Full Resolve: " + formula);
				return formula;
			}

			public Spec[] Find(string whereClause)
			{
				if (specs == null || specs.Count == 0 || string.IsNullOrWhiteSpace(whereClause))
				{
					return null;
				}
				if (whereClause.IndexOf("=") < 0 && whereClause.IndexOf("<") < 0 && whereClause.IndexOf(">") < 0)
				{
					whereClause = "name==\"" + whereClause + "\"";
				}
				LoggingPlugin.LogTrace("Find: " + whereClause);
				return DynamicQueryableExtensions.Where<Spec>(specs.AsQueryable(), whereClause, Array.Empty<object>()).ToArray();
			}

			public Spec FindFirst(string whereClause)
			{
				Spec[] array = Find(whereClause);
				LoggingPlugin.LogTrace("FindFirst: " + ((array != null) ? array.Length.ToString() : "0") + " Matches");
				return (array != null && array.Count() > 0) ? array[0] : null;
			}

			public string FindFirstValue(string whereClause)
			{
				Spec spec = FindFirst(whereClause);
				LoggingPlugin.LogTrace("FindFirstValue: " + ((spec != null) ? (spec.name + "=" + spec.formula) : "Null"));
				return (spec != null) ? spec.formula : "";
			}

			public string FindFirstExtraValue(string whereClause, string property)
			{
				Spec spec = FindFirst(whereClause);
				return (spec != null) ? spec.extra.Where((SpecPair p) => p.key == property).FirstOrDefault().value : "";
			}

			public CreatureBoardAsset FindAsset()
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return ((IEnumerable<CreatureBoardAsset>)(object)CreaturePresenter.GetTempReadOnlyViewOfAllCreatureAssets()).Where((CreatureBoardAsset a) => a.Name.Contains(name)).FirstOrDefault();
			}

			public CreatureBoardAsset[] FindAssets()
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return ((IEnumerable<CreatureBoardAsset>)(object)CreaturePresenter.GetTempReadOnlyViewOfAllCreatureAssets()).Where((CreatureBoardAsset a) => a.Name.Contains(name)).ToArray();
			}
		}

		public class CharactersSpecs
		{
			public enum CheckType
			{
				Regular = 1,
				Opposed,
				Attack,
				Damage,
				Effect,
				Heal,
				Generic
			}

			private List<CharacterSpecs> sheets = new List<CharacterSpecs>();

			private List<string> builtPaths = new List<string>();

			public static Sprite fallbackSprite = Image.LoadSprite("org.lordashes.plugins.d20.character.png", (CacheType)999);

			public List<CharacterSpecs> All()
			{
				return sheets;
			}

			public void Add(CharacterSpecs specs)
			{
				sheets.Add(specs);
			}

			public void Remove(string name)
			{
				for (int i = 0; i < sheets.Count; i++)
				{
					if (sheets[i].name == name)
					{
						sheets.RemoveAt(i);
						i--;
					}
				}
			}

			public void LoadCharacters(bool reload = false)
			{
				//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
				//IL_011c: Expected O, but got Unknown
				sheets.Clear();
				builtPaths.Clear();
				string[] array = File.Find("org.lordashes.plugins.d20.character.", (CacheType)999);
				foreach (string text in array)
				{
					if (text.ToLower().EndsWith(".json"))
					{
						LoadCharacter(text);
					}
				}
				LoggingPlugin.LogInfo("Loaded " + _self.characters.sheets.Count + " Character Sheets");
				if (!reload)
				{
					RadialUIPlugin.AddCustomButtonOnCharacter("org.lordashes.plugins.d20", new ItemArgs
					{
						Action = delegate
						{
							//IL_000e: Unknown result type (might be due to invalid IL or missing references)
							LoggingPlugin.LogTrace("Selected Character Menu. Triggering Deep Menu...");
							CreatureBoardAsset val = null;
							CreaturePresenter.TryGetAsset(LocalClient.SelectedCreatureId, ref val);
							DeepMenusPlugin.NavigateTo(DiceRoller.StripTrailingInteger(val.Name));
						},
						CloseMenuOnActivate = true,
						FadeName = true,
						Icon = LoadSpriteOrDefault("org.lordashes.plugins.d20.character.png", fallbackSprite),
						Title = "Actions"
					}, (Func<NGuid, NGuid, bool>)delegate
					{
						//IL_000e: Unknown result type (might be due to invalid IL or missing references)
						CreatureBoardAsset instigator = null;
						CreaturePresenter.TryGetAsset(LocalClient.SelectedCreatureId, ref instigator);
						if ((Object)(object)instigator != (Object)null)
						{
							LoggingPlugin.LogDebug("Looking for Sheet For '" + DiceRoller.StripTrailingInteger(instigator.Name) + "'");
							return _self.characters.sheets.Any((CharacterSpecs c) => c.name == DiceRoller.StripTrailingInteger(instigator.Name));
						}
						return false;
					});
				}
				foreach (CharacterSpecs character in sheets)
				{
					DeepMenusPlugin._self.CreateSubMenuItem("/" + character.name, DeepMenusPlugin._self.MakeItemEntry("Edit", (Action<string, string>)delegate
					{
						LoadUserSettings(_self.characters.FindFirst(character.name));
						menuEditOpen = true;
						GameInputEnabled(!menuEditOpen);
					}, LoadSpriteOrDefault("org.lordashes.plugins.d20.exit.png", fallbackSprite), false, true), (Func<bool>)(() => true));
					foreach (Spec spec in character.specs)
					{
						LoggingPlugin.LogTrace("Considering Entry " + spec.name + " (" + spec.menu + ")");
						if (spec.menu != null && spec.menu.Trim() != "")
						{
							BuildMenu(character.name, spec.menu);
						}
					}
				}
			}

			private static void LoadCharacter(string characterSheet)
			{
				string text = File.ReadAllText(characterSheet, (CacheType)999);
				text = text.TrimStart('\ufeff', '\u200b');
				LoggingPlugin.LogInfo("Loading Character Sheet From " + characterSheet);
				try
				{
					CharacterSpecs characterSpecs = JsonConvert.DeserializeObject<CharacterSpecs>(text);
					string characterName = characterSpecs.name;
					if (!_self.characters.All().Any((CharacterSpecs cs) => cs.name == characterName))
					{
						_self.characters.Add(characterSpecs);
						if (characterSpecs.chainSources == null)
						{
							return;
						}
						LoggingPlugin.LogDebug("Chain Loading Set To " + characterSpecs.chainSources);
						string[] array = characterSpecs.chainSources.Split(new char[1] { ',' });
						string[] array2 = array;
						foreach (string text2 in array2)
						{
							LoggingPlugin.LogDebug("Chain Loading org.lordashes.plugins.d20.character." + text2);
							LoggingPlugin.LogDebug(JsonConvert.SerializeObject((object)_self.characters));
							CharacterSpecs characterSpecs2 = _self.characters.FindFirst(DiceRoller.StripTrailingInteger(characterName));
							text = File.ReadAllText("org.lordashes.plugins.d20.common." + text2, (CacheType)999);
							text = text.TrimStart('\ufeff', '\u200b');
							characterSpecs = JsonConvert.DeserializeObject<CharacterSpecs>(text);
							foreach (Spec spec in characterSpecs.specs)
							{
								characterSpecs2.specs.Add(spec);
							}
						}
					}
					else
					{
						LoggingPlugin.LogWarning("Duplicated Character Sheet For '" + characterName + "'");
						SystemMessage.DisplayInfoText("D20 Plugin:\r\nDuplicate Character " + characterName, 2.5f, 0f, (Action)null);
					}
				}
				catch (Exception ex)
				{
					string fileName = Path.GetFileName(characterSheet);
					if (ex.Message.IndexOf("line") > -1)
					{
						string text3 = ex.Message.Substring(ex.Message.IndexOf("line") + 4).Trim();
						text3 = text3.Substring(0, text3.IndexOf(",")).Trim();
						LoggingPlugin.LogError("Error On Line " + text3.Substring(1) + " Of " + fileName + " (" + ex.Message + ")");
						try
						{
							int num = int.Parse(text3);
							string[] array3 = text.Split(new string[1] { "\r\n" }, StringSplitOptions.None);
							LoggingPlugin.LogError("Problem Line: " + array3[num].Trim());
						}
						catch (Exception ex2)
						{
							LoggingPlugin.LogError("'" + text3 + "'");
							LoggingPlugin.LogError(ex2.Message);
						}
					}
					else
					{
						LoggingPlugin.LogError(ex.Message);
					}
					string[] source = text.Split(new string[1] { "\r\n" }, StringSplitOptions.None);
					string text4 = string.Join("\r\n", source.Select((string line, int index) => $"Line {index + 1:0000}: {line}"));
					LoggingPlugin.LogInfo("Fault JSON:\r\n" + text4);
				}
			}

			public CharacterSpecs[] Find(string name)
			{
				if (name == "")
				{
					return null;
				}
				return DynamicQueryableExtensions.Where<CharacterSpecs>(sheets.AsQueryable(), "name==\"" + name + "\"", Array.Empty<object>()).ToArray();
			}

			public CharacterSpecs FindFirst(string name)
			{
				if (name == "")
				{
					return null;
				}
				return DynamicQueryableExtensions.Where<CharacterSpecs>(sheets.AsQueryable(), "name==\"" + name + "\"", Array.Empty<object>()).FirstOrDefault();
			}

			public string FindValue(string name, string whereClause)
			{
				return FindFirst(name)?.FindFirstValue(whereClause);
			}

			public static Sprite LoadSpriteOrDefault(string seekSprite, Sprite fallBackSprite)
			{
				if (File.Find(seekSprite, (CacheType)999).Any())
				{
					return Image.LoadSprite(seekSprite, (CacheType)999);
				}
				return fallBackSprite;
			}

			private void BuildMenu(string characterName, string menu)
			{
				menu = "/" + characterName + menu;
				string text = menu.Substring(menu.LastIndexOf("/") + 1);
				string text2 = menu.Substring(0, menu.LastIndexOf("/"));
				string[] array = text2.Substring(1).Split(new char[1] { '/' });
				string text3 = "";
				for (int j = 0; j < array.Length; j++)
				{
					if (!builtPaths.Contains(text3 + ":" + array[j]))
					{
						LoggingPlugin.LogDebug("Building Path " + text3 + "/" + array[j]);
						DeepMenusPlugin._self.CreateSubMenu(text3, DeepMenusPlugin._self.MakeSubMenuEntry(array[j], (text3 != "") ? LoadSpriteOrDefault("org.lordashes.plugins.d20." + array[j] + ".png", fallbackSprite) : null, false, true), (Func<bool>)(() => true));
						builtPaths.Add(text3 + ":" + array[j]);
					}
					text3 = text3 + "/" + array[j];
				}
				LoggingPlugin.LogDebug("Building Leaf " + text3 + "/" + text);
				DeepMenusPlugin._self.CreateSubMenuItem(text3, DeepMenusPlugin._self.MakeItemEntry(text, (Action<string, string>)delegate(string i, string m)
				{
					((MonoBehaviour)_self).StartCoroutine(InitiateMenuAction(i, m));
				}, LoadSpriteOrDefault("org.lordashes.plugins.d20." + text + ".png", fallbackSprite), false, true), (Func<bool>)(() => true));
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass7_0
		{
			public string menu;

			public string item;

			public Func<Spec, bool> <>9__3;

			public Func<Spec, bool> <>9__4;

			public Func<Spec, bool> <>9__5;

			public Func<Spec, bool> <>9__6;

			public Func<Spec, bool> <>9__7;

			internal bool <InitiateMenuAction>b__3(Spec s)
			{
				return s.menu == menu + "/" + item;
			}

			internal bool <InitiateMenuAction>b__4(Spec s)
			{
				return s.menu == menu + "/" + item;
			}

			internal bool <InitiateMenuAction>b__5(Spec s)
			{
				return s.menu == menu + "/" + item;
			}

			internal bool <InitiateMenuAction>b__6(Spec s)
			{
				return s.menu == menu + "/" + item;
			}

			internal bool <InitiateMenuAction>b__7(Spec s)
			{
				return s.menu == menu + "/" + item;
			}
		}

		[CompilerGenerated]
		private sealed class <InitiateMenuAction>d__7 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public string item;

			public string menu;

			public CreatureBoardAsset[] instigators;

			public CreatureBoardAsset[] targets;

			private <>c__DisplayClass7_0 <>8__1;

			private CreatureGuid[] <selectedAssetsIds>5__2;

			private CreatureBoardAsset[] <>s__3;

			private int <>s__4;

			private CreatureBoardAsset <instigator>5__5;

			private CharacterSpecs <stack>5__6;

			private CharacterSpecs <sheet>5__7;

			private Spec <spec>5__8;

			private string <action>5__9;

			private string <publicityStr>5__10;

			private Scripts.MessagePublicity <publicity>5__11;

			private string <>s__12;

			private string <opposed>5__13;

			private int <expectedTargets>5__14;

			private string <>s__15;

			private CreatureBoardAsset <targetAsset>5__16;

			private string <t>5__17;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <InitiateMenuAction>d__7(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>8__1 = null;
				<selectedAssetsIds>5__2 = null;
				<>s__3 = null;
				<instigator>5__5 = null;
				<stack>5__6 = null;
				<sheet>5__7 = null;
				<spec>5__8 = null;
				<action>5__9 = null;
				<publicityStr>5__10 = null;
				<>s__12 = null;
				<opposed>5__13 = null;
				<>s__15 = null;
				<targetAsset>5__16 = null;
				<t>5__17 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f5: Expected O, but got Unknown
				//IL_014f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0154: Unknown result type (might be due to invalid IL or missing references)
				//IL_0707: Unknown result type (might be due to invalid IL or missing references)
				//IL_070c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0711: Unknown result type (might be due to invalid IL or missing references)
				//IL_0785: Unknown result type (might be due to invalid IL or missing references)
				//IL_078a: Unknown result type (might be due to invalid IL or missing references)
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>8__1 = new <>c__DisplayClass7_0();
					<>8__1.menu = menu;
					<>8__1.item = item;
					LoggingPlugin.LogDebug("Action Selected: " + <>8__1.item + " (" + <>8__1.menu + ")");
					((MonoBehaviour)_self).StartCoroutine(PatchCallCameraClick.preventClickCollection(1f));
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					<selectedAssetsIds>5__2 = null;
					LocalClient.TryGetLassoedCreatureIds(ref <selectedAssetsIds>5__2);
					if (<selectedAssetsIds>5__2 == null)
					{
						instigators = GetCreatureAssets(<selectedAssetsIds>5__2);
					}
					if (<selectedAssetsIds>5__2 == null)
					{
						instigators = GetCreatureAssets((CreatureGuid[])(object)new CreatureGuid[1] { LocalClient.SelectedCreatureId });
					}
					if (targets == null)
					{
						targets = GetAffectedCreatures();
					}
					LoggingPlugin.LogDebug("Instagators (" + instigators.Length + ") = " + string.Join(",", instigators.Select((CreatureBoardAsset a) => a.Name)));
					LoggingPlugin.LogDebug("Targets (" + targets.Length + ") = " + string.Join(",", targets.Select((CreatureBoardAsset a) => a.Name)));
					<>8__1.menu = <>8__1.menu.Substring(1);
					<>8__1.menu = <>8__1.menu.Substring(<>8__1.menu.IndexOf("/"));
					<>s__3 = instigators;
					<>s__4 = 0;
					goto IL_0e5f;
				case 2:
					<>1__state = -1;
					<targetAsset>5__16 = null;
					goto IL_0e16;
				case 3:
					<>1__state = -1;
					goto IL_0e16;
				case 4:
					<>1__state = -1;
					goto IL_0e16;
				case 5:
					<>1__state = -1;
					goto IL_0e16;
				case 6:
					<>1__state = -1;
					goto IL_0e16;
				case 7:
					{
						<>1__state = -1;
						goto IL_0e16;
					}
					IL_0e2c:
					<stack>5__6 = null;
					<sheet>5__7 = null;
					<spec>5__8 = null;
					<action>5__9 = null;
					goto IL_0e49;
					IL_0e16:
					<opposed>5__13 = null;
					<>s__15 = null;
					<publicityStr>5__10 = null;
					goto IL_0e2c;
					IL_0e49:
					<instigator>5__5 = null;
					<>s__4++;
					goto IL_0e5f;
					IL_0e5f:
					if (<>s__4 < <>s__3.Length)
					{
						<instigator>5__5 = <>s__3[<>s__4];
						LoggingPlugin.LogDebug("Current Pass Instinagtor: " + <instigator>5__5.Name);
						LoggingPlugin.LogDebug("Current Targets (" + targets.Length + ") = " + string.Join(",", targets.Select((CreatureBoardAsset a) => a.Name)));
						if ((Object)(object)<instigator>5__5 != (Object)null)
						{
							<stack>5__6 = new CharacterSpecs();
							<sheet>5__7 = _self.characters.FindFirst(DiceRoller.StripTrailingInteger(<instigator>5__5.Name));
							<spec>5__8 = null;
							<action>5__9 = <sheet>5__7.FindFirstExtraValue("menu==\"" + <>8__1.menu + "/" + <>8__1.item + "\"", "type");
							LoggingPlugin.LogDebug("Action: " + ((<action>5__9 != null) ? <action>5__9 : "Null"));
							if (<action>5__9 == null || <action>5__9.Trim() == "")
							{
								<action>5__9 = "skill";
							}
							<spec>5__8 = <sheet>5__7.specs.Where((Spec s) => s.menu == <>8__1.menu + "/" + <>8__1.item).FirstOrDefault();
							if (<spec>5__8 != null)
							{
								LoggingPlugin.LogTrace("Getting Publicity");
								<publicityStr>5__10 = <spec>5__8.Extra("message");
								<publicity>5__11 = Scripts.MessagePublicity.publicMessage;
								string text = <publicityStr>5__10;
								<>s__12 = text;
								string text2 = <>s__12;
								if (!(text2 == "private"))
								{
									if (text2 == "semiprivate")
									{
										<publicity>5__11 = Scripts.MessagePublicity.semiPrivateMessage;
									}
									else
									{
										<publicity>5__11 = Scripts.MessagePublicity.publicMessage;
									}
								}
								else
								{
									<publicity>5__11 = Scripts.MessagePublicity.privateMessage;
								}
								<>s__12 = null;
								string text3 = <action>5__9;
								<>s__15 = text3;
								switch (<>s__15)
								{
								case "info":
								case "skill":
								case "attack":
								case "save":
								case "spell":
									break;
								case "effect":
									<spec>5__8 = <sheet>5__7.specs.Where((Spec s) => s.menu == <>8__1.menu + "/" + <>8__1.item).FirstOrDefault();
									LoggingPlugin.LogDebug("Found Spec: " + (<spec>5__8 != null));
									LoggingPlugin.LogDebug("Processing " + <instigator>5__5.Name + "'s " + <>8__1.item + " (" + <action>5__9 + ") As Damage");
									<>2__current = Scripts.ProcessEffectOnTarget(<stack>5__6, CharactersSpecs.CheckType.Effect, <spec>5__8, <instigator>5__5, (targets.Length != 0) ? targets[0] : <instigator>5__5, "Hit", <publicity>5__11, <spec>5__8.name);
									<>1__state = 4;
									return true;
								case "damage":
									<spec>5__8 = <sheet>5__7.specs.Where((Spec s) => s.menu == <>8__1.menu + "/" + <>8__1.item).FirstOrDefault();
									LoggingPlugin.LogDebug("Found Spec: " + (<spec>5__8 != null));
									LoggingPlugin.LogDebug("Processing " + <instigator>5__5.Name + "'s " + <>8__1.item + " (" + <action>5__9 + ") As Damage");
									<>2__current = Scripts.ProcessDamageOnTarget(<stack>5__6, CharactersSpecs.CheckType.Damage, <spec>5__8, <instigator>5__5, (targets.Length != 0) ? targets[0] : <instigator>5__5, "Hit", <publicity>5__11, <spec>5__8.name);
									<>1__state = 5;
									return true;
								case "heal":
									<spec>5__8 = <sheet>5__7.specs.Where((Spec s) => s.menu == <>8__1.menu + "/" + <>8__1.item).FirstOrDefault();
									LoggingPlugin.LogDebug("Found Spec: " + (<spec>5__8 != null));
									LoggingPlugin.LogDebug("Processing " + <instigator>5__5.Name + "'s " + <>8__1.item + " (" + <action>5__9 + ") As Heal");
									<>2__current = Scripts.ProcessHealOnTarget(<stack>5__6, CharactersSpecs.CheckType.Heal, <spec>5__8, <instigator>5__5, (targets.Length != 0) ? targets[0] : <instigator>5__5, <publicity>5__11);
									<>1__state = 6;
									return true;
								default:
									<spec>5__8 = <sheet>5__7.specs.Where((Spec s) => s.menu == <>8__1.menu + "/" + <>8__1.item).FirstOrDefault();
									LoggingPlugin.LogDebug("Found Spec: " + (<spec>5__8 != null));
									LoggingPlugin.LogDebug("Processing " + <instigator>5__5.Name + "'s " + <>8__1.item + " (" + <action>5__9 + ") As Generic");
									<>2__current = Scripts.ProcessGeneric(<stack>5__6, CharactersSpecs.CheckType.Generic, <spec>5__8, <instigator>5__5, (targets.Length != 0) ? targets[0] : <instigator>5__5, <publicity>5__11);
									<>1__state = 7;
									return true;
								}
								LoggingPlugin.LogDebug("Found Spec: " + (<spec>5__8 != null));
								<opposed>5__13 = <spec>5__8.Extra("opposed");
								LoggingPlugin.LogDebug("Found Opposed: " + (<opposed>5__13 != null));
								<expectedTargets>5__14 = ((<spec>5__8.Extra("targets") != null) ? int.Parse(<spec>5__8.Extra("targets")) : 0);
								LoggingPlugin.LogDebug("Expected Targets: " + <expectedTargets>5__14);
								if (<opposed>5__13 != null && <opposed>5__13 != "" && new CreatureGuid(RadialUIPlugin.GetLastRadialTargetCreature()) != LocalClient.SelectedCreatureId)
								{
									LoggingPlugin.LogDebug("Processing " + <instigator>5__5.Name + "'s " + <>8__1.item + " (" + <action>5__9 + ") As Opposed Skill With Selected Target.");
									<targetAsset>5__16 = null;
									CreaturePresenter.TryGetAsset(new CreatureGuid(RadialUIPlugin.GetLastRadialTargetCreature()), ref <targetAsset>5__16);
									<>2__current = Scripts.ProcessSequence(<stack>5__6, (<action>5__9 == "attack" || <action>5__9 == "spell") ? CharactersSpecs.CheckType.Attack : CharactersSpecs.CheckType.Opposed, <spec>5__8, <instigator>5__5, (CreatureBoardAsset[])(object)new CreatureBoardAsset[1] { <targetAsset>5__16 }, <publicity>5__11);
									<>1__state = 2;
									return true;
								}
								if (<opposed>5__13 != null && <opposed>5__13 != "")
								{
									LoggingPlugin.LogDebug("Processing " + <instigator>5__5.Name + "'s " + <>8__1.item + " (" + <action>5__9 + ") As Opposed Skill. Collecting Targets.");
									TargetsCollection obj = new TargetsCollection
									{
										targetsCollectingSpecType = <action>5__9,
										targetsCollectingSpec = <spec>5__8,
										targetsCollectingInstigator = <instigator>5__5,
										targetsCollectingPublicity = <publicity>5__11
									};
									<t>5__17 = <spec>5__8.Extra("targets");
									obj.targetsCollecting = int.Parse((<t>5__17 != null) ? <t>5__17 : int.MaxValue.ToString());
									targetsCollection = obj;
									<t>5__17 = null;
									goto IL_0e16;
								}
								LoggingPlugin.LogDebug("Processing " + <instigator>5__5.Name + "'s " + <>8__1.item + " (" + <action>5__9 + ") As Skill");
								<>2__current = Scripts.ProcessSequence(<stack>5__6, CharactersSpecs.CheckType.Regular, <spec>5__8, <instigator>5__5, null, <publicity>5__11);
								<>1__state = 3;
								return true;
							}
							goto IL_0e2c;
						}
						goto IL_0e49;
					}
					<>s__3 = null;
					LoggingPlugin.LogDebug("Action Processing Completed");
					return false;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		public static CreatureBoardAsset[] GetCreatureAssets(CreatureGuid[] cids)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			List<CreatureBoardAsset> list = new List<CreatureBoardAsset>();
			if (cids != null)
			{
				foreach (CreatureGuid val in cids)
				{
					CreatureBoardAsset val2 = null;
					CreaturePresenter.TryGetAsset(val, ref val2);
					if ((Object)(object)val2 != (Object)null)
					{
						list.Add(val2);
					}
				}
			}
			return list.ToArray();
		}

		public static string[] GetCreatureNames(CreatureGuid[] cids)
		{
			return (from a in GetCreatureAssets(cids)
				select a.Name).ToArray();
		}

		private static CreatureBoardAsset[] GetAffectedCreatures()
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			List<CreatureBoardAsset> list = new List<CreatureBoardAsset>();
			FieldInfo fieldInfo = (from i in typeof(CreatureBoardAsset).GetRuntimeFields()
				where i.Name == "_selected"
				select i).FirstOrDefault();
			if (fieldInfo != null)
			{
				foreach (CreatureBoardAsset item2 in (IEnumerable<CreatureBoardAsset>)CreaturePresenter.GetTempReadOnlyViewOfAllCreatureAssets())
				{
					if ((Object)(object)item2 != (Object)null && (bool)fieldInfo.GetValue(item2))
					{
						list.Add(item2);
					}
				}
			}
			if (!list.Any((CreatureBoardAsset c) => c.CreatureId == new CreatureGuid(RadialUIPlugin.GetLastRadialTargetCreature())))
			{
				CreatureBoardAsset val = null;
				CreaturePresenter.TryGetAsset(new CreatureGuid(RadialUIPlugin.GetLastRadialTargetCreature()), ref val);
				if ((Object)(object)val != (Object)null)
				{
					list.Add(val);
				}
			}
			CreatureBoardAsset item = default(CreatureBoardAsset);
			CreaturePresenter.TryGetAsset(LocalClient.SelectedCreatureId, ref item);
			if (list.Contains(item))
			{
				list.Remove(item);
			}
			return list.ToArray();
		}

		[IteratorStateMachine(typeof(<InitiateMenuAction>d__7))]
		public static IEnumerator InitiateMenuAction(string item, string menu, CreatureBoardAsset[] instigators = null, CreatureBoardAsset[] targets = null)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <InitiateMenuAction>d__7(0)
			{
				item = item,
				menu = menu,
				instigators = instigators,
				targets = targets
			};
		}
	}

	public static class DiceRoller
	{
		public class RollResult
		{
			public string name { get; set; }

			public string formula { get; set; }

			public string formulaResolved { get; set; }

			public string formulaDice { get; set; }

			public int total { get; set; }

			public int[] dice { get; set; }
		}

		public enum RollingMethod
		{
			randomGeneratorDice = 1,
			talespireDice
		}

		public static class RollSimplifier
		{
			public class RollParseResult
			{
				public string RollString { get; set; }

				public List<short> AllDiceValues { get; set; }

				public List<int> Totals { get; set; }
			}

			public static RollParseResult ParseRollResults(RollResults rollResults)
			{
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				List<short> allDiceValues = new List<short>();
				List<string> list = new List<string>();
				List<int> list2 = new List<int>();
				RollGroup[] array = rollResults.ResultsGroups.ToArray();
				foreach (RollGroup val in array)
				{
					var (item, item2) = ProcessOperand(val.Result, allDiceValues);
					list.Add(item);
					list2.Add(item2);
				}
				return new RollParseResult
				{
					RollString = string.Join(" / ", list),
					AllDiceValues = allDiceValues,
					Totals = list2
				};
			}

			private static (string str, int total) ProcessOperand(RollOperand operand, List<short> allDiceValues)
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Invalid comparison between Unknown and I8
				//IL_003a: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
				//IL_0101: Unknown result type (might be due to invalid IL or missing references)
				//IL_015e: Unknown result type (might be due to invalid IL or missing references)
				//IL_016d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0065: Unknown result type (might be due to invalid IL or missing references)
				//IL_0075: Unknown result type (might be due to invalid IL or missing references)
				//IL_0082: Unknown result type (might be due to invalid IL or missing references)
				//IL_0083: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
				RollOperation val = default(RollOperation);
				RollResult val2 = default(RollResult);
				RollValue val3 = default(RollValue);
				Which val4 = ((RollOperand)(ref operand)).Get(ref val, ref val2, ref val3);
				Which val5 = val4;
				Which val6 = val5;
				if ((long)val6 <= 2L)
				{
					switch ((uint)val6)
					{
					case 0u:
					{
						RollOperand[] array2 = val.Operands.ToArray();
						if (array2.Length != 2)
						{
							throw new InvalidOperationException("Unexpected number of operands in RollOperation (expected 2).");
						}
						(string, int) tuple = ProcessOperand(array2[0], allDiceValues);
						(string, int) tuple2 = ProcessOperand(array2[1], allDiceValues);
						int item2 = (((int)val.Operator == 0) ? (tuple.Item2 + tuple2.Item2) : (tuple.Item2 - tuple2.Item2));
						string text = (((int)val.Operator == 0) ? "+" : "-");
						return (tuple.Item1 + text + tuple2.Item1, item2);
					}
					case 1u:
					{
						int num = ((IEnumerable<short>)val2.Results).Count();
						string registeredName = ((DieKind)(ref val2.Kind)).RegisteredName;
						short[] array = val2.Results.ToArray();
						allDiceValues.AddRange(array);
						int item = array.Sum((short r) => r);
						return ($"{num}{registeredName}", item);
					}
					case 2u:
					{
						short value = val3.Value;
						return (value.ToString(), val3.Value);
					}
					}
				}
				throw new InvalidOperationException("Unknown RollOperand type encountered.");
			}
		}

		private static readonly Random _rng = new Random();

		private static readonly Regex TokenRegex = new Regex("(\\d+[dD]\\d+[aAdD]?|\\d+|[+\\-*/])", RegexOptions.Compiled);

		private static readonly Regex DiceRegex = new Regex("(\\d+)[dD](\\d+)([aAdD]?)", RegexOptions.Compiled);

		private static readonly string TermPattern = "(?:\\d+[dD]\\d+[aAdD]?|\\d+|[A-Za-z_][A-Za-z0-9_]*)";

		public static TaskCompletionSource<RollResult> pendingRoll;

		public static async Task<RollResult> Roll(Characters.CharacterSpecs instigatorSheet, string rollName, string expression, RollingMethod? rollingStyle = null)
		{
			RollingMethod useRollingStyle = (rollingStyle.HasValue ? rollingStyle.Value : rollingStyleOffensive);
			RollResult rollResult = new RollResult
			{
				name = rollName,
				formula = expression,
				formulaResolved = SimplifyExpression(ComputeConstants(instigatorSheet.Resolve(expression)))
			};
			RollResult rawRollResult;
			switch (useRollingStyle)
			{
			case RollingMethod.randomGeneratorDice:
				rawRollResult = RollRandomGeneratorDice(instigatorSheet, rollResult.formulaResolved);
				break;
			case RollingMethod.talespireDice:
			{
				string justDice = ExtractTalespireDiceRolls(rollResult.formulaResolved);
				rawRollResult = ((!(justDice.Trim() != "")) ? new RollResult
				{
					dice = new int[0]
				} : (await RollTalespireDice(instigatorSheet, rollName, justDice.Trim())));
				break;
			}
			default:
				return null;
			}
			rollResult.formulaDice = ResolveDiceValues(rollResult.formulaResolved, rawRollResult.dice);
			rollResult.total = ResolveTotal(rollResult.formulaResolved, rawRollResult.dice);
			rollResult.dice = rawRollResult.dice;
			LoggingPlugin.LogDebug("Dice Roller: Name: " + rollResult.name);
			LoggingPlugin.LogDebug("Dice Roller: Formula: " + rollResult.formula);
			LoggingPlugin.LogDebug("Dice Roller: Roll: " + rollResult.formulaResolved);
			LoggingPlugin.LogDebug("Dice Roller: Dice: " + rollResult.formulaDice);
			LoggingPlugin.LogDebug("Dice Roller: Total: " + rollResult.total);
			return rollResult;
		}

		public static Task<RollResult> RollTalespireDice(Characters.CharacterSpecs instigatorSheet, string rollName, string expression)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			LoggingPlugin.LogDebug("Using Talespire Dice");
			if (pendingRoll != null)
			{
				throw new InvalidOperationException("A virtual dice roll is already in progress.");
			}
			LoggingPlugin.LogDebug("Setting Dice Expecting Flag");
			pendingRoll = new TaskCompletionSource<RollResult>();
			string text = "talespire://dice/" + rollName + ":" + expression;
			LoggingPlugin.LogDebug("Requesting: " + text);
			LocalConnectionManager.ProcessTaleSpireUrl(text);
			return pendingRoll.Task;
		}

		public static RollResult RollRandomGeneratorDice(Characters.CharacterSpecs instigatorSheet, string expression)
		{
			LoggingPlugin.LogDebug("Using Random Generator Dice");
			if (string.IsNullOrWhiteSpace(expression))
			{
				throw new ArgumentException("Expression cannot be empty.");
			}
			List<int> diceRolls = new List<int>();
			string expression2 = DiceRegex.Replace(expression, delegate(Match match)
			{
				int count = int.Parse(match.Groups[1].Value);
				int sides = int.Parse(match.Groups[2].Value);
				char c = ((match.Groups[3].Value.Length > 0) ? char.ToUpperInvariant(match.Groups[3].Value[0]) : '\0');
				if (c == '\0')
				{
					return RollOnce().ToString();
				}
				int val = RollOnce();
				int val2 = RollOnce();
				return ((c == 'A') ? Math.Max(val, val2) : Math.Min(val, val2)).ToString();
			});
			int total = EvaluateIntegerExpression(expression2);
			return new RollResult
			{
				formula = expression,
				formulaResolved = SimplifyExpression(ComputeConstants(instigatorSheet.Resolve(expression))),
				formulaDice = SimplifyExpression(ResolveDiceValues(ComputeConstants(instigatorSheet.Resolve(expression)), diceRolls.ToArray())),
				total = total,
				dice = diceRolls.ToArray()
			};
			int RollOnce()
			{
				int num = 0;
				for (int i = 0; i < P_0.count; i++)
				{
					int num2 = _rng.Next(1, P_0.sides + 1);
					diceRolls.Add(num2);
					num += num2;
				}
				return num;
			}
		}

		public static string ResolveDiceValues(string formula, int[] dice)
		{
			if (string.IsNullOrWhiteSpace(formula))
			{
				throw new ArgumentException("Expression cannot be empty.");
			}
			if (dice == null)
			{
				throw new ArgumentNullException("dice");
			}
			int num = 0;
			StringBuilder stringBuilder = new StringBuilder();
			int num2 = 0;
			foreach (Match item in DiceRegex.Matches(formula))
			{
				stringBuilder.Append(formula.Substring(num2, item.Index - num2));
				int num3 = int.Parse(item.Groups[1].Value);
				char c = ((item.Groups[3].Value.Length > 0) ? char.ToUpperInvariant(item.Groups[3].Value[0]) : '\0');
				int num4 = ((c != 'A' && c != 'D') ? 1 : 2);
				int num5 = num3 * num4;
				if (num + num5 > dice.Length)
				{
					throw new ArgumentException("Not enough dice values provided.");
				}
				if (num4 > 1)
				{
					stringBuilder.Append("(");
					for (int i = 0; i < num5; i++)
					{
						if (i > 0)
						{
							stringBuilder.Append(",");
						}
						stringBuilder.Append(dice[num + i]);
					}
					stringBuilder.Append(")");
					stringBuilder.Append(c);
				}
				else if (num3 == 1)
				{
					stringBuilder.Append(dice[num]);
				}
				else
				{
					stringBuilder.Append("(");
					for (int j = 0; j < num3; j++)
					{
						if (j > 0)
						{
							stringBuilder.Append(",");
						}
						stringBuilder.Append(dice[num + j]);
					}
					stringBuilder.Append(")");
				}
				num += num5;
				num2 = item.Index + item.Length;
			}
			stringBuilder.Append(formula.Substring(num2));
			return stringBuilder.ToString();
		}

		public static int ResolveTotal(string formula, int[] dice)
		{
			int num = 0;
			StringBuilder stringBuilder = new StringBuilder();
			foreach (Match item in TokenRegex.Matches(formula))
			{
				string value = item.Value;
				Match match2 = DiceRegex.Match(value);
				if (match2.Success)
				{
					int num2 = int.Parse(match2.Groups[1].Value);
					char c = ((match2.Groups[3].Length > 0) ? char.ToUpperInvariant(match2.Groups[3].Value[0]) : '\0');
					if (c == '\0')
					{
						if (num + num2 > dice.Length)
						{
							throw new ArgumentException("Not enough dice values supplied.");
						}
						int num3 = 0;
						for (int i = 0; i < num2; i++)
						{
							num3 += dice[num++];
						}
						stringBuilder.Append(num3);
						continue;
					}
					int num4 = num2 * 2;
					if (num + num4 > dice.Length)
					{
						throw new ArgumentException("Not enough dice values supplied.");
					}
					int num5 = 0;
					for (int j = 0; j < num2; j++)
					{
						num5 += dice[num++];
					}
					int num6 = 0;
					for (int k = 0; k < num2; k++)
					{
						num6 += dice[num++];
					}
					int value2 = ((c == 'A') ? Math.Max(num5, num6) : Math.Min(num5, num6));
					stringBuilder.Append(value2);
				}
				else
				{
					stringBuilder.Append(value);
				}
			}
			object value3 = new DataTable().Compute(stringBuilder.ToString(), null);
			return Convert.ToInt32(value3);
		}

		public static int ResolveMaxTotal(string expression)
		{
			if (string.IsNullOrWhiteSpace(expression))
			{
				throw new ArgumentException("Expression cannot be empty.");
			}
			List<int> list = new List<int>();
			foreach (Match item2 in DiceRegex.Matches(expression))
			{
				int num = int.Parse(item2.Groups[1].Value);
				int num2 = int.Parse(item2.Groups[2].Value);
				string value = item2.Groups[3].Value;
				int item = num * num2;
				list.Add(item);
				if (!string.IsNullOrEmpty(value))
				{
					list.Add(item);
				}
			}
			return ResolveTotal(expression, list.ToArray());
		}

		public static string ExtractTalespireDiceRolls(string expression)
		{
			Regex regex = new Regex("(?<op>[+\\-*/]?)\\s*(?<dice>\\d+[dD]\\d+)(?<rep>[aAdD]?)|\\d+", RegexOptions.Compiled);
			StringBuilder stringBuilder = new StringBuilder();
			bool flag = true;
			foreach (Match item in regex.Matches(expression))
			{
				if (!item.Groups["dice"].Success)
				{
					continue;
				}
				string value = item.Groups["op"].Value;
				string value2 = item.Groups["dice"].Value;
				string value3 = item.Groups["rep"].Value;
				int num = ((value3.Length <= 0) ? 1 : 2);
				for (int i = 0; i < num; i++)
				{
					if (!flag)
					{
						stringBuilder.Append((value.Length > 0) ? value : "+");
					}
					stringBuilder.Append(value2);
					flag = false;
				}
			}
			return stringBuilder.ToString().Replace("-", "+").Replace("/", "+")
				.Replace("*", "+");
		}

		public static string SimplifyExpression(string formula)
		{
			if (string.IsNullOrWhiteSpace(formula))
			{
				return formula;
			}
			formula = Regex.Replace(formula, "(?<!\\w)(" + TermPattern + ")\\s*\\*\\s*0|0\\s*\\*\\s*(" + TermPattern + ")", "+0");
			formula = Regex.Replace(formula, "(?<!\\w)1\\s*\\*\\s*(" + TermPattern + ")", "$1");
			formula = Regex.Replace(formula, "(" + TermPattern + ")\\s*\\*\\s*1(?!\\w)", "$1");
			formula = Regex.Replace(formula, "\\+\\+", "+");
			formula = Regex.Replace(formula, "\\+-", "-");
			formula = Regex.Replace(formula, "-\\+", "-");
			formula = Regex.Replace(formula, "--", "+");
			formula = Regex.Replace(formula, "^\\+", "");
			return formula;
		}

		public static string StripTrailingInteger(string input)
		{
			if (string.IsNullOrEmpty(input))
			{
				return input;
			}
			return Regex.Replace(input, "(\\(\\d+\\)|\\d+)$", "");
		}

		public static string ComputeConstants(string expression)
		{
			while (expression.Contains("("))
			{
				int startIndex = expression.IndexOf("(");
				string text = expression.Substring(startIndex);
				text = expression.Substring(0, expression.IndexOf(")") + 1);
				string text2 = Compute(text).ToString();
				expression = expression.Replace(text, text2);
				LoggingPlugin.LogDebug("Compute Constants: Replacing '" + text + "' With '" + text2 + "'. Expression is now: " + expression);
			}
			return expression;
		}

		private static string Compute(string expression)
		{
			DataTable dataTable = new DataTable();
			return dataTable.Compute(expression, null).ToString();
		}

		private static int EvaluateIntegerExpression(string expression)
		{
			object value = new DataTable().Compute(expression, null);
			return Convert.ToInt32(value);
		}
	}

	public class TargetsCollection
	{
		public string targetsCollectingSpecType = null;

		public Characters.Spec targetsCollectingSpec = null;

		public CreatureBoardAsset targetsCollectingInstigator;

		public Scripts.MessagePublicity targetsCollectingPublicity = Scripts.MessagePublicity.publicMessage;

		public int targetsCollecting = 0;

		public List<CreatureBoardAsset> targetsCollected = new List<CreatureBoardAsset>();
	}

	[HarmonyPatch(typeof(UI_DiceRollGroup), "DisplayGroup")]
	public static class PatchSetResult
	{
		public static bool Prefix(UI_DiceRollGroup __instance, RollGroup resultsGroup, bool isFirst, TMP_Text ____headerText, FactoryInspectorSetup<UI_DiceOperator> ____operatorFactory, RectTransform ____content, int ____contentGridWrapWidth, GridLayoutGroup ____contentGrid, RectTransform ____transform)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			if (DiceRoller.pendingRoll != null)
			{
				string text = (isFirst ? "Rolled" : "And");
				string name = resultsGroup.Name;
				if (!string.IsNullOrWhiteSpace(name))
				{
					text = text + " " + name;
				}
				____headerText.text = text;
				int num = (int)(from m in typeof(UI_DiceRollGroup).GetRuntimeMethods()
					where m.Name == "DisplayOperand"
					select m).FirstOrDefault().Invoke(__instance, new object[2] { resultsGroup.Result, true });
				UI_DiceOperator val = ____operatorFactory.Hire(true);
				((Component)val).transform.SetAsLastSibling();
				if (((Transform)____content).childCount <= ____contentGridWrapWidth)
				{
					____contentGrid.constraint = (Constraint)2;
					____contentGrid.constraintCount = 1;
					RectTransformExtensions.SetHeight(____transform, 25f + ____contentGrid.cellSize.y);
					return false;
				}
				____contentGrid.constraint = (Constraint)1;
				____contentGrid.constraintCount = ____contentGridWrapWidth;
				float num2 = math.ceil((float)((Transform)____content).childCount / (float)____contentGrid.constraintCount) * (____contentGrid.cellSize.y + ____contentGrid.spacing.y);
				RectTransformExtensions.SetHeight(____transform, 25f + num2);
				return false;
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(GUIManager), "PlayMode_OnStateChange")]
	public static class GUIManagerPlayModeOnStateChange
	{
		public static bool Prefix(State obj)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			if (((object)obj).ToString() == "PlayMode+TurnBased")
			{
				LoggingPlugin.LogDebug("Initiative Mode Selected");
				AssetDataPlugin.SendInfo("org.lordashes.plugins.d20", "action:initiative");
				ChatManager.SendChatMessageToBoard("[Roll Initiative!]\r\nCollecting Initiatives", LocalPlayer.Id.Value, (float3?)null, false);
				initiativeOrder.Clear();
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(UI_InitativeManager), "OpenEdit")]
	public class InitiativeManagerApplyEditPatch
	{
		private static void Postfix(bool value)
		{
			//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_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			LoggingPlugin.LogDebug("Applying Stored Initiatives");
			InitiativeManager.SetEditQueue(initiativeOrder.Values.ToArray());
			LoggingPlugin.LogDebug("Ending Initiative Collection");
			if (collectingInitiative && summarizeInitiative)
			{
				string text = "";
				foreach (KeyValuePair<int, QueueElement> item in initiativeOrder)
				{
					CreatureBoardAsset val = null;
					CreaturePresenter.TryGetAsset(item.Value.CreatureGuid, ref val);
					if ((Object)(object)val != (Object)null)
					{
						text = text + item.Key + ": " + val.Name + "\r\n";
					}
				}
				if (text != "")
				{
					text = text.Substring(0, text.Length - 2);
					ChatManager.SendChatMessageToBoard("[Initiative]\r\n" + text, LocalPlayer.Id.Value, (float3?)null, false);
				}
			}
			collectingInitiative = false;
		}
	}

	[HarmonyPatch(typeof(UIChatMessageManager), "AddChatMessage")]
	public static class PatchAddMessage
	{
		public static bool Prefix(string creatureName, Texture2D icon, string chatMessage, IChatFocusable focus = null)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			LoggingPlugin.LogDebug("Initiative Collection: " + collectingInitiative);
			if (collectingInitiative)
			{
				LoggingPlugin.LogDebug("Initiative Collection: Active");
				CreatureBoardAsset val = null;
				CreaturePresenter.TryGetAsset(LocalClient.SelectedCreatureId, ref val);
				if (LocalClient.IsPartyGm)
				{
					LoggingPlugin.LogDebug("Initiative Collection: GM Client");
					string text = chatMessage.Substring(chatMessage.LastIndexOf(" ") + 1);
					LoggingPlugin.LogDebug("Initiative Collection: Adding Roll: " + text + " For " + creatureName);
					initiativeOrder.Add(int.Parse(text), new QueueElement((ElementType)0, LocalClient.SelectedCreatureId));
				}
				else
				{
					LoggingPlugin.LogDebug("Initiative Collection: Non-GM Client");
				}
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(UIChatMessageManager), "AddDiceResultMessage")]
	public static class PatchAddDiceResultMessage
	{
		public static bool Prefix(RollResults diceResult, ResultsOrigin origin, ClientGuid sender, bool hidden, IChatFocusable focus = null)
		{
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			if (DiceRoller.pendingRoll != null)
			{
				DiceRoller.RollSimplifier.RollParseResult rollParseResult = DiceRoller.RollSimplifier.ParseRollResults(diceResult);
				int num = rollParseResult.Totals.Sum();
				DiceRoller.RollResult result = new DiceRoller.RollResult
				{
					total = rollParseResult.Totals.Sum(),
					dice = ((IEnumerable<short>)rollParseResult.AllDiceValues).Select((Func<short, int>)((short s) => s)).ToArray()
				};
				DiceRoller.pendingRoll?.TrySetResult(result);
				DiceRoller.pendingRoll = null;
				DiceRollManager val = Object.FindObjectOfType<DiceRollManager>();
				if ((Object)(object)val != (Object)null)
				{
					val.RemoveRoll(diceResult.RollId);
				}
				return false;
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(BoardTool), "CallCameraClick")]
	public static class PatchCallCameraClick
	{
		[CompilerGenerated]
		private sealed class <holdAndClear>d__3 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public float delay;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <holdAndClear>d__3(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_0031: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(delay);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					targetsCollection.targetsCollecting = 0;
					targetsCollection.targetsCollected.Clear();
					return false;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		[CompilerGenerated]
		private sealed class <preventClickCollection>d__4 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public float delay;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <preventClickCollection>d__4(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					preventClickCalls = true;
					<>2__current = (object)new WaitForSeconds(delay);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					preventClickCalls = false;
					return false;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		public static bool preventClickCalls;

		public static bool Prefix(CameraClickEvent click)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			if (!preventClickCalls && targetsCollection.targetsCollecting > 0 && !((object)BoardToolManager.CurrentTool).ToString().Contains("RulerBoardTool"))
			{
				string[] obj = new string[6] { "Generic Click: User Click At ", null, null, null, null, null };
				Vector2 position = click.position;
				obj[1] = ((object)(Vector2)(ref position)).ToString();
				obj[2] = " With Tool ";
				obj[3] = ((object)BoardToolManager.CurrentTool).ToString();
				obj[4] = " And Collecting ";
				obj[5] = collecting;
				LoggingPlugin.LogDebug(string.Concat(obj));
				preventClickCalls = true;
				((MonoBehaviour)_self).StartCoroutine(preventClickCollection(1f));
				CreatureBoardAsset val = null;
				float3 val2 = default(float3);
				PixelPickingManager.TryGetPickedCreature(ref val2, ref val);
				if ((Object)(object)val != (Object)null)
				{
					LoggingPlugin.LogDebug("Generic Click: Added Asset " + val.Name + " At " + ((object)(float3)(ref val2)).ToString());
					targetsCollection.targetsCollected.Add(val);
					if (targetsCollection.targetsCollected.Count >= targetsCollection.targetsCollecting)
					{
						ProcessSelection();
					}
				}
				if (Input.GetMouseButtonDown(2))
				{
					ProcessSelection();
				}
			}
			return true;
		}

		public static void ProcessSelection()
		{
			Characters.CharacterSpecs stack = new Characters.CharacterSpecs();
			((MonoBehaviour)_self).StartCoroutine(preventClickCollection(2f));
			((MonoBehaviour)_self).StartCoroutine(Scripts.ProcessSequence(stack, (targetsCollection.targetsCollectingSpecType == "attack" || targetsCollection.targetsCollectingSpecType == "spell") ? Characters.CharactersSpecs.CheckType.Attack : Characters.CharactersSpecs.CheckType.Opposed, targetsCollection.targetsCollectingSpec, targetsCollection.targetsCollectingInstigator, targetsCollection.targetsCollected.ToArray(), targetsCollection.targetsCollectingPublicity));
			((MonoBehaviour)_self).StartCoroutine(holdAndClear(2f));
		}

		[IteratorStateMachine(typeof(<holdAndClear>d__3))]
		public static IEnumerator holdAndClear(float delay)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <holdAndClear>d__3(0)
			{
				delay = delay
			};
		}

		[IteratorStateMachine(typeof(<preventClickCollection>d__4))]
		public static IEnumerator preventClickCollection(float delay)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <preventClickCollection>d__4(0)
			{
				delay = delay
			};
		}
	}

	[HarmonyPatch(typeof(Ruler), "SetNewMode")]
	public static class PatchSetNewMode
	{
		public static bool Prefix(int newModeIndex, bool forceRecreate)
		{
			if (targetsCollection.targetsCollecting > 0)
			{
				LoggingPlugin.LogDebug("D20 Plugin: Ruler Mode Change To Type " + rulerTypes[newModeIndex] + " (" + newModeIndex + ")");
				collecting = rulerTypes[newModeIndex];
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(Ruler), "OnClick")]
	public static class PatchOnClick
	{
		[CompilerGenerated]
		private sealed class <closeRuler>d__2 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <closeRuler>d__2(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0038: Unknown result type (might be due to invalid IL or missing references)
				//IL_0042: Expected O, but got Unknown
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0069: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					UI_Rulers.EnableRulers(false);
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					UI_Rulers.EnableRulers(true);
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 2;
					return true;
				case 2:
					<>1__state = -1;
					UI_Rulers.EnableRulers(false);
					return false;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		public static bool Prefix(Ruler __instance, int buttonId)
		{
			return true;
		}

		public static void Postfix(Ruler __instance, int buttonId)
		{
			//IL_030e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0315: Unknown result type (might be due to invalid IL or missing references)
			//IL_031a: Unknown result type (might be due to invalid IL or missing references)
			//IL_031f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0342: Unknown result type (might be due to invalid IL or missing references)
			//IL_0347: Unknown result type (might be due to invalid IL or missing references)
			//IL_0553: Unknown result type (might be due to invalid IL or missing references)
			//IL_0558: Unknown result type (might be due to invalid IL or missing references)
			//IL_0369: Unknown result type (might be due to invalid IL or missing references)
			//IL_036e: Unknown result type (might be due to invalid IL or missing references)
			//IL_038e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0395: Unknown result type (might be due to invalid IL or missing references)
			//IL_039a: Unknown result type (might be due to invalid IL or missing references)
			//IL_039f: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_040b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0410: Unknown result type (might be due to invalid IL or missing references)
			//IL_057a: Unknown result type (might be due to invalid IL or missing references)
			//IL_057f: Unknown result type (might be due to invalid IL or missing references)
			//IL_048c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0491: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_05cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0615: Unknown result type (might be due to invalid IL or missing references)
			//IL_061c: Unknown result type (might be due to invalid IL or missing references)
			//IL_062d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_0673: Unknown result type (might be due to invalid IL or missing references)
			//IL_0678: Unknown result type (might be due to invalid IL or missing references)
			//IL_021b: Unknown result type (might be due to invalid IL or missing references)
			LoggingPlugin.LogDebug("Ruler " + ((Object)__instance).name + " Click: Button " + buttonId + ", Targets: " + targetsCollection.targetsCollecting + ", Collecting: " + PluginD20.collecting);
			if (PatchCallCameraClick.preventClickCalls || targetsCollection.targetsCollecting <= 0)
			{
				return;
			}
			List<Vector3> list = new List<Vector3>();
			if (!(PluginD20.collecting != ""))
			{
				return;
			}
			List<Vector3> list2 = new List<Vector3>();
			GameObject val = GameObject.Find(((Object)__instance).name);
			Vector3 val2;
			if ((Object)(object)val != (Object)null)
			{
				foreach (Transform item in ExtensionMethods.Children(val.transform))
				{
					LoggingPlugin.LogDebug("Ruler " + ((Object)__instance).name + ": Found Child: " + ((Object)item).name + " While Searching For " + PluginD20.collecting + "Indicator(Clone)");
					if (!(((Object)item).name == PluginD20.collecting + "Indicator(Clone)"))
					{
						continue;
					}
					LoggingPlugin.LogDebug("Ruler " + ((Object)__instance).name + ": Found " + ((Object)item).name + " With " + ExtensionMethods.Children(((Component)item).transform).Count() + " Children");
					foreach (Transform item2 in ExtensionMethods.Children(((Component)item).transform))
					{
						string collecting = PluginD20.collecting;
						val2 = item2.position;
						LoggingPlugin.LogDebug(collecting + " Point: " + ((object)(Vector3)(ref val2)).ToString());
						if (item2.position != Vector3.zero)
						{
							list.Add(item2.position);
						}
					}
				}
			}
			LoggingPlugin.LogDebug("Ruler " + ((Object)__instance).name + ": Collecting: " + PluginD20.collecting + ", Points: " + list.Count);
			string collecting2 = PluginD20.collecting;
			string text = collecting2;
			CreatureGuid creatureId;
			if (!(text == "Sphere"))
			{
				if (!(text == "Box") || list.Count != 2)
				{
					return;
				}
				LoggingPlugin.LogDebug("Ruler " + ((Object)__instance).name + ": Applying Selection Based On " + PluginD20.collecting);
				foreach (CreatureBoardAsset item3 in (IEnumerable<CreatureBoardAsset>)CreaturePresenter.GetTempReadOnlyViewOfAllCreatureAssets())
				{
					if (item3.CreatureId != LocalClient.SelectedCreatureId)
					{
						string[] obj = new string[8]
						{
							"Ruler ",
							((Object)__instance).name,
							": Asset ",
							item3.Name,
							" (",
							null,
							null,
							null
						};
						creatureId = item3.CreatureId;
						obj[5] = ((object)(CreatureGuid)(ref creatureId)).ToString();
						obj[6] = ") At ";
						val2 = ((Component)((MovableBoardAsset)item3).Rotator).transform.position;
						obj[7] = ((object)(Vector3)(ref val2)).ToString();
						LoggingPlugin.LogDebug(string.Concat(obj));
						if (IsPointInsideBox(list[0], list[1], ((Component)((MovableBoardAsset)item3).Rotator).transform.position))
						{
							string[] obj2 = new string[7]
							{
								"Ruler ",
								((Object)__instance).name,
								": Asset ",
								item3.Name,
								" (",
								null,
								null
							};
							creatureId = item3.CreatureId;
							obj2[5] = ((object)(CreatureGuid)(ref creatureId)).ToString();
							obj2[6] = ") Is Selected";
							LoggingPlugin.LogDebug(string.Concat(obj2));
							targetsCollection.targetsCollected.Add(item3);
						}
					}
				}
				PatchCallCameraClick.preventClickCalls = true;
				((MonoBehaviour)_self).StartCoroutine(PatchCallCameraClick.preventClickCollection(1f));
				((MonoBehaviour)_self).StartCoroutine(closeRuler());
				PluginD20.collecting = "";
			}
			else
			{
				if (list.Count != 2)
				{
					return;
				}
				LoggingPlugin.LogDebug("Ruler " + ((Object)__instance).name + ": Applying Selection Based On " + PluginD20.collecting);
				val2 = list[0] - list[1];
				float magnitude = ((Vector3)(ref val2)).magnitude;
				LoggingPlugin.LogDebug("Radius = " + magnitude);
				foreach (CreatureBoardAsset item4 in (IEnumerable<CreatureBoardAsset>)CreaturePresenter.GetTempReadOnlyViewOfAllCreatureAssets())
				{
					if (item4.CreatureId != LocalClient.SelectedCreatureId)
					{
						val2 = ((Component)((MovableBoardAsset)item4).Rotator).transform.position - list[0];
						float magnitude2 = ((Vector3)(ref val2)).magnitude;
						string[] obj3 = new string[11]
						{
							"Ruler ",
							((Object)__instance).name,
							": Asset ",
							item4.Name,
							" (",
							null,
							null,
							null,
							null,
							null,
							null
						};
						creatureId = item4.CreatureId;
						obj3[5] = ((object)(CreatureGuid)(ref creatureId)).ToString();
						obj3[6] = ") At ";
						val2 = ((Component)((MovableBoardAsset)item4).Rotator).transform.position;
						obj3[7] = ((object)(Vector3)(ref val2)).ToString();
						obj3[8] = " Is ";
						obj3[9] = magnitude2.ToString();
						obj3[10] = " away";
						LoggingPlugin.LogDebug(string.Concat(obj3));
						if (magnitude2 <= magnitude)
						{
							string[] obj4 = new string[7]
							{
								"Ruler ",
								((Object)__instance).name,
								": Asset ",
								item4.Name,
								" (",
								null,
								null
							};
							creatureId = item4.CreatureId;
							obj4[5] = ((object)(CreatureGuid)(ref creatureId)).ToString();
							obj4[6] = ") Is Selected";
							LoggingPlugin.LogDebug(string.Concat(obj4));
							targetsCollection.targetsCollected.Add(item4);
						}
					}
				}
				PatchCallCameraClick.preventClickCalls = true;
				((MonoBehaviour)_self).StartCoroutine(PatchCallCameraClick.preventClickCollection(1f));
				((MonoBehaviour)_self).StartCoroutine(closeRuler());
				PluginD20.collecting = "";
			}
		}

		[IteratorStateMachine(typeof(<closeRuler>d__2))]
		public static IEnumerator closeRuler()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <closeRuler>d__2(0);
		}

		public static bool IsPointInsideBox(Vector3 cornerA, Vector3 cornerB, Vector3 point)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: 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_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			float num = Mathf.Min(cornerA.x, cornerB.x);
			float num2 = Mathf.Max(cornerA.x, cornerB.x);
			float num3 = Mathf.Min(cornerA.y, cornerB.y);
			float num4 = Mathf.Max(cornerA.y, cornerB.y);
			float num5 = Mathf.Min(cornerA.z, cornerB.z);
			float num6 = Mathf.Max(cornerA.z, cornerB.z);
			return point.x >= num && point.x <= num2 && point.y >= num3 && point.y <= num4 && point.z >= num5 && point.z <= num6;
		}
	}

	public class RemoteQuerySpecs
	{
		public string name { get; set; }

		public string item { get; set; }
	}

	public class RemoteQueryRequest
	{
		public Guid id { get; set; }

		public RemoteQuerySpecs query { get; set; }

		public string requestor { get; set; }

		public string[] targetClients { get; set; }

		public string[] targetPlayers { get; set; }
	}

	public class RemoteQueryResponse
	{
		public Guid id { get; set; }

		public string response { get; set; }

		public string requestor { get; set; }

		public string client { get; set; }

		public string player { get; set; }
	}

	public static class RemoteQuery
	{
		[CompilerGenerated]
		private sealed class <ProcessResultsAfterSetDelay>d__5 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public Guid id;

			public TaskCompletionSource<List<RemoteQueryResponse>> token;

			public float delay;

			private List<RemoteQueryResponse> <returnResponse>5__1;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <ProcessResultsAfterSetDelay>d__5(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<returnResponse>5__1 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0042: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					LoggingPlugin.LogDebug("Wait: Waiting For Responses: Started Wait For Timeout Of " + delay);
					<>2__current = (object)new WaitForSeconds(delay);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					LoggingPlugin.LogDebug("Wait: Triggering Set Delay Callback With " + results[id].Count + " results");
					<returnResponse>5__1 = results[id];
					results.Remove(id);
					LoggingPlugin.LogDebug("Wait: Results Removed From Queue. Posting Results (Token: " + ((token == null) ? "Null" : "Ready") + ")");
					token?.TrySetResult(<returnResponse>5__1);
					token = null;
					return false;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		[CompilerGenerated]
		private sealed class <ProcessResultsAfterSetResponses>d__6 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public Guid id;

			public TaskCompletionSource<List<RemoteQueryResponse>> token;

			public int expectedResult;

			public int delay;

			private List<RemoteQueryResponse> <returnResponse>5__1;

			private ulong <i>5__2;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <ProcessResultsAfterSetResponses>d__6(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<returnResponse>5__1 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00aa: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					if (delay == 0)
					{
						delay = int.MaxValue;
					}
					LoggingPlugin.LogDebug("Wait: Waiting For Responses: Started Wait For " + expectedResult + " Responses With Timeout Of " + delay);
					<i>5__2 = 0uL;
					break;
				case 1:
					<>1__state = -1;
					<i>5__2++;
					break;
				}
				if (<i>5__2 < (ulong)((long)delay * 2L) && results[id].Count < expectedResult)
				{
					<>2__current = (object)new WaitForSeconds(0.5f);
					<>1__state = 1;
					return true;
				}
				LoggingPlugin.LogDebug("Wait: Triggering Set Responses Callback With " + results[id].Count + " results");
				<returnResponse>5__1 = results[id];
				results.Remove(id);
				LoggingPlugin.LogDebug("Wait: Results Removed From Queue. Posting Results (Token: " + ((token == null) ? "Null" : "Ready") + ")");
				token?.TrySetResult(<returnResponse>5__1);
				token = null;
				return false;
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		public static string hold;

		public static TaskCompletionSource<bool> reactionToken;

		public static Task<List<RemoteQueryResponse>> MakeRequest(RemoteQuerySpecs query, TaskCompletionSource<List<RemoteQueryResponse>> token, string[] specificClients = null, string[] specificPlayers = null, int expectedResult = 0, int expectedResultsTimeout = 0)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			Guid guid = System.Guid.NewGuid();
			results.Add(guid, new List<RemoteQueryResponse>());
			RemoteQueryRequest obj = new RemoteQueryRequest
			{
				id = guid,
				query = query
			};
			ClientGuid id = LocalClient.Id;
			obj.requestor = ((object)(ClientGuid)(ref id)).ToString();
			obj.targetClients = specificClients;
			obj.targetPlayers = specificPlayers;
			string text = JsonConvert.SerializeObject((object)obj);
			LoggingPlugin.LogDebug("Sending Remote Request:" + text);
			AssetDataPlugin.SendInfo("org.lordashes.plugins.d20", text);
			if (expectedResult == 0 && expectedResultsTimeout > 0)
			{
				((MonoBehaviour)_self).StartCoroutine(ProcessResultsAfterSetDelay(guid, token, expectedResultsTimeout));
			}
			else if (expectedResult == 0 && expectedResultsTimeout == 0)
			{
				((MonoBehaviour)_self).StartCoroutine(ProcessResultsAfterSetResponses(guid, token, expectedResult, 10));
			}
			else
			{
				((MonoBehaviour)_self).StartCoroutine(ProcessResultsAfterSetResponses(guid, token, expectedResult, expectedResultsTimeout));
			}
			return token.Task;
		}

		public static async void ReceiveRemoteQueryResult(DatumChange datum)
		{
			LoggingPlugin.LogDebug("Remote Message:" + JsonConvert.SerializeObject((object)datum));
			ChangeAction action2 = datum.action;
			ChangeAction val = action2;
			ChangeAction val2 = val;
			if ((int)val2 != 0 && val2 - 2 > 1)
			{
				return;
			}
			LoggingPlugin.LogDebug("Remote Message: Checking Message Type");
			ClientGuid id;
			if (datum.value.ToString().Contains("message:"))
			{
				SystemMessage.DisplayInfoText("D20 Plugin:\r\n" + datum.value.ToString().Substring("message:".Length), 2.5f, 0f, (Action)null);
			}
			else if (datum.value.ToString().Contains("action:"))
			{
				string action = datum.value.ToString().Substring("action:".Length);
				string text = action;
				if (text == "initiative")
				{
					LoggingPlugin.LogDebug("Remote Message: Starting Initiative Collection");
					collectingInitiative = true;
				}
			}
			else if (datum.value.ToString().Contains("query"))
			{
				LoggingPlugin.LogDebug("Remote Message: Is A Request");
				RemoteQueryRequest request = JsonConvert.DeserializeObject<RemoteQueryRequest>(datum.value.ToString());
				int num;
				if (request.targetClients != null)
				{
					string[] targetClients = request.targetClients;
					id = LocalClient.Id;
					num = ((!targetClients.Contains<string>(((object)(ClientGuid)(ref id)).ToString())) ? 1 : 0);
				}
				else
				{
					num = 0;
				}
				if (num != 0)
				{
					return;
				}
				PlayerGuid id2;
				int num2;
				if (request.targetPlayers != null)
				{
					string[] targetPlayers = request.targetPlayers;
					id2 = LocalPlayer.Id;
					num2 = ((!targetPlayers.Contains<string>(((object)(PlayerGuid)(ref id2)).ToString())) ? 1 : 0);
				}
				else
				{
					num2 = 0;
				}
				if (num2 != 0)
				{
					return;
				}
				LoggingPlugin.LogDebug("Remote Message: Seeking Sheets Matching " + request.query.name);
				Characters.CharacterSpecs[] queryResults = _self.characters.Find(DiceRoller.StripTrailingInteger(request.query.name));
				LoggingPlugin.LogDebug("Remote Message: Found " + ((queryResults == null) ? "0" : queryResults.Length.ToString()) + " Sheets");
				bool foundMatch = false;
				if (queryResults == null || queryResults.Length == 0)
				{
					return;
				}
				Characters.CharacterSpecs[] array = queryResults;
				foreach (Characters.CharacterSpecs sheet in array)
				{
					LoggingPlugin.LogDebug("Remote Message: Opposed Options " + request.query.item);
					string msg = "";
					string opposedOption = request.query.item;
					if (opposedOption.StartsWith("damage:"))
					{
						if (queryResults[0].FindFirstValue("Reaction") == "1")
						{
							LoggingPlugin.LogDebug("Delaying Response Until Opposing User Click Continue");
							hold = "Damage Reaction";
							await WaitForReaction();
						}
						LoggingPlugin.LogDebug("Remote Message: Looking For Damage Adjustments");
						string matchKeword = opposedOption.Substring("damage:".Length);
						LoggingPlugin.LogDebug("Remote Message: Looking For '" + matchKeword + "' Damage Adjustments");
						Characters.Spec immunitiesSpec = sheet.specs.Where((Characters.Spec e) => e.name == "Immunities").FirstOrDefault();
						Characters.Spec resistancesSpec = sheet.specs.Where((Characters.Spec e) => e.name == "Resistances").FirstOrDefault();
						Characters.Spec reductionsSpec = sheet.specs.Where((Characters.Spec e) => e.name == "Reductions").FirstOrDefault();
						Characters.Spec vulnerabilitiesSpec = sheet.specs.Where((Characters.Spec e) => e.name == "Vulnerabilities").FirstOrDefault();
						string immunities = ((immunitiesSpec != null) ? sheet.Resolve(immunitiesSpec.formula) : "");
						string resistances = ((resistancesSpec != null) ? sheet.Resolve(resistancesSpec.formula) : "");
						string reductions = ((reductionsSpec != null) ? sheet.Resolve(reductionsSpec.formula) : "");
						string vulnerabilities = ((vulnerabilitiesSpec != null) ? sheet.Resolve(vulnerabilitiesSpec.formula) : "");
						LoggingPlugin.LogDebug("Remote Message: Collected Possible Damage Adjustments");
						LoggingPlugin.LogDebug("Remote Message: Immunities = " + immunities);
						LoggingPlugin.LogDebug("Remote Message: Resistances = " + resistances);
						LoggingPlugin.LogDebug("Remote Message: Reductions = " + reductions);
						LoggingPlugin.LogDebug("Remote Message: Vulnerabilities = " + vulnerabilities);
						if (immunities != null && (immunities.Contains(matchKeword) || immunities.Contains("*")))
						{
							msg = msg + opposedOption + "=Immunity,";
						}
						else if (resistances != null && (resistances.Contains(matchKeword) || resistances.Contains("*")))
						{
							msg = msg + opposedOption + "=Resistance,";
						}
						else if (reductions == null || (!reductions.Contains(matchKeword) && !resistances.Contains("*")))
						{
							msg = ((vulnerabilities == null || (!vulnerabilities.Contains(matchKeword) && !vulnerabilities.Contains("*"))) ? (msg + opposedOption + "=Regular,") : (msg + opposedOption + "=Vulnerability,"));
						}
						else
						{
							string amount3 = reductions.Substring(reductions.IndexOf(matchKeword));
							amount3 = amount3.Substring(amount3.IndexOf("(") + 1);
							amount3 = amount3.Substring(0, amount3.IndexOf(")"));
							msg = msg + opposedOption + "=" + amount3 + ",";
						}
					}
					else
					{
						int bestScore = 0;
						string bestOptionName = "";
						Characters.Spec bestOption = null;
						string[] array2 = opposedOption.Split(new char[1] { ',' });
						foreach (string opposedOptionItem in array2)
						{
							if (queryResults[0].FindFirstValue("Reaction") == "1")
							{
								LoggingPlugin.LogDebug("Delaying Response Until Opposing User Click Continue");
								hold = "Defense Reaction";
								await WaitForReaction();
							}
							LoggingPlugin.LogDebug("Remote Message: Trying To Find " + opposedOption);
							Characters.Spec seekResult = sheet.specs.Where((Characters.Spec e) => e.name == opposedOption).FirstOrDefault();
							if (seekResult != null)
							{
								LoggingPlugin.LogDebug("Remote Message: Found " + seekResult.name + " (" + seekResult.formula + ")");
								int score = DiceRoller.ResolveMaxTotal(sheet.Resolve(seekResult.formula));
								if (score > bestScore)
								{
									bestScore = score;
									bestOptionName = opposedOptionItem;
									bestOption = seekResult;
								}
							}
						}
						CreatureBoardAsset target = null;
						try
						{
							target = ((IEnumerable<CreatureBoardAsset>)(object)CreaturePresenter.GetTempReadOnlyViewOfAllCreatureAssets()).Where((CreatureBoardAsset cba) => cba.Name == request.query.name).FirstOrDefault();
						}
						catch
						{
						}
						DiceRoller.RollResult rollResult = await DiceRoller.Roll(sheet, bestOptionName, bestOption.formula, rollingStyleDefensive);
						Scripts.ProcessExtensions(Scripts.ExtensionType.targetSkillResult, null, target, null, sheet, null, bestOptionName, null, rollResult, delegate(DiceRoller.RollResult r)
						{
							rollResult = r;
						});
						msg = msg + JsonConvert.SerializeObject((object)rollResult) + ",";
					}
					if (msg != "")
					{
						if (msg.IndexOf("=") < 0)
						{
							msg = "[" + msg.Substring(0, msg.Length - 1) + "]";
						}
						foundMatch = true;
						if (msg.EndsWith(","))
						{
							msg = msg.Substring(0, msg.Length - 1);
						}
						LoggingPlugin.LogDebug("Remote Message: Sending Result To Requestor " + request.requestor.ToString() + " Message '" + msg + "'");
						RemoteQueryResponse obj2 = new RemoteQueryResponse
						{
							id = request.id,
							requestor = request.requestor.ToString(),
							response = msg
						};
						id = LocalClient.Id;
						obj2.client = ((object)(ClientGuid)(ref id)).ToString();
						id2 = LocalPlayer.Id;
						obj2.player = ((object)(PlayerGuid)(ref id2)).ToString();
						RemoteQueryResponse response = obj2;
						AssetDataPlugin.SendInfo("org.lordashes.plugins.d20", JsonConvert.SerializeObject((object)response));
					}
				}
				if (!foundMatch)
				{
					SystemMessage.DisplayInfoText("Characte Sheet For " + request.query.name + " Is Missing " + request.query.item, 2.5f, 0f, (Action)null);
				}
			}
			else
			{
				LoggingPlugin.LogDebug("Remote Message: Is A Response");
				RemoteQueryResponse result = JsonConvert.DeserializeObject<RemoteQueryResponse>(datum.value.ToString());
				LoggingPlugin.LogDebug("Remote Message: Message Destined For Requestor " + result.requestor.ToString());
				string[] obj3 = new string[6] { "Remote Message: Check: ", result.requestor, "=", null, null, null };
				id = LocalClient.Id;
				obj3[3] = ((object)(ClientGuid)(ref id)).ToString();
				obj3[4] = ", Expecting Id=";
				obj3[5] = results.ContainsKey(result.id).ToString();
				LoggingPlugin.LogDebug(string.Concat(obj3));
				string requestor = result.requestor;
				id = LocalClient.Id;
				if (requestor == ((object)(ClientGuid)(ref id)).ToString() && results.ContainsKey(result.id))
				{
					LoggingPlugin.LogDebug("Remote Message: Adding Response To Results List (" + result.response + ")");
					results[result.id].Add(result);
					LoggingPlugin.LogDebug("Remote Message: Collected " + results[result.id].Count() + " Responses");
				}
			}
		}

		public static async Task WaitForReaction()
		{
			try
			{
				reactionToken = new TaskCompletionSource<bool>();
				await reactionToken.Task;
				LoggingPlugin.LogDebug("Reaction " + hold + " finished");
			}
			catch (OperationCanceledException)
			{
				LoggingPlugin.LogDebug("Reaction " + hold + " was canceled");
			}
			catch (Exception ex3)
			{
				Exception ex = ex3;
				Debug.LogException(ex);
			}
		}

		[IteratorStateMachine(typeof(<ProcessResultsAfterSetDelay>d__5))]
		public static IEnumerator ProcessResultsAfterSetDelay(Guid id, TaskCompletionSource<List<RemoteQueryResponse>> token, float delay)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <ProcessResultsAfterSetDelay>d__5(0)
			{
				id = id,
				token = token,
				delay = delay
			};
		}

		[IteratorStateMachine(typeof(<ProcessResultsAfterSetResponses>d__6))]
		public static IEnumerator ProcessResultsAfterSetResponses(Guid id, TaskCompletionSource<List<RemoteQueryResponse>> token, int expectedResult, int delay)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <ProcessResultsAfterSetResponses>d__6(0)
			{
				id = id,
				token = token,
				expectedResult = expectedResult,
				delay = delay
			};
		}
	}

	public static class Scripts
	{
		public class Script
		{
			public string use { get; set; }

			public string gm { get; set; }

			public string instigator { get; set; }

			public string target { get; set; }

			public string others { get; set; }

			public string instigator_speech { get; set; }

			public string target_speech { get; set; }
		}

		public enum ExtensionType
		{
			instigatorSkillResult = 1,
			targetSkillResult,
			damageResult
		}

		public class ToggleCallaback
		{
			public ToggleRequired toggleOnWho { get; set; }

			public string toggleName { get; set; }

			public Func<CreatureBoardAsset, CreatureBoardAsset, Characters.CharacterSpecs, Characters.CharacterSpecs, Characters.Spec, string, Characters.Spec, DiceRoller.RollResult, Task<DiceRoller.RollResult>> callback { get; set; }
		}

		public enum ToggleRequired
		{
			instigator,
			target
		}

		public enum MessagePublicity
		{
			publicMessage,
			semiPrivateMessage,
			privateMessage
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass11_0
		{
			public Task<DiceRoller.RollResult> extensionTask;

			internal bool <ProcessExtensions>b__0()
			{
				return extensionTask.IsCompleted;
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass12_0
		{
			public Task<List<RemoteQueryResponse>> queryTask;

			internal bool <QueryRemotes>b__0()
			{
				return queryTask.IsCompleted;
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass13_0
		{
			public Task<List<RemoteQueryResponse>> queryTask;

			internal bool <QueryRemotesForDamage>b__0()
			{
				return queryTask.IsCompleted;
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass14_0
		{
			public Task<DiceRoller.RollResult> rollTask;

			internal bool <RollDice>b__0()
			{
				return rollTask.IsCompleted;
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass15_0
		{
			public CreatureBoardAsset instigator;
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass15_1
		{
			public CreatureBoardAsset target;

			public <>c__DisplayClass15_0 CS$<>8__locals1;
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass15_2
		{
			public string item;

			public string menu;

			public <>c__DisplayClass15_1 CS$<>8__locals2;

			internal void <ProcessSequence>b__0(string chainItem, string chainMenu, Characters.CharacterSpecs chainInstigatorSheet, CreatureBoardAsset chaininstigator, CreatureBoardAsset chainTarget)
			{
				Characters.InitiateMenuAction(item, menu, (CreatureBoardAsset[])(object)new CreatureBoardAsset[1] { CS$<>8__locals2.CS$<>8__locals1.instigator }, (CreatureBoardAsset[])(object)new CreatureBoardAsset[1] { CS$<>8__locals2.target });
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass15_3
		{
			public string item;

			public string menu;

			public <>c__DisplayClass15_1 CS$<>8__locals3;

			internal void <ProcessSequence>b__1(string chainItem, string chainMenu, Characters.CharacterSpecs chainInstigatorSheet, CreatureBoardAsset chaininstigator, CreatureBoardAsset chainTarget)
			{
				Characters.InitiateMenuAction(item, menu, (CreatureBoardAsset[])(object)new CreatureBoardAsset[1] { CS$<>8__locals3.CS$<>8__locals1.instigator }, (CreatureBoardAsset[])(object)new CreatureBoardAsset[1] { CS$<>8__locals3.target });
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass15_4
		{
			public string item;

			public string menu;

			public <>c__DisplayClass15_1 CS$<>8__locals4;

			internal void <ProcessSequence>b__2(string chainItem, string chainMenu, Characters.CharacterSpecs chainInstigatorSheet, CreatureBoardAsset chaininstigator, CreatureBoardAsset chainTarget)
			{
				Characters.InitiateMenuAction(item, menu, (CreatureBoardAsset[])(object)new CreatureBoardAsset[1] { CS$<>8__locals4.CS$<>8__locals1.instigator }, (CreatureBoardAsset[])(object)new CreatureBoardAsset[1] { CS$<>8__locals4.target });
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass16_0
		{
			public DiceRoller.RollResult rollResult;

			internal void <ProcessInstigatorRoll>b__0(DiceRoller.RollResult r)
			{
				rollResult = r;
			}

			internal void <ProcessInstigatorRoll>b__1(DiceRoller.RollResult r)
			{
				rollResult = r;
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass17_0
		{
			public DiceRoller.RollResult opposedRoll;

			internal void <ProcessTargetRoll>b__0(DiceRoller.RollResult r)
			{
				opposedRoll = r;
			}

			internal void <ProcessTargetRoll>b__1(DiceRoller.RollResult r)
			{
				opposedRoll = r;
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass18_0
		{
			public string adjustor;

			public DiceRoller.RollResult damage;

			internal void <ProcessDamageOnTarget>b__0(string r)
			{
				adjustor = r;
			}

			internal void <ProcessDamageOnTarget>b__1(DiceRoller.RollResult r)
			{
				damage = r;
			}

			internal void <ProcessDamageOnTarget>b__2(DiceRoller.RollResult r)
			{
				damage = r;
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass20_0
		{
			public DiceRoller.RollResult heal;

			internal void <ProcessHealOnTarget>b__0(DiceRoller.RollResult r)
			{
				heal = r;
			}
		}

		[CompilerGenerated]
		private sealed class <AnimateAttack>d__22 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public Characters.Spec check;

			public CreatureBoardAsset instigator;

			public CreatureBoardAsset target;

			public bool firstTarget;

			public bool success;

			private float <distance>5__1;

			private string <anim>5__2;

			private AttackEmotes <animEmote>5__3;

			private Transform <hook>5__4;

			private Projectile <projectile>5__5;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <AnimateAttack>d__22(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<anim>5__2 = null;
				<hook>5__4 = null;
				<projectile>5__5 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0050: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
				//IL_0197: Unknown result type (might be due to invalid IL or missing references)
				//IL_019c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0257: Unknown result type (might be due to invalid IL or missing references)
				//IL_035b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0360: Unknown result type (might be due to invalid IL or missing references)
				//IL_036a: Expected O, but got Unknown
				//IL_0378: Unknown result type (might be due to invalid IL or missing references)
				//IL_037d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0387: Expected O, but got Unknown
				//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
				//IL_02bc: Unknown result type (might be due to invalid IL or missing references)
				//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
				//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
				//IL_02d7: Unknown result type (might be due to invalid IL or missing references)
				if (<>1__state != 0)
				{
					return false;
				}
				<>1__state = -1;
				if (useAnimations.Value)
				{
					<distance>5__1 = (int)Math.Floor(Vector3.Distance(((Component)((MovableBoardAsset)instigator).Rotator).transform.position, ((Component)((MovableBoardAsset)target).Rotator).transform.position) * 5f);
					if (!success)
					{
						LoggingPlugin.LogDebug("Miss: Doing Wiggle Animation");
						target.PlayEmote(missAnimation.Value.ToString());
					}
					else
					{
						<anim>5__2 = check.Extra("animOnce");
						LoggingPlugin.LogDebug("Target " + (firstTarget ? "is" : "is not") + " first target. AnimOnce is " + ((<anim>5__2 == null) ? "Null" : <anim>5__2));
						if (<anim>5__2 != null && !firstTarget)
						{
							LoggingPlugin.LogDebug("AnimOnce set but this not the first target. Supressing animation.");
							<anim>5__2 = "";
						}
						if (<anim>5__2 == null)
						{
							LoggingPlugin.LogDebug("AnimOnce not set. Checking Anim.");
							<anim>5__2 = check.Extra("anim");
						}
						if (<anim>5__2 == null)
						{
							LoggingPlugin.LogDebug("Anim not set. Using defaut.");
							AttackEmotes value;
							string? text;
							if (!(<distance>5__1 < 10f))
							{
								value = hitRangedAnimation.Value;
								text = ((object)(AttackEmotes)(ref value)).ToString();
							}
							else
							{
								value = hitMeleeAnimation.Value;
								text = ((object)(AttackEmotes)(ref value)).ToString();
							}
							<anim>5__2 = text;
						}
						if (<anim>5__2 != null && <anim>5__2 != "")
						{
							LoggingPlugin.LogDebug(instigator.Name + " and " + target.Name + " Are " + <distance>5__1 + "' Apart. Doing A " + <anim>5__2 + " Animation");
							<animEmote>5__3 = (AttackEmotes)0;
							if (Enum.TryParse

plugins/Newtonsoft.Json.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Linq.JsonPath;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Schema, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cbd8d53b9d7de30f1f1278f636ec462cf9c254991291e66ebb157a885638a517887633b898ccbcf0d5c5ff7be85a6abe9e765d0ac7cd33c68dac67e7e64530e8222101109f154ab14a941c490ac155cd1d4fcba0fabb49016b4ef28593b015cab5937da31172f03f67d09edda404b88a60023f062ae71d0b2e4438b74cc11dc9")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("9ca358aa-317b-4925-8ada-4a29e943a363")]
[assembly: CLSCompliant(true)]
[assembly: TargetFramework(".NETFramework,Version=v4.5", FrameworkDisplayName = ".NET Framework 4.5")]
[assembly: AssemblyCompany("Newtonsoft")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © James Newton-King 2008")]
[assembly: AssemblyDescription("Json.NET is a popular high-performance JSON framework for .NET")]
[assembly: AssemblyFileVersion("13.0.4.30916")]
[assembly: AssemblyInformationalVersion("13.0.4+4e13299d4b0ec96bd4df9954ef646bd2d1b5bf2a")]
[assembly: AssemblyProduct("Json.NET")]
[assembly: AssemblyTitle("Json.NET .NET 4.5")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/JamesNK/Newtonsoft.Json")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("13.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)]
	internal sealed class DynamicallyAccessedMembersAttribute : Attribute
	{
		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)
		{
			MemberTypes = memberTypes;
		}
	}
	[Flags]
	internal enum DynamicallyAccessedMemberTypes
	{
		None = 0,
		PublicParameterlessConstructor = 1,
		PublicConstructors = 3,
		NonPublicConstructors = 4,
		PublicMethods = 8,
		NonPublicMethods = 0x10,
		PublicFields = 0x20,
		NonPublicFields = 0x40,
		PublicNestedTypes = 0x80,
		NonPublicNestedTypes = 0x100,
		PublicProperties = 0x200,
		NonPublicProperties = 0x400,
		PublicEvents = 0x800,
		NonPublicEvents = 0x1000,
		Interfaces = 0x2000,
		All = -1
	}
	[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class FeatureGuardAttribute : Attribute
	{
		public Type FeatureType { get; }

		public FeatureGuardAttribute(Type featureType)
		{
			FeatureType = featureType;
		}
	}
	[AttributeUsage(AttributeTargets.Property, Inherited = false)]
	internal sealed class FeatureSwitchDefinitionAttribute : Attribute
	{
		public string SwitchName { get; }

		public FeatureSwitchDefinitionAttribute(string switchName)
		{
			SwitchName = switchName;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresDynamicCodeAttribute : Attribute
	{
		public string Message { get; }

		public string? Url { get; set; }

		public RequiresDynamicCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresUnreferencedCodeAttribute : Attribute
	{
		public string Message { get; }

		public string? Url { get; set; }

		public RequiresUnreferencedCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
	internal sealed class UnconditionalSuppressMessageAttribute : Attribute
	{
		public string Category { get; }

		public string CheckId { get; }

		public string? Scope { get; set; }

		public string? Target { get; set; }

		public string? MessageId { get; set; }

		public string? Justification { get; set; }

		public UnconditionalSuppressMessageAttribute(string category, string checkId)
		{
			Category = category;
			CheckId = checkId;
		}
	}
}
namespace Newtonsoft.Json
{
	public enum ConstructorHandling
	{
		Default,
		AllowNonPublicDefaultConstructor
	}
	public enum DateFormatHandling
	{
		IsoDateFormat,
		MicrosoftDateFormat
	}
	public enum DateParseHandling
	{
		None,
		DateTime,
		DateTimeOffset
	}
	public enum DateTimeZoneHandling
	{
		Local,
		Utc,
		Unspecified,
		RoundtripKind
	}
	public class DefaultJsonNameTable : JsonNameTable
	{
		private class Entry
		{
			internal readonly string Value;

			internal readonly int HashCode;

			internal Entry Next;

			internal Entry(string value, int hashCode, Entry next)
			{
				Value = value;
				HashCode = hashCode;
				Next = next;
			}
		}

		private static readonly int HashCodeRandomizer;

		private int _count;

		private Entry[] _entries;

		private int _mask = 31;

		static DefaultJsonNameTable()
		{
			HashCodeRandomizer = Environment.TickCount;
		}

		public DefaultJsonNameTable()
		{
			_entries = new Entry[_mask + 1];
		}

		public override string? Get(char[] key, int start, int length)
		{
			if (length == 0)
			{
				return string.Empty;
			}
			int num = length + HashCodeRandomizer;
			num += (num << 7) ^ key[start];
			int num2 = start + length;
			for (int i = start + 1; i < num2; i++)
			{
				num += (num << 7) ^ key[i];
			}
			num -= num >> 17;
			num -= num >> 11;
			num -= num >> 5;
			int num3 = Volatile.Read(ref _mask);
			int num4 = num & num3;
			for (Entry entry = _entries[num4]; entry != null; entry = entry.Next)
			{
				if (entry.HashCode == num && TextEquals(entry.Value, key, start, length))
				{
					return entry.Value;
				}
			}
			return null;
		}

		public string Add(string key)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			int length = key.Length;
			if (length == 0)
			{
				return string.Empty;
			}
			int num = length + HashCodeRandomizer;
			for (int i = 0; i < key.Length; i++)
			{
				num += (num << 7) ^ key[i];
			}
			num -= num >> 17;
			num -= num >> 11;
			num -= num >> 5;
			for (Entry entry = _entries[num & _mask]; entry != null; entry = entry.Next)
			{
				if (entry.HashCode == num && entry.Value.Equals(key, StringComparison.Ordinal))
				{
					return entry.Value;
				}
			}
			return AddEntry(key, num);
		}

		private string AddEntry(string str, int hashCode)
		{
			int num = hashCode & _mask;
			Entry entry = new Entry(str, hashCode, _entries[num]);
			_entries[num] = entry;
			if (_count++ == _mask)
			{
				Grow();
			}
			return entry.Value;
		}

		private void Grow()
		{
			Entry[] entries = _entries;
			int num = _mask * 2 + 1;
			Entry[] array = new Entry[num + 1];
			for (int i = 0; i < entries.Length; i++)
			{
				Entry entry = entries[i];
				while (entry != null)
				{
					int num2 = entry.HashCode & num;
					Entry next = entry.Next;
					entry.Next = array[num2];
					array[num2] = entry;
					entry = next;
				}
			}
			_entries = array;
			Volatile.Write(ref _mask, num);
		}

		private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length)
		{
			if (str1.Length != str2Length)
			{
				return false;
			}
			for (int i = 0; i < str1.Length; i++)
			{
				if (str1[i] != str2[str2Start + i])
				{
					return false;
				}
			}
			return true;
		}
	}
	[Flags]
	public enum DefaultValueHandling
	{
		Include = 0,
		Ignore = 1,
		Populate = 2,
		IgnoreAndPopulate = 3
	}
	public enum FloatFormatHandling
	{
		String,
		Symbol,
		DefaultValue
	}
	public enum FloatParseHandling
	{
		Double,
		Decimal
	}
	public enum Formatting
	{
		None,
		Indented
	}
	public interface IArrayPool<T>
	{
		T[] Rent(int minimumLength);

		void Return(T[]? array);
	}
	public interface IJsonLineInfo
	{
		int LineNumber { get; }

		int LinePosition { get; }

		bool HasLineInfo();
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
	public sealed class JsonArrayAttribute : JsonContainerAttribute
	{
		private bool _allowNullItems;

		public bool AllowNullItems
		{
			get
			{
				return _allowNullItems;
			}
			set
			{
				_allowNullItems = value;
			}
		}

		public JsonArrayAttribute()
		{
		}

		public JsonArrayAttribute(bool allowNullItems)
		{
			_allowNullItems = allowNullItems;
		}

		public JsonArrayAttribute(string id)
			: base(id)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)]
	public sealed class JsonConstructorAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
	public abstract class JsonContainerAttribute : Attribute
	{
		internal bool? _isReference;

		internal bool? _itemIsReference;

		internal ReferenceLoopHandling? _itemReferenceLoopHandling;

		internal TypeNameHandling? _itemTypeNameHandling;

		private Type? _namingStrategyType;

		private object[]? _namingStrategyParameters;

		public string? Id { get; set; }

		public string? Title { get; set; }

		public string? Description { get; set; }

		public Type? ItemConverterType { get; set; }

		public object[]? ItemConverterParameters { get; set; }

		public Type? NamingStrategyType
		{
			get
			{
				return _namingStrategyType;
			}
			set
			{
				_namingStrategyType = value;
				NamingStrategyInstance = null;
			}
		}

		public object[]? NamingStrategyParameters
		{
			get
			{
				return _namingStrategyParameters;
			}
			set
			{
				_namingStrategyParameters = value;
				NamingStrategyInstance = null;
			}
		}

		internal NamingStrategy? NamingStrategyInstance { get; set; }

		public bool IsReference
		{
			get
			{
				return _isReference.GetValueOrDefault();
			}
			set
			{
				_isReference = value;
			}
		}

		public bool ItemIsReference
		{
			get
			{
				return _itemIsReference.GetValueOrDefault();
			}
			set
			{
				_itemIsReference = value;
			}
		}

		public ReferenceLoopHandling ItemReferenceLoopHandling
		{
			get
			{
				return _itemReferenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_itemReferenceLoopHandling = value;
			}
		}

		public TypeNameHandling ItemTypeNameHandling
		{
			get
			{
				return _itemTypeNameHandling.GetValueOrDefault();
			}
			set
			{
				_itemTypeNameHandling = value;
			}
		}

		protected JsonContainerAttribute()
		{
		}

		protected JsonContainerAttribute(string id)
		{
			Id = id;
		}
	}
	public static class JsonConvert
	{
		public static readonly string True = "true";

		public static readonly string False = "false";

		public static readonly string Null = "null";

		public static readonly string Undefined = "undefined";

		public static readonly string PositiveInfinity = "Infinity";

		public static readonly string NegativeInfinity = "-Infinity";

		public static readonly string NaN = "NaN";

		public static Func<JsonSerializerSettings>? DefaultSettings { get; set; }

		public static string ToString(DateTime value)
		{
			return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
		}

		public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
		{
			DateTime value2 = DateTimeUtils.EnsureDateTime(value, timeZoneHandling);
			using StringWriter stringWriter = StringUtils.CreateStringWriter(64);
			stringWriter.Write('"');
			DateTimeUtils.WriteDateTimeString(stringWriter, value2, format, null, CultureInfo.InvariantCulture);
			stringWriter.Write('"');
			return stringWriter.ToString();
		}

		public static string ToString(DateTimeOffset value)
		{
			return ToString(value, DateFormatHandling.IsoDateFormat);
		}

		public static string ToString(DateTimeOffset value, DateFormatHandling format)
		{
			using StringWriter stringWriter = StringUtils.CreateStringWriter(64);
			stringWriter.Write('"');
			DateTimeUtils.WriteDateTimeOffsetString(stringWriter, value, format, null, CultureInfo.InvariantCulture);
			stringWriter.Write('"');
			return stringWriter.ToString();
		}

		public static string ToString(bool value)
		{
			if (!value)
			{
				return False;
			}
			return True;
		}

		public static string ToString(char value)
		{
			return ToString(char.ToString(value));
		}

		public static string ToString(Enum value)
		{
			return value.ToString("D");
		}

		public static string ToString(int value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(short value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(ushort value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(uint value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(long value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		private static string ToStringInternal(BigInteger value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(ulong value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(float value)
		{
			return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
		}

		internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
		{
			return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
		}

		private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
		{
			if (floatFormatHandling == FloatFormatHandling.Symbol || (!double.IsInfinity(value) && !double.IsNaN(value)))
			{
				return text;
			}
			if (floatFormatHandling == FloatFormatHandling.DefaultValue)
			{
				if (nullable)
				{
					return Null;
				}
				return "0.0";
			}
			return quoteChar + text + quoteChar;
		}

		public static string ToString(double value)
		{
			return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
		}

		internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
		{
			return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
		}

		private static string EnsureDecimalPlace(double value, string text)
		{
			if (double.IsNaN(value) || double.IsInfinity(value) || StringUtils.IndexOf(text, '.') != -1 || StringUtils.IndexOf(text, 'E') != -1 || StringUtils.IndexOf(text, 'e') != -1)
			{
				return text;
			}
			return text + ".0";
		}

		private static string EnsureDecimalPlace(string text)
		{
			if (StringUtils.IndexOf(text, '.') != -1)
			{
				return text;
			}
			return text + ".0";
		}

		public static string ToString(byte value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(sbyte value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(decimal value)
		{
			return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
		}

		public static string ToString(Guid value)
		{
			return ToString(value, '"');
		}

		internal static string ToString(Guid value, char quoteChar)
		{
			string text = value.ToString("D", CultureInfo.InvariantCulture);
			string text2 = quoteChar.ToString(CultureInfo.InvariantCulture);
			return text2 + text + text2;
		}

		public static string ToString(TimeSpan value)
		{
			return ToString(value, '"');
		}

		internal static string ToString(TimeSpan value, char quoteChar)
		{
			return ToString(value.ToString(), quoteChar);
		}

		public static string ToString(Uri? value)
		{
			if (value == null)
			{
				return Null;
			}
			return ToString(value, '"');
		}

		internal static string ToString(Uri value, char quoteChar)
		{
			return ToString(value.OriginalString, quoteChar);
		}

		public static string ToString(string? value)
		{
			return ToString(value, '"');
		}

		public static string ToString(string? value, char delimiter)
		{
			return ToString(value, delimiter, StringEscapeHandling.Default);
		}

		public static string ToString(string? value, char delimiter, StringEscapeHandling stringEscapeHandling)
		{
			if (delimiter != '"' && delimiter != '\'')
			{
				throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter");
			}
			return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, appendDelimiters: true, stringEscapeHandling);
		}

		public static string ToString(object? value)
		{
			if (value == null)
			{
				return Null;
			}
			return ConvertUtils.GetTypeCode(value.GetType()) switch
			{
				PrimitiveTypeCode.String => ToString((string)value), 
				PrimitiveTypeCode.Char => ToString((char)value), 
				PrimitiveTypeCode.Boolean => ToString((bool)value), 
				PrimitiveTypeCode.SByte => ToString((sbyte)value), 
				PrimitiveTypeCode.Int16 => ToString((short)value), 
				PrimitiveTypeCode.UInt16 => ToString((ushort)value), 
				PrimitiveTypeCode.Int32 => ToString((int)value), 
				PrimitiveTypeCode.Byte => ToString((byte)value), 
				PrimitiveTypeCode.UInt32 => ToString((uint)value), 
				PrimitiveTypeCode.Int64 => ToString((long)value), 
				PrimitiveTypeCode.UInt64 => ToString((ulong)value), 
				PrimitiveTypeCode.Single => ToString((float)value), 
				PrimitiveTypeCode.Double => ToString((double)value), 
				PrimitiveTypeCode.DateTime => ToString((DateTime)value), 
				PrimitiveTypeCode.Decimal => ToString((decimal)value), 
				PrimitiveTypeCode.DBNull => Null, 
				PrimitiveTypeCode.DateTimeOffset => ToString((DateTimeOffset)value), 
				PrimitiveTypeCode.Guid => ToString((Guid)value), 
				PrimitiveTypeCode.Uri => ToString((Uri)value), 
				PrimitiveTypeCode.TimeSpan => ToString((TimeSpan)value), 
				PrimitiveTypeCode.BigInteger => ToStringInternal((BigInteger)value), 
				_ => throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())), 
			};
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value)
		{
			return SerializeObject(value, (Type?)null, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value, Formatting formatting)
		{
			return SerializeObject(value, formatting, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value, params JsonConverter[] converters)
		{
			JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings
			{
				Converters = converters
			} : null);
			return SerializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters)
		{
			JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings
			{
				Converters = converters
			} : null);
			return SerializeObject(value, null, formatting, settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value, JsonSerializerSettings? settings)
		{
			return SerializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			return SerializeObjectInternal(value, type, jsonSerializer);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings)
		{
			return SerializeObject(value, null, formatting, settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			jsonSerializer.Formatting = formatting;
			return SerializeObjectInternal(value, type, jsonSerializer);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer)
		{
			StringWriter stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture);
			using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter))
			{
				jsonTextWriter.Formatting = jsonSerializer.Formatting;
				jsonSerializer.Serialize(jsonTextWriter, value, type);
			}
			return stringWriter.ToString();
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static object? DeserializeObject(string value)
		{
			return DeserializeObject(value, (Type?)null, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static object? DeserializeObject(string value, JsonSerializerSettings settings)
		{
			return DeserializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static object? DeserializeObject(string value, Type type)
		{
			return DeserializeObject(value, type, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static T? DeserializeObject<T>(string value)
		{
			return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
		{
			return DeserializeObject<T>(value);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings)
		{
			return DeserializeObject<T>(value, settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static T? DeserializeObject<T>(string value, params JsonConverter[] converters)
		{
			return (T)DeserializeObject(value, typeof(T), converters);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings)
		{
			return (T)DeserializeObject(value, typeof(T), settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters)
		{
			JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings
			{
				Converters = converters
			} : null);
			return DeserializeObject(value, type, settings);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings)
		{
			ValidationUtils.ArgumentNotNull(value, "value");
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			if (!jsonSerializer.IsCheckAdditionalContentSet())
			{
				jsonSerializer.CheckAdditionalContent = true;
			}
			using JsonTextReader reader = new JsonTextReader(new StringReader(value));
			return jsonSerializer.Deserialize(reader, type);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static void PopulateObject(string value, object target)
		{
			PopulateObject(value, target, null);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static void PopulateObject(string value, object target, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			using JsonReader jsonReader = new JsonTextReader(new StringReader(value));
			jsonSerializer.Populate(jsonReader, target);
			if (settings == null || !settings.CheckAdditionalContent)
			{
				return;
			}
			while (jsonReader.Read())
			{
				if (jsonReader.TokenType != JsonToken.Comment)
				{
					throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object.");
				}
			}
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeXmlNode(XmlNode? node)
		{
			return SerializeXmlNode(node, Formatting.None);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeXmlNode(XmlNode? node, Formatting formatting)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter();
			return SerializeObject(node, formatting, xmlNodeConverter);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter
			{
				OmitRootObject = omitRootObject
			};
			return SerializeObject(node, formatting, xmlNodeConverter);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XmlDocument? DeserializeXmlNode(string value)
		{
			return DeserializeXmlNode(value, null);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName)
		{
			return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute: false);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute)
		{
			return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter();
			xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName;
			xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute;
			xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters;
			return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), xmlNodeConverter);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeXNode(XObject? node)
		{
			return SerializeXNode(node, Formatting.None);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeXNode(XObject? node, Formatting formatting)
		{
			return SerializeXNode(node, formatting, omitRootObject: false);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter
			{
				OmitRootObject = omitRootObject
			};
			return SerializeObject(node, formatting, xmlNodeConverter);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XDocument? DeserializeXNode(string value)
		{
			return DeserializeXNode(value, null);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName)
		{
			return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute: false);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute)
		{
			return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter();
			xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName;
			xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute;
			xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters;
			return (XDocument)DeserializeObject(value, typeof(XDocument), xmlNodeConverter);
		}
	}
	public abstract class JsonConverter
	{
		public virtual bool CanRead => true;

		public virtual bool CanWrite => true;

		public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer);

		public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer);

		public abstract bool CanConvert(Type objectType);
	}
	public abstract class JsonConverter<T> : JsonConverter
	{
		public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
		{
			if (!((value != null) ? (value is T) : ReflectionUtils.IsNullable(typeof(T))))
			{
				throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));
			}
			WriteJson(writer, (T)value, serializer);
		}

		public abstract void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer);

		public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
		{
			bool flag = existingValue == null;
			if (!flag && !(existingValue is T))
			{
				throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));
			}
			return ReadJson(reader, objectType, flag ? default(T) : ((T)existingValue), !flag, serializer);
		}

		public abstract T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer);

		public sealed override bool CanConvert(Type objectType)
		{
			return typeof(T).IsAssignableFrom(objectType);
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class JsonConverterAttribute : Attribute
	{
		private readonly Type _converterType;

		public Type ConverterType => _converterType;

		public object[]? ConverterParameters { get; }

		public JsonConverterAttribute(Type converterType)
		{
			if (converterType == null)
			{
				throw new ArgumentNullException("converterType");
			}
			_converterType = converterType;
		}

		public JsonConverterAttribute(Type converterType, params object[] converterParameters)
			: this(converterType)
		{
			ConverterParameters = converterParameters;
		}
	}
	public class JsonConverterCollection : Collection<JsonConverter>
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
	public sealed class JsonDictionaryAttribute : JsonContainerAttribute
	{
		public JsonDictionaryAttribute()
		{
		}

		public JsonDictionaryAttribute(string id)
			: base(id)
		{
		}
	}
	[Serializable]
	public class JsonException : Exception
	{
		public JsonException()
		{
		}

		public JsonException(string message)
			: base(message)
		{
		}

		public JsonException(string message, Exception? innerException)
			: base(message, innerException)
		{
		}

		public JsonException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message)
		{
			message = JsonPosition.FormatMessage(lineInfo, path, message);
			return new JsonException(message);
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public class JsonExtensionDataAttribute : Attribute
	{
		public bool WriteData { get; set; }

		public bool ReadData { get; set; }

		public JsonExtensionDataAttribute()
		{
			WriteData = true;
			ReadData = true;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public sealed class JsonIgnoreAttribute : Attribute
	{
	}
	public abstract class JsonNameTable
	{
		public abstract string? Get(char[] key, int start, int length);
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)]
	public sealed class JsonObjectAttribute : JsonContainerAttribute
	{
		private MemberSerialization _memberSerialization;

		internal MissingMemberHandling? _missingMemberHandling;

		internal Required? _itemRequired;

		internal NullValueHandling? _itemNullValueHandling;

		public MemberSerialization MemberSerialization
		{
			get
			{
				return _memberSerialization;
			}
			set
			{
				_memberSerialization = value;
			}
		}

		public MissingMemberHandling MissingMemberHandling
		{
			get
			{
				return _missingMemberHandling.GetValueOrDefault();
			}
			set
			{
				_missingMemberHandling = value;
			}
		}

		public NullValueHandling ItemNullValueHandling
		{
			get
			{
				return _itemNullValueHandling.GetValueOrDefault();
			}
			set
			{
				_itemNullValueHandling = value;
			}
		}

		public Required ItemRequired
		{
			get
			{
				return _itemRequired.GetValueOrDefault();
			}
			set
			{
				_itemRequired = value;
			}
		}

		public JsonObjectAttribute()
		{
		}

		public JsonObjectAttribute(MemberSerialization memberSerialization)
		{
			MemberSerialization = memberSerialization;
		}

		public JsonObjectAttribute(string id)
			: base(id)
		{
		}
	}
	internal enum JsonContainerType
	{
		None,
		Object,
		Array,
		Constructor
	}
	internal struct JsonPosition
	{
		private static readonly char[] SpecialCharacters = new char[18]
		{
			'.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t',
			'\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029'
		};

		internal JsonContainerType Type;

		internal int Position;

		internal string? PropertyName;

		internal bool HasIndex;

		public JsonPosition(JsonContainerType type)
		{
			Type = type;
			HasIndex = TypeHasIndex(type);
			Position = -1;
			PropertyName = null;
		}

		internal int CalculateLength()
		{
			switch (Type)
			{
			case JsonContainerType.Object:
				return PropertyName.Length + 5;
			case JsonContainerType.Array:
			case JsonContainerType.Constructor:
				return MathUtils.IntLength((ulong)Position) + 2;
			default:
				throw new ArgumentOutOfRangeException("Type");
			}
		}

		internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer)
		{
			switch (Type)
			{
			case JsonContainerType.Object:
			{
				string propertyName = PropertyName;
				if (propertyName.IndexOfAny(SpecialCharacters) != -1)
				{
					sb.Append("['");
					if (writer == null)
					{
						writer = new StringWriter(sb);
					}
					JavaScriptUtils.WriteEscapedJavaScriptString(writer, propertyName, '\'', appendDelimiters: false, JavaScriptUtils.SingleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer);
					sb.Append("']");
				}
				else
				{
					if (sb.Length > 0)
					{
						sb.Append('.');
					}
					sb.Append(propertyName);
				}
				break;
			}
			case JsonContainerType.Array:
			case JsonContainerType.Constructor:
				sb.Append('[');
				sb.Append(Position);
				sb.Append(']');
				break;
			}
		}

		internal static bool TypeHasIndex(JsonContainerType type)
		{
			if (type != JsonContainerType.Array)
			{
				return type == JsonContainerType.Constructor;
			}
			return true;
		}

		internal static string BuildPath(List<JsonPosition> positions, JsonPosition? currentPosition)
		{
			int num = 0;
			if (positions != null)
			{
				for (int i = 0; i < positions.Count; i++)
				{
					num += positions[i].CalculateLength();
				}
			}
			if (currentPosition.HasValue)
			{
				num += currentPosition.GetValueOrDefault().CalculateLength();
			}
			StringBuilder stringBuilder = new StringBuilder(num);
			StringWriter writer = null;
			char[] buffer = null;
			if (positions != null)
			{
				foreach (JsonPosition position in positions)
				{
					position.WriteTo(stringBuilder, ref writer, ref buffer);
				}
			}
			currentPosition?.WriteTo(stringBuilder, ref writer, ref buffer);
			return stringBuilder.ToString();
		}

		internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message)
		{
			if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal))
			{
				message = message.Trim();
				if (!StringUtils.EndsWith(message, '.'))
				{
					message += ".";
				}
				message += " ";
			}
			message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path);
			if (lineInfo != null && lineInfo.HasLineInfo())
			{
				message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition);
			}
			message += ".";
			return message;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class JsonPropertyAttribute : Attribute
	{
		internal NullValueHandling? _nullValueHandling;

		internal DefaultValueHandling? _defaultValueHandling;

		internal ReferenceLoopHandling? _referenceLoopHandling;

		internal ObjectCreationHandling? _objectCreationHandling;

		internal TypeNameHandling? _typeNameHandling;

		internal bool? _isReference;

		internal int? _order;

		internal Required? _required;

		internal bool? _itemIsReference;

		internal ReferenceLoopHandling? _itemReferenceLoopHandling;

		internal TypeNameHandling? _itemTypeNameHandling;

		public Type? ItemConverterType { get; set; }

		public object[]? ItemConverterParameters { get; set; }

		public Type? NamingStrategyType { get; set; }

		public object[]? NamingStrategyParameters { get; set; }

		public NullValueHandling NullValueHandling
		{
			get
			{
				return _nullValueHandling.GetValueOrDefault();
			}
			set
			{
				_nullValueHandling = value;
			}
		}

		public DefaultValueHandling DefaultValueHandling
		{
			get
			{
				return _defaultValueHandling.GetValueOrDefault();
			}
			set
			{
				_defaultValueHandling = value;
			}
		}

		public ReferenceLoopHandling ReferenceLoopHandling
		{
			get
			{
				return _referenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_referenceLoopHandling = value;
			}
		}

		public ObjectCreationHandling ObjectCreationHandling
		{
			get
			{
				return _objectCreationHandling.GetValueOrDefault();
			}
			set
			{
				_objectCreationHandling = value;
			}
		}

		public TypeNameHandling TypeNameHandling
		{
			get
			{
				return _typeNameHandling.GetValueOrDefault();
			}
			set
			{
				_typeNameHandling = value;
			}
		}

		public bool IsReference
		{
			get
			{
				return _isReference.GetValueOrDefault();
			}
			set
			{
				_isReference = value;
			}
		}

		public int Order
		{
			get
			{
				return _order.GetValueOrDefault();
			}
			set
			{
				_order = value;
			}
		}

		public Required Required
		{
			get
			{
				return _required.GetValueOrDefault();
			}
			set
			{
				_required = value;
			}
		}

		public string? PropertyName { get; set; }

		public ReferenceLoopHandling ItemReferenceLoopHandling
		{
			get
			{
				return _itemReferenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_itemReferenceLoopHandling = value;
			}
		}

		public TypeNameHandling ItemTypeNameHandling
		{
			get
			{
				return _itemTypeNameHandling.GetValueOrDefault();
			}
			set
			{
				_itemTypeNameHandling = value;
			}
		}

		public bool ItemIsReference
		{
			get
			{
				return _itemIsReference.GetValueOrDefault();
			}
			set
			{
				_itemIsReference = value;
			}
		}

		public JsonPropertyAttribute()
		{
		}

		public JsonPropertyAttribute(string propertyName)
		{
			PropertyName = propertyName;
		}
	}
	public abstract class JsonReader : IDisposable
	{
		protected internal enum State
		{
			Start,
			Complete,
			Property,
			ObjectStart,
			Object,
			ArrayStart,
			Array,
			Closed,
			PostValue,
			ConstructorStart,
			Constructor,
			Error,
			Finished
		}

		private JsonToken _tokenType;

		private object? _value;

		internal char _quoteChar;

		internal State _currentState;

		private JsonPosition _currentPosition;

		private CultureInfo? _culture;

		private DateTimeZoneHandling _dateTimeZoneHandling;

		private int? _maxDepth;

		private bool _hasExceededMaxDepth;

		internal DateParseHandling _dateParseHandling;

		internal FloatParseHandling _floatParseHandling;

		private string? _dateFormatString;

		private List<JsonPosition>? _stack;

		protected State CurrentState => _currentState;

		public bool CloseInput { get; set; }

		public bool SupportMultipleContent { get; set; }

		public virtual char QuoteChar
		{
			get
			{
				return _quoteChar;
			}
			protected internal set
			{
				_quoteChar = value;
			}
		}

		public DateTimeZoneHandling DateTimeZoneHandling
		{
			get
			{
				return _dateTimeZoneHandling;
			}
			set
			{
				if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_dateTimeZoneHandling = value;
			}
		}

		public DateParseHandling DateParseHandling
		{
			get
			{
				return _dateParseHandling;
			}
			set
			{
				if (value < DateParseHandling.None || value > DateParseHandling.DateTimeOffset)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_dateParseHandling = value;
			}
		}

		public FloatParseHandling FloatParseHandling
		{
			get
			{
				return _floatParseHandling;
			}
			set
			{
				if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_floatParseHandling = value;
			}
		}

		public string? DateFormatString
		{
			get
			{
				return _dateFormatString;
			}
			set
			{
				_dateFormatString = value;
			}
		}

		public int? MaxDepth
		{
			get
			{
				return _maxDepth;
			}
			set
			{
				if (value <= 0)
				{
					throw new ArgumentException("Value must be positive.", "value");
				}
				_maxDepth = value;
			}
		}

		public virtual JsonToken TokenType => _tokenType;

		public virtual object? Value => _value;

		public virtual Type? ValueType => _value?.GetType();

		public virtual int Depth
		{
			get
			{
				int num = _stack?.Count ?? 0;
				if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
				{
					return num;
				}
				return num + 1;
			}
		}

		public virtual string Path
		{
			get
			{
				if (_currentPosition.Type == JsonContainerType.None)
				{
					return string.Empty;
				}
				JsonPosition? currentPosition = ((_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart) ? new JsonPosition?(_currentPosition) : null);
				return JsonPosition.BuildPath(_stack, currentPosition);
			}
		}

		public CultureInfo Culture
		{
			get
			{
				return _culture ?? CultureInfo.InvariantCulture;
			}
			set
			{
				_culture = value;
			}
		}

		public virtual Task<bool> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<bool>() ?? Read().ToAsync();
		}

		public async Task SkipAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			if (TokenType == JsonToken.PropertyName)
			{
				await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			if (JsonTokenUtils.IsStartToken(TokenType))
			{
				int depth = Depth;
				while (await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false) && depth < Depth)
				{
				}
			}
		}

		internal async Task ReaderReadAndAssertAsync(CancellationToken cancellationToken)
		{
			if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
			{
				throw CreateUnexpectedEndException();
			}
		}

		public virtual Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<bool?>() ?? Task.FromResult(ReadAsBoolean());
		}

		public virtual Task<byte[]?> ReadAsBytesAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<byte[]>() ?? Task.FromResult(ReadAsBytes());
		}

		internal async Task<byte[]?> ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken)
		{
			List<byte> buffer = new List<byte>();
			do
			{
				if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
				{
					SetToken(JsonToken.None);
				}
			}
			while (!ReadArrayElementIntoByteArrayReportDone(buffer));
			byte[] array = buffer.ToArray();
			SetToken(JsonToken.Bytes, array, updateIndex: false);
			return array;
		}

		public virtual Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<DateTime?>() ?? Task.FromResult(ReadAsDateTime());
		}

		public virtual Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<DateTimeOffset?>() ?? Task.FromResult(ReadAsDateTimeOffset());
		}

		public virtual Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<decimal?>() ?? Task.FromResult(ReadAsDecimal());
		}

		public virtual Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return Task.FromResult(ReadAsDouble());
		}

		public virtual Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<int?>() ?? Task.FromResult(ReadAsInt32());
		}

		public virtual Task<string?> ReadAsStringAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<string>() ?? Task.FromResult(ReadAsString());
		}

		internal async Task<bool> ReadAndMoveToContentAsync(CancellationToken cancellationToken)
		{
			bool flag = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			if (flag)
			{
				flag = await MoveToContentAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			return flag;
		}

		internal Task<bool> MoveToContentAsync(CancellationToken cancellationToken)
		{
			JsonToken tokenType = TokenType;
			if (tokenType == JsonToken.None || tokenType == JsonToken.Comment)
			{
				return MoveToContentFromNonContentAsync(cancellationToken);
			}
			return AsyncUtils.True;
		}

		private async Task<bool> MoveToContentFromNonContentAsync(CancellationToken cancellationToken)
		{
			JsonToken tokenType;
			do
			{
				if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
				{
					return false;
				}
				tokenType = TokenType;
			}
			while (tokenType == JsonToken.None || tokenType == JsonToken.Comment);
			return true;
		}

		internal JsonPosition GetPosition(int depth)
		{
			if (_stack != null && depth < _stack.Count)
			{
				return _stack[depth];
			}
			return _currentPosition;
		}

		protected JsonReader()
		{
			_currentState = State.Start;
			_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
			_dateParseHandling = DateParseHandling.DateTime;
			_floatParseHandling = FloatParseHandling.Double;
			_maxDepth = 64;
			CloseInput = true;
		}

		private void Push(JsonContainerType value)
		{
			UpdateScopeWithFinishedValue();
			if (_currentPosition.Type == JsonContainerType.None)
			{
				_currentPosition = new JsonPosition(value);
				return;
			}
			if (_stack == null)
			{
				_stack = new List<JsonPosition>();
			}
			_stack.Add(_currentPosition);
			_currentPosition = new JsonPosition(value);
			if (!_maxDepth.HasValue || !(Depth + 1 > _maxDepth) || _hasExceededMaxDepth)
			{
				return;
			}
			_hasExceededMaxDepth = true;
			throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth));
		}

		private JsonContainerType Pop()
		{
			JsonPosition currentPosition;
			if (_stack != null && _stack.Count > 0)
			{
				currentPosition = _currentPosition;
				_currentPosition = _stack[_stack.Count - 1];
				_stack.RemoveAt(_stack.Count - 1);
			}
			else
			{
				currentPosition = _currentPosition;
				_currentPosition = default(JsonPosition);
			}
			if (_maxDepth.HasValue && Depth <= _maxDepth)
			{
				_hasExceededMaxDepth = false;
			}
			return currentPosition.Type;
		}

		private JsonContainerType Peek()
		{
			return _currentPosition.Type;
		}

		public abstract bool Read();

		public virtual int? ReadAsInt32()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				object value = Value;
				if (value is int)
				{
					return (int)value;
				}
				int num;
				if (value is BigInteger bigInteger)
				{
					num = (int)bigInteger;
				}
				else
				{
					try
					{
						num = Convert.ToInt32(value, CultureInfo.InvariantCulture);
					}
					catch (Exception ex)
					{
						throw JsonReaderException.Create(this, "Could not convert to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex);
					}
				}
				SetToken(JsonToken.Integer, num, updateIndex: false);
				return num;
			}
			case JsonToken.String:
			{
				string s = (string)Value;
				return ReadInt32String(s);
			}
			default:
				throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal int? ReadInt32String(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (int.TryParse(s, NumberStyles.Integer, Culture, out var result))
			{
				SetToken(JsonToken.Integer, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual string? ReadAsString()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.String:
				return (string)Value;
			default:
				if (JsonTokenUtils.IsPrimitiveToken(contentToken))
				{
					object value = Value;
					if (value != null)
					{
						string text = ((!(value is IFormattable formattable)) ? ((value is Uri uri) ? uri.OriginalString : value.ToString()) : formattable.ToString(null, Culture));
						SetToken(JsonToken.String, text, updateIndex: false);
						return text;
					}
				}
				throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		public virtual byte[]? ReadAsBytes()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.StartObject:
			{
				ReadIntoWrappedTypeObject();
				byte[] array2 = ReadAsBytes();
				ReaderReadAndAssert();
				if (TokenType != JsonToken.EndObject)
				{
					throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
				}
				SetToken(JsonToken.Bytes, array2, updateIndex: false);
				return array2;
			}
			case JsonToken.String:
			{
				string text = (string)Value;
				Guid g;
				byte[] array3 = ((text.Length == 0) ? CollectionUtils.ArrayEmpty<byte>() : ((!ConvertUtils.TryConvertGuid(text, out g)) ? Convert.FromBase64String(text) : g.ToByteArray()));
				SetToken(JsonToken.Bytes, array3, updateIndex: false);
				return array3;
			}
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Bytes:
				if (Value is Guid guid)
				{
					byte[] array = guid.ToByteArray();
					SetToken(JsonToken.Bytes, array, updateIndex: false);
					return array;
				}
				return (byte[])Value;
			case JsonToken.StartArray:
				return ReadArrayIntoByteArray();
			default:
				throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal byte[] ReadArrayIntoByteArray()
		{
			List<byte> list = new List<byte>();
			do
			{
				if (!Read())
				{
					SetToken(JsonToken.None);
				}
			}
			while (!ReadArrayElementIntoByteArrayReportDone(list));
			byte[] array = list.ToArray();
			SetToken(JsonToken.Bytes, array, updateIndex: false);
			return array;
		}

		private bool ReadArrayElementIntoByteArrayReportDone(List<byte> buffer)
		{
			switch (TokenType)
			{
			case JsonToken.None:
				throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
			case JsonToken.Integer:
				buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture));
				return false;
			case JsonToken.EndArray:
				return true;
			case JsonToken.Comment:
				return false;
			default:
				throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
			}
		}

		public virtual double? ReadAsDouble()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				object value = Value;
				if (value is double)
				{
					return (double)value;
				}
				double num = ((!(value is BigInteger bigInteger)) ? Convert.ToDouble(value, CultureInfo.InvariantCulture) : ((double)bigInteger));
				SetToken(JsonToken.Float, num, updateIndex: false);
				return num;
			}
			case JsonToken.String:
				return ReadDoubleString((string)Value);
			default:
				throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal double? ReadDoubleString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out var result))
			{
				SetToken(JsonToken.Float, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual bool? ReadAsBoolean()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				bool flag = ((!(Value is BigInteger bigInteger)) ? Convert.ToBoolean(Value, CultureInfo.InvariantCulture) : (bigInteger != 0L));
				SetToken(JsonToken.Boolean, flag, updateIndex: false);
				return flag;
			}
			case JsonToken.String:
				return ReadBooleanString((string)Value);
			case JsonToken.Boolean:
				return (bool)Value;
			default:
				throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal bool? ReadBooleanString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (bool.TryParse(s, out var result))
			{
				SetToken(JsonToken.Boolean, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual decimal? ReadAsDecimal()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				object value = Value;
				if (value is decimal)
				{
					return (decimal)value;
				}
				decimal num;
				if (value is BigInteger bigInteger)
				{
					num = (decimal)bigInteger;
				}
				else
				{
					try
					{
						num = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
					}
					catch (Exception ex)
					{
						throw JsonReaderException.Create(this, "Could not convert to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex);
					}
				}
				SetToken(JsonToken.Float, num, updateIndex: false);
				return num;
			}
			case JsonToken.String:
				return ReadDecimalString((string)Value);
			default:
				throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal decimal? ReadDecimalString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (decimal.TryParse(s, NumberStyles.Number, Culture, out var result))
			{
				SetToken(JsonToken.Float, result, updateIndex: false);
				return result;
			}
			if (ConvertUtils.DecimalTryParse(s.ToCharArray(), 0, s.Length, out result) == ParseResult.Success)
			{
				SetToken(JsonToken.Float, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual DateTime? ReadAsDateTime()
		{
			switch (GetContentToken())
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Date:
				if (Value is DateTimeOffset dateTimeOffset)
				{
					SetToken(JsonToken.Date, dateTimeOffset.DateTime, updateIndex: false);
				}
				return (DateTime)Value;
			case JsonToken.String:
				return ReadDateTimeString((string)Value);
			default:
				throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
			}
		}

		internal DateTime? ReadDateTimeString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out var dt))
			{
				dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
			{
				dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual DateTimeOffset? ReadAsDateTimeOffset()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Date:
				if (Value is DateTime dateTime)
				{
					SetToken(JsonToken.Date, new DateTimeOffset(dateTime), updateIndex: false);
				}
				return (DateTimeOffset)Value;
			case JsonToken.String:
			{
				string s = (string)Value;
				return ReadDateTimeOffsetString(s);
			}
			default:
				throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal DateTimeOffset? ReadDateTimeOffsetString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out var dt))
			{
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
			{
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		internal void ReaderReadAndAssert()
		{
			if (!Read())
			{
				throw CreateUnexpectedEndException();
			}
		}

		internal JsonReaderException CreateUnexpectedEndException()
		{
			return JsonReaderException.Create(this, "Unexpected end when reading JSON.");
		}

		internal void ReadIntoWrappedTypeObject()
		{
			ReaderReadAndAssert();
			if (Value != null && Value.ToString() == "$type")
			{
				ReaderReadAndAssert();
				if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal))
				{
					ReaderReadAndAssert();
					if (Value.ToString() == "$value")
					{
						return;
					}
				}
			}
			throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
		}

		public void Skip()
		{
			if (TokenType == JsonToken.PropertyName)
			{
				Read();
			}
			if (JsonTokenUtils.IsStartToken(TokenType))
			{
				int depth = Depth;
				while (Read() && depth < Depth)
				{
				}
			}
		}

		protected void SetToken(JsonToken newToken)
		{
			SetToken(newToken, null, updateIndex: true);
		}

		protected void SetToken(JsonToken newToken, object? value)
		{
			SetToken(newToken, value, updateIndex: true);
		}

		protected void SetToken(JsonToken newToken, object? value, bool updateIndex)
		{
			_tokenType = newToken;
			_value = value;
			switch (newToken)
			{
			case JsonToken.StartObject:
				_currentState = State.ObjectStart;
				Push(JsonContainerType.Object);
				break;
			case JsonToken.StartArray:
				_currentState = State.ArrayStart;
				Push(JsonContainerType.Array);
				break;
			case JsonToken.StartConstructor:
				_currentState = State.ConstructorStart;
				Push(JsonContainerType.Constructor);
				break;
			case JsonToken.EndObject:
				ValidateEnd(JsonToken.EndObject);
				break;
			case JsonToken.EndArray:
				ValidateEnd(JsonToken.EndArray);
				break;
			case JsonToken.EndConstructor:
				ValidateEnd(JsonToken.EndConstructor);
				break;
			case JsonToken.PropertyName:
				_currentState = State.Property;
				_currentPosition.PropertyName = (string)value;
				break;
			case JsonToken.Raw:
			case JsonToken.Integer:
			case JsonToken.Float:
			case JsonToken.String:
			case JsonToken.Boolean:
			case JsonToken.Null:
			case JsonToken.Undefined:
			case JsonToken.Date:
			case JsonToken.Bytes:
				SetPostValueState(updateIndex);
				break;
			case JsonToken.Comment:
				break;
			}
		}

		internal void SetPostValueState(bool updateIndex)
		{
			if (Peek() != 0 || SupportMultipleContent)
			{
				_currentState = State.PostValue;
			}
			else
			{
				SetFinished();
			}
			if (updateIndex)
			{
				UpdateScopeWithFinishedValue();
			}
		}

		private void UpdateScopeWithFinishedValue()
		{
			if (_currentPosition.HasIndex)
			{
				_currentPosition.Position++;
			}
		}

		private void ValidateEnd(JsonToken endToken)
		{
			JsonContainerType jsonContainerType = Pop();
			if (GetTypeForCloseToken(endToken) != jsonContainerType)
			{
				throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, jsonContainerType));
			}
			if (Peek() != 0 || SupportMultipleContent)
			{
				_currentState = State.PostValue;
			}
			else
			{
				SetFinished();
			}
		}

		protected void SetStateBasedOnCurrent()
		{
			JsonContainerType jsonContainerType = Peek();
			switch (jsonContainerType)
			{
			case JsonContainerType.Object:
				_currentState = State.Object;
				break;
			case JsonContainerType.Array:
				_currentState = State.Array;
				break;
			case JsonContainerType.Constructor:
				_currentState = State.Constructor;
				break;
			case JsonContainerType.None:
				SetFinished();
				break;
			default:
				throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContainerType));
			}
		}

		private void SetFinished()
		{
			_currentState = ((!SupportMultipleContent) ? State.Finished : State.Start);
		}

		private JsonContainerType GetTypeForCloseToken(JsonToken token)
		{
			return token switch
			{
				JsonToken.EndObject => JsonContainerType.Object, 
				JsonToken.EndArray => JsonContainerType.Array, 
				JsonToken.EndConstructor => JsonContainerType.Constructor, 
				_ => throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)), 
			};
		}

		void IDisposable.Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (_currentState != State.Closed && disposing)
			{
				Close();
			}
		}

		public virtual void Close()
		{
			_currentState = State.Closed;
			_tokenType = JsonToken.None;
			_value = null;
		}

		internal void ReadAndAssert()
		{
			if (!Read())
			{
				throw JsonSerializationException.Create(this, "Unexpected end when reading JSON.");
			}
		}

		internal void ReadForTypeAndAssert(JsonContract? contract, bool hasConverter)
		{
			if (!ReadForType(contract, hasConverter))
			{
				throw JsonSerializationException.Create(this, "Unexpected end when reading JSON.");
			}
		}

		internal bool ReadForType(JsonContract? contract, bool hasConverter)
		{
			if (hasConverter)
			{
				return Read();
			}
			switch (contract?.InternalReadType ?? ReadType.Read)
			{
			case ReadType.Read:
				return ReadAndMoveToContent();
			case ReadType.ReadAsInt32:
				ReadAsInt32();
				break;
			case ReadType.ReadAsInt64:
			{
				bool result = ReadAndMoveToContent();
				if (TokenType == JsonToken.Undefined)
				{
					throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract?.UnderlyingType ?? typeof(long)));
				}
				return result;
			}
			case ReadType.ReadAsDecimal:
				ReadAsDecimal();
				break;
			case ReadType.ReadAsDouble:
				ReadAsDouble();
				break;
			case ReadType.ReadAsBytes:
				ReadAsBytes();
				break;
			case ReadType.ReadAsBoolean:
				ReadAsBoolean();
				break;
			case ReadType.ReadAsString:
				ReadAsString();
				break;
			case ReadType.ReadAsDateTime:
				ReadAsDateTime();
				break;
			case ReadType.ReadAsDateTimeOffset:
				ReadAsDateTimeOffset();
				break;
			default:
				throw new ArgumentOutOfRangeException();
			}
			return TokenType != JsonToken.None;
		}

		internal bool ReadAndMoveToContent()
		{
			if (Read())
			{
				return MoveToContent();
			}
			return false;
		}

		internal bool MoveToContent()
		{
			JsonToken tokenType = TokenType;
			while (tokenType == JsonToken.None || tokenType == JsonToken.Comment)
			{
				if (!Read())
				{
					return false;
				}
				tokenType = TokenType;
			}
			return true;
		}

		private JsonToken GetContentToken()
		{
			JsonToken tokenType;
			do
			{
				if (!Read())
				{
					SetToken(JsonToken.None);
					return JsonToken.None;
				}
				tokenType = TokenType;
			}
			while (tokenType == JsonToken.Comment);
			return tokenType;
		}
	}
	[Serializable]
	public class JsonReaderException : JsonException
	{
		public int LineNumber { get; }

		public int LinePosition { get; }

		public string? Path { get; }

		public JsonReaderException()
		{
		}

		public JsonReaderException(string message)
			: base(message)
		{
		}

		public JsonReaderException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public JsonReaderException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception? innerException)
			: base(message, innerException)
		{
			Path = path;
			LineNumber = lineNumber;
			LinePosition = linePosition;
		}

		internal static JsonReaderException Create(JsonReader reader, string message)
		{
			return Create(reader, message, null);
		}

		internal static JsonReaderException Create(JsonReader reader, string message, Exception? ex)
		{
			return Create(reader as IJsonLineInfo, reader.Path, message, ex);
		}

		internal static JsonReaderException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex)
		{
			message = JsonPosition.FormatMessage(lineInfo, path, message);
			int lineNumber;
			int linePosition;
			if (lineInfo != null && lineInfo.HasLineInfo())
			{
				lineNumber = lineInfo.LineNumber;
				linePosition = lineInfo.LinePosition;
			}
			else
			{
				lineNumber = 0;
				linePosition = 0;
			}
			return new JsonReaderException(message, path, lineNumber, linePosition, ex);
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public sealed class JsonRequiredAttribute : Attribute
	{
	}
	[Serializable]
	public class JsonSerializationException : JsonException
	{
		public int LineNumber { get; }

		public int LinePosition { get; }

		public string? Path { get; }

		public JsonSerializationException()
		{
		}

		public JsonSerializationException(string message)
			: base(message)
		{
		}

		public JsonSerializationException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public JsonSerializationException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception? innerException)
			: base(message, innerException)
		{
			Path = path;
			LineNumber = lineNumber;
			LinePosition = linePosition;
		}

		internal static JsonSerializationException Create(JsonReader reader, string message)
		{
			return Create(reader, message, null);
		}

		internal static JsonSerializationException Create(JsonReader reader, string message, Exception? ex)
		{
			return Create(reader as IJsonLineInfo, reader.Path, message, ex);
		}

		internal static JsonSerializationException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex)
		{
			message = JsonPosition.FormatMessage(lineInfo, path, message);
			int lineNumber;
			int linePosition;
			if (lineInfo != null && lineInfo.HasLineInfo())
			{
				lineNumber = lineInfo.LineNumber;
				linePosition = lineInfo.LinePosition;
			}
			else
			{
				lineNumber = 0;
				linePosition = 0;
			}
			return new JsonSerializationException(message, path, lineNumber, linePosition, ex);
		}
	}
	[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
	[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
	public class JsonSerializer
	{
		internal TypeNameHandling _typeNameHandling;

		internal TypeNameAssemblyFormatHandling _typeNameAssemblyFormatHandling;

		internal PreserveReferencesHandling _preserveReferencesHandling;

		internal ReferenceLoopHandling _referenceLoopHandling;

		internal MissingMemberHandling _missingMemberHandling;

		internal ObjectCreationHandling _objectCreationHandling;

		internal NullValueHandling _nullValueHandling;

		internal DefaultValueHandling _defaultValueHandling;

		internal ConstructorHandling _constructorHandling;

		internal MetadataPropertyHandling _metadataPropertyHandling;

		internal JsonConverterCollection? _converters;

		internal IContractResolver _contractResolver;

		internal ITraceWriter? _traceWriter;

		internal IEqualityComparer? _equalityComparer;

		internal ISerializationBinder _serializationBinder;

		internal StreamingContext _context;

		private IReferenceResolver? _referenceResolver;

		private Formatting? _formatting;

		private DateFormatHandling? _dateFormatHandling;

		private DateTimeZoneHandling? _dateTimeZoneHandling;

		private DateParseHandling? _dateParseHandling;

		private FloatFormatHandling? _floatFormatHandling;

		private FloatParseHandling? _floatParseHandling;

		private StringEscapeHandling? _stringEscapeHandling;

		private CultureInfo _culture;

		private int? _maxDepth;

		private bool _maxDepthSet;

		private bool? _checkAdditionalContent;

		private string? _dateFormatString;

		private bool _dateFormatStringSet;

		public virtual IReferenceResolver? ReferenceResolver
		{
			get
			{
				return GetReferenceResolver();
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value", "Reference resolver cannot be null.");
				}
				_referenceResolver = value;
			}
		}

		[Obsolete("Binder is obsolete. Use SerializationBinder instead.")]
		public virtual SerializationBinder Binder
		{
			get
			{
				if (_serializationBinder is SerializationBinder result)
				{
					return result;
				}
				if (_serializationBinder is SerializationBinderAdapter serializationBinderAdapter)
				{
					return serializationBinderAdapter.SerializationBinder;
				}
				throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set.");
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value", "Serialization binder cannot be null.");
				}
				_serializationBinder = (value as ISerializationBinder) ?? new SerializationBinderAdapter(value);
			}
		}

		public virtual ISerializationBinder SerializationBinder
		{
			get
			{
				return _serializationBinder;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value", "Serialization binder cannot be null.");
				}
				_serializationBinder = value;
			}
		}

		public virtual ITraceWriter? TraceWriter
		{
			get
			{
				return _traceWriter;
			}
			set
			{
				_traceWriter = value;
			}
		}

		public virtual IEqualityComparer? EqualityComparer
		{
			get
			{
				return _equalityComparer;
			}
			set
			{
				_equalityComparer = value;
			}
		}

		public virtual TypeNameHandling TypeNameHandling
		{
			get
			{
				return _typeNameHandling;
			}
			set
			{
				if (value < TypeNameHandling.None || value > TypeNameHandling.Auto)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_typeNameHandling = value;
			}
		}

		[Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")]
		public virtual FormatterAssemblyStyle TypeNameAssemblyFormat
		{
			get
			{
				return (FormatterAssemblyStyle)_typeNameAssemblyFormatHandling;
			}
			set
			{
				if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_typeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value;
			}
		}

		public virtual TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling
		{
			get
			{
				return _typeNameAssemblyFormatHandling;
			}
			set
			{
				if (value < TypeNameAssemblyFormatHandling.Simple || value > TypeNameAssemblyFormatHandling.Full)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_typeNameAssemblyFormatHandling = value;
			}
		}

		public virtual PreserveReferencesHandling PreserveReferencesHandling
		{
			get
			{
				return _preserveReferencesHandling;
			}
			set
			{
				if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_preserveReferencesHandling = value;
			}
		}

		public virtual ReferenceLoopHandling ReferenceLoopHandling
		{
			get
			{
				return _referenceLoopHandling;
			}
			set
			{
				if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_referenceLoopHandling = value;
			}
		}

		public virtual MissingMemberHandling MissingMemberHandling
		{
			get
			{
				return _missingMemberHandling;
			}
			set
			{
				if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_missingMemberHandling = value;
			}
		}

		public virtual NullValueHandling NullValueHandling
		{
			get
			{
				return _nullValueHandling;
			}
			set
			{
				if (value < NullValueHandling.Include || value > NullValueHandling.Ignore)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_nullValueHandling = value;
			}
		}

		public virtual DefaultValueHandling DefaultValueHandling
		{
			get
			{
				return _defaultValueHandling;
			}
			set
			{
				if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_defaultValueHandling = value;
			}
		}

		public virtual ObjectCreationHandling ObjectCreationHandling
		{
			get
			{
				return _objectCreationHandling;
			}
			set
			{
				if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_objectCreationHandling = value;
			}
		}

		public virtual ConstructorHandling ConstructorHandling
		{
			get
			{
				return _constructorHandling;
			}
			set
			{
				if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_constructorHandling = value;
			}
		}

		public virtual MetadataPropertyHandling MetadataPropertyHandling
		{
			get
			{
				return _metadataPropertyHandling;
			}
			set
			{
				if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_metadataPropertyHandling = value;
			}
		}

		public virtual JsonConverterCollection Converters
		{
			get
			{
				if (_converters == null)
				{
					_converters = new JsonConverterCollection();
				}
				return _converters;
			}
		}

		public virtual IContractResolver ContractResolver
		{
			get
			{
				return _contractResolver;
			}
			set
			{
				_contractResolver = value ?? DefaultContractResolver.Instance;
			}
		}

		public virtual StreamingContext Context
		{
			get
			{
				return _context;
			}
			set
			{
				_context = value;
			}
		}

		public virtual Formatting Formatting
		{
			get
			{
				return _formatting.GetValueOrDefault();
			}
			set
			{
				_formatting = value;
			}
		}

		public virtual DateFormatHandling DateFormatHandling
		{
			get
			{
				return _dateFormatHandling.GetValueOrDefault();
			}
			set
			{
				_dateFormatHandling = value;
			}
		}

		public virtual DateTimeZoneHandling DateTimeZoneHandling
		{
			get
			{
				return _dateTimeZoneHandling.GetValueOrDefault(DateTimeZoneHandling.RoundtripKind);
			}
			set
			{
				_dateTimeZoneHandling = value;
			}
		}

		public virtual DateParseHandling DateParseHandling
		{
			get
			{
				return _dateParseHandling.GetValueOrDefault(DateParseHandling.DateTime);
			}
			set
			{
				_dateParseHandling = value;
			}
		}

		public virtual FloatParseHandling FloatParseHandling
		{
			get
			{
				return _floatParseHandling.GetValueOrDefault();
			}
			set
			{
				_floatParseHandling = value;
			}
		}

		public virtual FloatFormatHandling FloatFormatHandling
		{
			get
			{
				return _floatFormatHandling.GetValueOrDefault();
			}
			set
			{
				_floatFormatHandling = value;
			}
		}

		public virtual StringEscapeHandling StringEscapeHandling
		{
			get
			{
				return _stringEscapeHandling.GetValueOrDefault();
			}
			set
			{
				_stringEscapeHandling = value;
			}
		}

		public virtual string DateFormatString
		{
			get
			{
				return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
			}
			set
			{
				_dateFormatString = value;
				_dateFormatStringSet = true;
			}
		}

		public virtual CultureInfo Culture
		{
			get
			{
				return _culture ?? JsonSerializerSettings.DefaultCulture;
			}
			set
			{
				_culture = value;
			}
		}

		public virtual int? MaxDepth
		{
			get
			{
				return _maxDepth;
			}
			set
			{
				if (value <= 0)
				{
					throw new ArgumentException("Value must be positive.", "value");
				}
				_maxDepth = value;
				_maxDepthSet = true;
			}
		}

		public virtual bool CheckAdditionalContent
		{
			get
			{
				return _checkAdditionalContent.GetValueOrDefault();
			}
			set
			{
				_checkAdditionalContent = value;
			}
		}

		public virtual event EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>? Error;

		internal bool IsCheckAdditionalContentSet()
		{
			return _checkAdditionalContent.HasValue;
		}

		public JsonSerializer()
		{
			_referenceLoopHandling = ReferenceLoopHandling.Error;
			_missingMemberHandling = MissingMemberHandling.Ignore;
			_nullValueHandling = NullValueHandling.Include;
			_defaultValueHandling = DefaultValueHandling.Include;
			_objectCreationHandling = ObjectCreationHandling.Auto;
			_preserveReferencesHandling = PreserveReferencesHandling.None;
			_constructorHandling = ConstructorHandling.Default;
			_typeNameHandling = TypeNameHandling.None;
			_metadataPropertyHandling = MetadataPropertyHandling.Default;
			_context = JsonSerializerSettings.DefaultContext;
			_serializationBinder = DefaultSerializationBinder.Instance;
			_culture = JsonSerializerSettings.DefaultCulture;
			_contractResolver = DefaultContractResolver.Instance;
		}

		public static JsonSerializer Create()
		{
			return new JsonSerializer();
		}

		public static JsonSerializer Create(JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = Create();
			if (settings != null)
			{
				ApplySerializerSettings(jsonSerializer, settings);
			}
			return jsonSerializer;
		}

		public static JsonSerializer CreateDefault()
		{
			return Create(JsonConvert.DefaultSettings?.Invoke());
		}

		public static JsonSerializer CreateDefault(JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = CreateDefault();
			if (settings != null)
			{
				ApplySerializerSettings(jsonSerializer, settings);
			}
			return jsonSerializer;
		}

		private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings)
		{
			if (!CollectionUtils.IsNullOrEmpty(settings.Converters))
			{
				for (int i = 0; i < settings.Converters.Count; i++)
				{
					serializer.Converters.Insert(i, settings.Converters[i]);
				}
			}
			if (settings._typeNameHandling.HasValue)
			{
				serializer.TypeNameHandling = settings.TypeNameHandling;
			}
			if (settings._metadataPropertyHandling.HasValue)
			{
				serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling;
			}
			if (settings._typeNameAssemblyFormatHandling.HasValue)
			{
				serializer.TypeNameAssemblyFormatHandling = settings.TypeNameAssemblyFormatHandling;
			}
			if (settings._preserveReferencesHandling.HasValue)
			{
				serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling;
			}
			if (settings._referenceLoopHandling.HasValue)
			{
				serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling;
			}
			if (settings._missingMemberHandling.HasValue)
			{
				serializer.MissingMemberHandling = settings.MissingMemberHandling;
			}
			if (settings._objectCreationHandling.HasValue)
			{
				serializer.ObjectCreationHandling = settings.ObjectCreationHandling;
			}
			if (settings._nullValueHandling.HasValue)
			{
				serializer.NullValueHandling = settings.NullValueHandling;
			}
			if (settings._defaultValueHandling.HasValue)
			{
				serializer.DefaultValueHandling = settings.DefaultValueHandling;
			}
			if (settings._constructorHandling.HasValue)
			{
				serializer.ConstructorHandling = settings.ConstructorHandling;
			}
			if (settings._context.HasValue)
			{
				serializer.Context = settings.Context;
			}
			if (settings._checkAdditionalContent.HasValue)
			{
				serializer._checkAdditionalContent = settings._checkAdditionalContent;
			}
			if (settings.Error != null)
			{
				serializer.Error += settings.Error;
			}
			if (settings.ContractResolver != null)
			{
				serializer.ContractResolver = settings.ContractResolver;
			}
			if (settings.ReferenceResolverProvider != null)
			{
				serializer.ReferenceResolver = settings.ReferenceResolverProvider();
			}
			if (settings.TraceWriter != null)
			{
				serializer.TraceWriter = settings.TraceWriter;
			}
			if (settings.EqualityComparer != null)
			{
				serializer.EqualityComparer = settings.EqualityComparer;
			}
			if (settings.SerializationBinder != null)
			{
				serializer.SerializationBinder = settings.SerializationBinder;
			}
			if (settings._formatting.HasValue)
			{
				serializer._formatting = settings._formatting;
			}
			if (settings._dateFormatHandling.HasValue)
			{
				serializer._dateFormatHandling = settings._dateFormatHandling;
			}
			if (settings._dateTimeZoneHandling.HasValue)
			{
				serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling;
			}
			if (settings._dateParseHandling.HasValue)
			{
				serializer._dateParseHandling = settings._dateParseHandling;
			}
			if (settings._dateFormatStringSet)
			{
				serializer._dateFormatString = settings._dateFormatString;
				serializer._dateFormatStringSet = settings._dateFormatStringSet;
			}
			if (settings._floatFormatHandling.HasValue)
			{
				serializer._floatFormatHandling = settings._floatFormatHandling;
			}
			if (settings._floatParseHandling.HasValue)
			{
				serializer._floatParseHandling = settings._floatParseHandling;
			}
			if (settings._stringEscapeHandling.HasValue)
			{
				serializer._stringEscapeHandling = settings._stringEscapeHandling;
			}
			if (settings._culture != null)
			{
				serializer._culture = settings._culture;
			}
			if (settings._maxDepthSet)
			{
				serializer._maxDepth = settings._maxDepth;
				serializer._maxDepthSet = settings._maxDepthSet;
			}
		}

		[DebuggerStepThrough]
		public void Populate(TextReader reader, object target)
		{
			Populate(new JsonTextReader(reader), target);
		}

		[DebuggerStepThrough]
		public void Populate(JsonReader reader, object target)
		{
			PopulateInternal(reader, target);
		}

		internal virtual void PopulateInternal(JsonReader reader, object target)
		{
			ValidationUtils.ArgumentNotNull(reader, "reader");
			ValidationUtils.ArgumentNotNull(target, "target");
			SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString);
			TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null);
			new JsonSerializerInternalReader(this).Populate(traceJsonReader ?? reader, target);
			if (traceJsonReader != null)
			{
				TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
			}
			ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
		}

		[DebuggerStepThrough]
		public object? Deserialize(JsonReader reader)
		{
			return Deserialize(reader, null);
		}

		[DebuggerStepThrough]
		public object? Deserialize(TextReader reader, Type objectType)
		{
			return Deserialize(new JsonTextReader(reader), objectType);
		}

		[DebuggerStepThrough]
		public T? Deserialize<T>(JsonReader reader)
		{
			return (T)Deserialize(reader, typeof(T));
		}

		[DebuggerStepThrough]
		public object? Deserialize(JsonReader reader, Type? objectType)
		{
			return DeserializeInternal(reader, objectType);
		}

		internal virtual object? DeserializeInternal(JsonReader reader, Type? objectType)
		{
			ValidationUtils.ArgumentNotNull(reader, "reader");
			SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString);
			TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null);
			object? result = new JsonSerializerInternalReader(this).Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent);
			if (traceJsonReader != null)
			{
				TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
			}
			ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
			return result;
		}

		internal void SetupReader(JsonReader reader, out CultureInfo? previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string? previousDateFormatString)
		{
			if (_culture != null && !_culture.Equals(reader.Culture))
			{
				previousCulture = reader.Culture;
				reader.Culture = _culture

plugins/System.Linq.Dynamic.Core.dll

Decompiled 2 weeks ago
#define TRACE
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Dynamic.Core.Config;
using System.Linq.Dynamic.Core.CustomTypeProviders;
using System.Linq.Dynamic.Core.Exceptions;
using System.Linq.Dynamic.Core.Extensions;
using System.Linq.Dynamic.Core.Parser;
using System.Linq.Dynamic.Core.Parser.SupportedMethods;
using System.Linq.Dynamic.Core.Parser.SupportedOperands;
using System.Linq.Dynamic.Core.Tokenizer;
using System.Linq.Dynamic.Core.TypeConverters;
using System.Linq.Dynamic.Core.Util;
using System.Linq.Dynamic.Core.Util.Cache;
using System.Linq.Dynamic.Core.Validation;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using AnyOfTypes;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("System.Linq.Dynamic.Core.SystemTextJson, PublicKey=00240000048000009400000006020000002400005253413100040000010001003daf4f4b7d160b1033de9a4a3275f4667a4558144296c3bb593aa0fd213dadf0ea4df5aa69e21763d409ada2a8f8925081bc2e81362be7916e22c624344309eba764edc4f8f84237ae053d2687ab3b888c9f4f3ff8a804bb5fee61e1ceadec97b08994580ef2df6bd7e077df4ad205c6d2bde479c512ab9be6ecc23c10694597")]
[assembly: InternalsVisibleTo("System.Linq.Dynamic.Core.NewtonsoftJson, PublicKey=00240000048000009400000006020000002400005253413100040000010001003daf4f4b7d160b1033de9a4a3275f4667a4558144296c3bb593aa0fd213dadf0ea4df5aa69e21763d409ada2a8f8925081bc2e81362be7916e22c624344309eba764edc4f8f84237ae053d2687ab3b888c9f4f3ff8a804bb5fee61e1ceadec97b08994580ef2df6bd7e077df4ad205c6d2bde479c512ab9be6ecc23c10694597")]
[assembly: InternalsVisibleTo("EntityFramework.DynamicLinq.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001003daf4f4b7d160b1033de9a4a3275f4667a4558144296c3bb593aa0fd213dadf0ea4df5aa69e21763d409ada2a8f8925081bc2e81362be7916e22c624344309eba764edc4f8f84237ae053d2687ab3b888c9f4f3ff8a804bb5fee61e1ceadec97b08994580ef2df6bd7e077df4ad205c6d2bde479c512ab9be6ecc23c10694597")]
[assembly: InternalsVisibleTo("EntityFramework.DynamicLinq.Tests.net452, PublicKey=00240000048000009400000006020000002400005253413100040000010001003daf4f4b7d160b1033de9a4a3275f4667a4558144296c3bb593aa0fd213dadf0ea4df5aa69e21763d409ada2a8f8925081bc2e81362be7916e22c624344309eba764edc4f8f84237ae053d2687ab3b888c9f4f3ff8a804bb5fee61e1ceadec97b08994580ef2df6bd7e077df4ad205c6d2bde479c512ab9be6ecc23c10694597")]
[assembly: InternalsVisibleTo("System.Linq.Dynamic.Core.Tests.Net6, PublicKey=00240000048000009400000006020000002400005253413100040000010001003daf4f4b7d160b1033de9a4a3275f4667a4558144296c3bb593aa0fd213dadf0ea4df5aa69e21763d409ada2a8f8925081bc2e81362be7916e22c624344309eba764edc4f8f84237ae053d2687ab3b888c9f4f3ff8a804bb5fee61e1ceadec97b08994580ef2df6bd7e077df4ad205c6d2bde479c512ab9be6ecc23c10694597")]
[assembly: InternalsVisibleTo("System.Linq.Dynamic.Core.Tests.Net5, PublicKey=00240000048000009400000006020000002400005253413100040000010001003daf4f4b7d160b1033de9a4a3275f4667a4558144296c3bb593aa0fd213dadf0ea4df5aa69e21763d409ada2a8f8925081bc2e81362be7916e22c624344309eba764edc4f8f84237ae053d2687ab3b888c9f4f3ff8a804bb5fee61e1ceadec97b08994580ef2df6bd7e077df4ad205c6d2bde479c512ab9be6ecc23c10694597")]
[assembly: InternalsVisibleTo("System.Linq.Dynamic.Core.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001003daf4f4b7d160b1033de9a4a3275f4667a4558144296c3bb593aa0fd213dadf0ea4df5aa69e21763d409ada2a8f8925081bc2e81362be7916e22c624344309eba764edc4f8f84237ae053d2687ab3b888c9f4f3ff8a804bb5fee61e1ceadec97b08994580ef2df6bd7e077df4ad205c6d2bde479c512ab9be6ecc23c10694597")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
[assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")]
[assembly: AssemblyCompany("ZZZ Projects")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © ZZZ Projects")]
[assembly: AssemblyDescription("This is a .NETStandard / .NET Core port of the the Microsoft assembly for the .Net 4.0 Dynamic language functionality.")]
[assembly: AssemblyFileVersion("1.7.1.0")]
[assembly: AssemblyInformationalVersion("1.7.1+ed0a3ddf6f7d39c3becff1faf2f6c8cae7515b0a")]
[assembly: AssemblyProduct("System.Linq.Dynamic.Core")]
[assembly: AssemblyTitle("System.Linq.Dynamic.Core")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/zzzprojects/System.Linq.Dynamic.Core")]
[assembly: AssemblyVersion("1.7.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace System
{
	internal static class StringExtensions
	{
		public static bool IsNullOrWhiteSpace(this string? value)
		{
			return string.IsNullOrWhiteSpace(value);
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace System.Reflection
{
	internal static class CustomIntrospectionExtensions
	{
		public static Type[] GetGenericTypeArguments(this TypeInfo typeInfo)
		{
			return typeInfo.GenericTypeArguments;
		}
	}
	internal static class CustomTypeBuilderExtensions
	{
		public static Type CreateType(this TypeBuilder tb)
		{
			return tb.CreateTypeInfo().AsType();
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)]
	internal sealed class DynamicallyAccessedMembersAttribute : Attribute
	{
		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)
		{
			MemberTypes = memberTypes;
		}
	}
	[Flags]
	internal enum DynamicallyAccessedMemberTypes
	{
		All = -1,
		None = 0,
		PublicParameterlessConstructor = 1,
		PublicConstructors = 3,
		NonPublicConstructors = 4,
		PublicMethods = 8,
		NonPublicMethods = 0x10,
		PublicFields = 0x20,
		NonPublicFields = 0x40,
		PublicNestedTypes = 0x80,
		NonPublicNestedTypes = 0x100,
		PublicProperties = 0x200,
		NonPublicProperties = 0x400,
		PublicEvents = 0x800,
		NonPublicEvents = 0x1000,
		Interfaces = 0x2000
	}
	[AttributeUsage(AttributeTargets.Parameter)]
	[DebuggerNonUserCode]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
}
namespace System.Linq.Expressions
{
	internal static class LambdaExpressionExtensions
	{
		public static Type GetReturnType(this LambdaExpression lambdaExpression)
		{
			return lambdaExpression.ReturnType;
		}
	}
}
namespace System.Linq.Dynamic.Core
{
	internal static class AssemblyBuilderFactory
	{
		public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access)
		{
			return AssemblyBuilder.DefineDynamicAssembly(name, access);
		}
	}
	internal class DefaultAssemblyHelper : IAssemblyHelper
	{
		private readonly ParsingConfig _config = Check.NotNull(parsingConfig, "parsingConfig");

		public DefaultAssemblyHelper(ParsingConfig parsingConfig)
		{
		}

		public Assembly[] GetAssemblies()
		{
			List<Assembly> list = AppDomain.CurrentDomain.GetAssemblies().ToList();
			List<string> loadedPaths = new List<string>();
			foreach (Assembly item in list)
			{
				try
				{
					if (!item.IsDynamic)
					{
						loadedPaths.Add(item.Location);
					}
				}
				catch
				{
				}
			}
			if (!_config.LoadAdditionalAssembliesFromCurrentDomainBaseDirectory)
			{
				return list.ToArray();
			}
			string[] source;
			try
			{
				source = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
			}
			catch
			{
				source = Array.Empty<string>();
			}
			string[] array = source.Where((string referencedPath) => !loadedPaths.Contains<string>(referencedPath, StringComparer.InvariantCultureIgnoreCase)).ToArray();
			foreach (string assemblyFile in array)
			{
				try
				{
					list.Add(AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(assemblyFile)));
				}
				catch
				{
				}
			}
			return list.ToArray();
		}
	}
	public class DefaultQueryableAnalyzer : IQueryableAnalyzer
	{
		public bool SupportsLinqToObjects(IQueryable query, IQueryProvider? provider = null)
		{
			Check.NotNull(query, "query");
			provider = provider ?? query.Provider;
			Type type = provider.GetType();
			bool flag = type.GetTypeInfo().BaseType == typeof(EnumerableQuery);
			if (!flag)
			{
				if (type.Name.StartsWith("QueryTranslatorProvider"))
				{
					try
					{
						PropertyInfo property = type.GetProperty("OriginalProvider");
						if (property != null)
						{
							return property.GetValue(provider, null) is IQueryProvider provider2 && SupportsLinqToObjects(query, provider2);
						}
						return SupportsLinqToObjects(query);
					}
					catch
					{
						return false;
					}
				}
				if (type.Name.StartsWith("ExpandableQuery"))
				{
					try
					{
						PropertyInfo property2 = query.GetType().GetProperty("InnerQuery", BindingFlags.Instance | BindingFlags.NonPublic);
						if (property2 != null)
						{
							return property2.GetValue(query, null) is IQueryable query2 && SupportsLinqToObjects(query2, provider);
						}
						return SupportsLinqToObjects(query);
					}
					catch
					{
						return false;
					}
				}
			}
			return flag;
		}
	}
	public abstract class DynamicClass : DynamicObject
	{
		internal const string IndexerName = "System_Linq_Dynamic_Core_DynamicClass_Indexer";

		private Dictionary<string, object?>? _propertiesDictionary;

		private Dictionary<string, object?> Properties
		{
			get
			{
				if (_propertiesDictionary == null)
				{
					_propertiesDictionary = new Dictionary<string, object>();
					PropertyInfo[] properties = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
					foreach (PropertyInfo propertyInfo in properties)
					{
						if (propertyInfo.GetIndexParameters().Length <= 0)
						{
							_propertiesDictionary.Add(propertyInfo.Name, propertyInfo.GetValue(this, null));
						}
					}
				}
				return _propertiesDictionary;
			}
		}

		[IndexerName("System_Linq_Dynamic_Core_DynamicClass_Indexer")]
		public object? this[string name]
		{
			get
			{
				if (!Properties.TryGetValue(name, out object value))
				{
					return null;
				}
				return value;
			}
			set
			{
				if (Properties.ContainsKey(name))
				{
					Properties[name] = value;
				}
				else
				{
					Properties.Add(name, value);
				}
			}
		}

		public T? GetDynamicPropertyValue<T>(string propertyName)
		{
			return (T)(GetType().GetProperty(propertyName)?.GetValue(this, null));
		}

		public object? GetDynamicPropertyValue(string propertyName)
		{
			return GetDynamicPropertyValue<object>(propertyName);
		}

		public void SetDynamicPropertyValue<T>(string propertyName, T value)
		{
			GetType().GetProperty(propertyName)?.SetValue(this, value, null);
		}

		public void SetDynamicPropertyValue(string propertyName, object value)
		{
			this.SetDynamicPropertyValue<object>(propertyName, value);
		}

		public bool ContainsProperty(string name)
		{
			return Properties.ContainsKey(name);
		}

		public override IEnumerable<string> GetDynamicMemberNames()
		{
			return Properties.Keys;
		}

		public override bool TryGetMember(GetMemberBinder binder, out object? result)
		{
			return Properties.TryGetValue(binder.Name, out result);
		}

		public override bool TrySetMember(SetMemberBinder binder, object? value)
		{
			string name = binder.Name;
			if (Properties.ContainsKey(name))
			{
				Properties[name] = value;
			}
			else
			{
				Properties.Add(name, value);
			}
			return true;
		}
	}
	public static class DynamicClassFactory
	{
		private const string DynamicAssemblyName = "System.Linq.Dynamic.Core.DynamicClasses, Version=1.0.0.0";

		private const string DynamicModuleName = "System.Linq.Dynamic.Core.DynamicClasses";

		private static readonly CustomAttributeBuilder CompilerGeneratedAttributeBuilder;

		private static readonly CustomAttributeBuilder DebuggerBrowsableAttributeBuilder;

		private static readonly CustomAttributeBuilder DebuggerHiddenAttributeBuilder;

		private static readonly ConstructorInfo ObjectCtor;

		private static readonly ConstructorInfo StringBuilderCtor;

		private static readonly MethodInfo StringBuilderAppendString;

		private static readonly MethodInfo StringBuilderAppendObject;

		private static readonly Type EqualityComparer;

		private static readonly ConcurrentDictionary<string, Type> GeneratedTypes;

		private static readonly ModuleBuilder ModuleBuilder;

		private static int _index;

		static DynamicClassFactory()
		{
			CompilerGeneratedAttributeBuilder = new CustomAttributeBuilder(typeof(CompilerGeneratedAttribute).GetConstructor(Type.EmptyTypes), Array.Empty<object>());
			DebuggerBrowsableAttributeBuilder = new CustomAttributeBuilder(typeof(DebuggerBrowsableAttribute).GetConstructor(new Type[1] { typeof(DebuggerBrowsableState) }), new object[1] { DebuggerBrowsableState.Never });
			DebuggerHiddenAttributeBuilder = new CustomAttributeBuilder(typeof(DebuggerHiddenAttribute).GetConstructor(Type.EmptyTypes), Array.Empty<object>());
			ObjectCtor = typeof(object).GetConstructor(Type.EmptyTypes);
			StringBuilderCtor = typeof(StringBuilder).GetConstructor(Type.EmptyTypes);
			StringBuilderAppendString = typeof(StringBuilder).GetMethod("Append", BindingFlags.Instance | BindingFlags.Public, null, new Type[1] { typeof(string) }, null);
			StringBuilderAppendObject = typeof(StringBuilder).GetMethod("Append", BindingFlags.Instance | BindingFlags.Public, null, new Type[1] { typeof(object) }, null);
			EqualityComparer = typeof(EqualityComparer<>);
			GeneratedTypes = new ConcurrentDictionary<string, Type>();
			_index = -1;
			ModuleBuilder = AssemblyBuilderFactory.DefineDynamicAssembly(new AssemblyName("System.Linq.Dynamic.Core.DynamicClasses, Version=1.0.0.0"), AssemblyBuilderAccess.RunAndCollect).DefineDynamicModule("System.Linq.Dynamic.Core.DynamicClasses");
		}

		public static Type CreateGenericComparerType(Type comparerGenericType, Type comparerType)
		{
			Check.NotNull(comparerGenericType, "comparerGenericType");
			Check.NotNull(comparerType, "comparerType");
			string text = comparerGenericType.FullName + "_" + comparerType.FullName;
			if (!GeneratedTypes.TryGetValue(text, out Type value))
			{
				lock (GeneratedTypes)
				{
					if (!GeneratedTypes.TryGetValue(text, out value))
					{
						MethodInfo method = comparerGenericType.GetMethod("Compare");
						MethodInfo method2 = typeof(IComparer).GetMethod("Compare");
						ConstructorInfo constructor = comparerType.GetConstructor(Type.EmptyTypes);
						Type cls = comparerGenericType.GetGenericArguments()[0];
						TypeBuilder typeBuilder = ModuleBuilder.DefineType(text, TypeAttributes.Public, typeof(object));
						typeBuilder.AddInterfaceImplementation(comparerGenericType);
						FieldBuilder field = typeBuilder.DefineField("_c", typeof(IComparer), FieldAttributes.Private | FieldAttributes.InitOnly);
						ILGenerator iLGenerator = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.HasThis, Type.EmptyTypes).GetILGenerator();
						iLGenerator.Emit(OpCodes.Ldarg_0);
						iLGenerator.Emit(OpCodes.Call, ObjectCtor);
						iLGenerator.Emit(OpCodes.Ldarg_0);
						iLGenerator.Emit(OpCodes.Newobj, constructor);
						iLGenerator.Emit(OpCodes.Stfld, field);
						iLGenerator.Emit(OpCodes.Ret);
						ILGenerator iLGenerator2 = typeBuilder.DefineMethod(method.Name, method.Attributes & ~MethodAttributes.Abstract, method.CallingConvention, method.ReturnType, (from p in method.GetParameters()
							select p.ParameterType).ToArray()).GetILGenerator();
						iLGenerator2.Emit(OpCodes.Ldarg_0);
						iLGenerator2.Emit(OpCodes.Ldfld, field);
						iLGenerator2.Emit(OpCodes.Ldarg_1);
						iLGenerator2.Emit(OpCodes.Box, cls);
						iLGenerator2.Emit(OpCodes.Ldarg_2);
						iLGenerator2.Emit(OpCodes.Box, cls);
						iLGenerator2.Emit(OpCodes.Callvirt, method2);
						iLGenerator2.Emit(OpCodes.Ret);
						return GeneratedTypes.GetOrAdd(text, typeBuilder.CreateType());
					}
				}
			}
			return value;
		}

		public static Type CreateType(IList<DynamicProperty> properties, bool createParameterCtor = true)
		{
			IList<DynamicProperty> properties2 = properties;
			Check.HasNoNulls(properties2, "properties");
			string key = GenerateKey(properties2, createParameterCtor);
			if (!GeneratedTypes.TryGetValue(key, out Type value))
			{
				lock (GeneratedTypes)
				{
					return GeneratedTypes.GetOrAdd(key, (string _) => EmitType(properties2, createParameterCtor));
				}
			}
			return value;
		}

		public static DynamicClass CreateInstance(IList<DynamicPropertyWithValue> dynamicPropertiesWithValue, bool createParameterCtor = true)
		{
			DynamicClass dynamicClass = (DynamicClass)Activator.CreateInstance(CreateType(dynamicPropertiesWithValue.Cast<DynamicProperty>().ToArray(), createParameterCtor));
			foreach (DynamicPropertyWithValue item in dynamicPropertiesWithValue.Where((DynamicPropertyWithValue p) => p.Value != null))
			{
				dynamicClass.SetDynamicPropertyValue(item.Name, item.Value);
			}
			return dynamicClass;
		}

		private static Type EmitType(IList<DynamicProperty> properties, bool createParameterCtor)
		{
			int num = Interlocked.Increment(ref _index);
			string name = (properties.Any() ? $"<>f__AnonymousType{num}`{properties.Count}" : $"<>f__AnonymousType{num}");
			TypeBuilder typeBuilder = ModuleBuilder.DefineType(name, TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(DynamicClass));
			typeBuilder.SetCustomAttribute(CompilerGeneratedAttributeBuilder);
			FieldBuilder[] array = new FieldBuilder[properties.Count];
			for (int i = 0; i < properties.Count; i++)
			{
				string name2 = properties[i].Name;
				Type type = properties[i].Type;
				array[i] = typeBuilder.DefineField("<" + name2 + ">i__Field", type, FieldAttributes.Private | FieldAttributes.InitOnly);
				array[i].SetCustomAttribute(DebuggerBrowsableAttributeBuilder);
				PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(name2, PropertyAttributes.None, CallingConventions.HasThis, type, Type.EmptyTypes);
				MethodBuilder methodBuilder = typeBuilder.DefineMethod("get_" + name2, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName, CallingConventions.HasThis, type, null);
				methodBuilder.SetCustomAttribute(CompilerGeneratedAttributeBuilder);
				ILGenerator iLGenerator = methodBuilder.GetILGenerator();
				iLGenerator.Emit(OpCodes.Ldarg_0);
				iLGenerator.Emit(OpCodes.Ldfld, array[i]);
				iLGenerator.Emit(OpCodes.Ret);
				propertyBuilder.SetGetMethod(methodBuilder);
				MethodBuilder methodBuilder2 = typeBuilder.DefineMethod("set_" + name2, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName, CallingConventions.HasThis, null, new Type[1] { type });
				methodBuilder2.SetCustomAttribute(CompilerGeneratedAttributeBuilder);
				methodBuilder2.DefineParameter(1, ParameterAttributes.In, properties[i].Name);
				ILGenerator iLGenerator2 = methodBuilder2.GetILGenerator();
				iLGenerator2.Emit(OpCodes.Ldarg_0);
				iLGenerator2.Emit(OpCodes.Ldarg_1);
				iLGenerator2.Emit(OpCodes.Stfld, array[i]);
				iLGenerator2.Emit(OpCodes.Ret);
				propertyBuilder.SetSetMethod(methodBuilder2);
			}
			MethodBuilder methodBuilder3 = typeBuilder.DefineMethod("ToString", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, CallingConventions.HasThis, typeof(string), Type.EmptyTypes);
			methodBuilder3.SetCustomAttribute(DebuggerHiddenAttributeBuilder);
			ILGenerator iLGenerator3 = methodBuilder3.GetILGenerator();
			iLGenerator3.DeclareLocal(typeof(StringBuilder));
			iLGenerator3.Emit(OpCodes.Newobj, StringBuilderCtor);
			iLGenerator3.Emit(OpCodes.Stloc_0);
			MethodBuilder methodBuilder4 = typeBuilder.DefineMethod("Equals", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, CallingConventions.HasThis, typeof(bool), new Type[1] { typeof(object) });
			methodBuilder4.DefineParameter(1, ParameterAttributes.In, "value");
			methodBuilder4.SetCustomAttribute(DebuggerHiddenAttributeBuilder);
			ILGenerator iLGenerator4 = methodBuilder4.GetILGenerator();
			iLGenerator4.DeclareLocal(typeBuilder.AsType());
			iLGenerator4.Emit(OpCodes.Ldarg_1);
			iLGenerator4.Emit(OpCodes.Isinst, typeBuilder.AsType());
			iLGenerator4.Emit(OpCodes.Stloc_0);
			iLGenerator4.Emit(OpCodes.Ldloc_0);
			MethodBuilder methodBuilder5 = typeBuilder.DefineMethod("GetHashCode", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, CallingConventions.HasThis, typeof(int), Type.EmptyTypes);
			methodBuilder5.SetCustomAttribute(DebuggerHiddenAttributeBuilder);
			ILGenerator iLGenerator5 = methodBuilder5.GetILGenerator();
			iLGenerator5.DeclareLocal(typeof(int));
			if (properties.Count == 0)
			{
				iLGenerator5.Emit(OpCodes.Ldc_I4_0);
			}
			else
			{
				int num2 = 0;
				for (int j = 0; j < properties.Count; j++)
				{
					num2 = num2 * -1521134295 + array[j].Name.GetHashCode();
				}
				iLGenerator5.Emit(OpCodes.Ldc_I4, num2);
			}
			Label label = iLGenerator4.DefineLabel();
			for (int k = 0; k < properties.Count; k++)
			{
				string name3 = properties[k].Name;
				Type type2 = properties[k].Type;
				Type type3 = EqualityComparer.MakeGenericType(type2);
				MethodInfo method = type3.GetMethod("get_Default", BindingFlags.Static | BindingFlags.Public);
				MethodInfo method2 = type3.GetMethod("Equals", BindingFlags.Instance | BindingFlags.Public, null, new Type[2] { type2, type2 }, null);
				iLGenerator4.Emit(OpCodes.Brfalse, label);
				iLGenerator4.Emit(OpCodes.Call, method);
				iLGenerator4.Emit(OpCodes.Ldarg_0);
				iLGenerator4.Emit(OpCodes.Ldfld, array[k]);
				iLGenerator4.Emit(OpCodes.Ldloc_0);
				iLGenerator4.Emit(OpCodes.Ldfld, array[k]);
				iLGenerator4.Emit(OpCodes.Callvirt, method2);
				MethodInfo method3 = type3.GetMethod("GetHashCode", BindingFlags.Instance | BindingFlags.Public, null, new Type[1] { type2 }, null);
				iLGenerator5.Emit(OpCodes.Stloc_0);
				iLGenerator5.Emit(OpCodes.Ldc_I4, -1521134295);
				iLGenerator5.Emit(OpCodes.Ldloc_0);
				iLGenerator5.Emit(OpCodes.Mul);
				iLGenerator5.Emit(OpCodes.Call, method);
				iLGenerator5.Emit(OpCodes.Ldarg_0);
				iLGenerator5.Emit(OpCodes.Ldfld, array[k]);
				iLGenerator5.Emit(OpCodes.Callvirt, method3);
				iLGenerator5.Emit(OpCodes.Add);
				iLGenerator3.Emit(OpCodes.Ldloc_0);
				iLGenerator3.Emit(OpCodes.Ldstr, (k == 0) ? ("{ " + name3 + " = ") : (", " + name3 + " = "));
				iLGenerator3.Emit(OpCodes.Callvirt, StringBuilderAppendString);
				iLGenerator3.Emit(OpCodes.Pop);
				iLGenerator3.Emit(OpCodes.Ldloc_0);
				iLGenerator3.Emit(OpCodes.Ldarg_0);
				iLGenerator3.Emit(OpCodes.Ldfld, array[k]);
				iLGenerator3.Emit(OpCodes.Box, properties[k].Type);
				iLGenerator3.Emit(OpCodes.Callvirt, StringBuilderAppendObject);
				iLGenerator3.Emit(OpCodes.Pop);
			}
			if (createParameterCtor && properties.Any())
			{
				ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.HasThis, Type.EmptyTypes);
				constructorBuilder.SetCustomAttribute(DebuggerHiddenAttributeBuilder);
				ILGenerator iLGenerator6 = constructorBuilder.GetILGenerator();
				iLGenerator6.Emit(OpCodes.Ldarg_0);
				iLGenerator6.Emit(OpCodes.Call, ObjectCtor);
				iLGenerator6.Emit(OpCodes.Ret);
				Type[] parameterTypes = properties.Select((DynamicProperty p) => p.Type).ToArray();
				ConstructorBuilder constructorBuilder2 = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.HasThis, parameterTypes);
				constructorBuilder2.SetCustomAttribute(DebuggerHiddenAttributeBuilder);
				ILGenerator iLGenerator7 = constructorBuilder2.GetILGenerator();
				iLGenerator7.Emit(OpCodes.Ldarg_0);
				iLGenerator7.Emit(OpCodes.Call, ObjectCtor);
				for (int l = 0; l < properties.Count; l++)
				{
					constructorBuilder2.DefineParameter(l + 1, ParameterAttributes.None, properties[l].Name);
					iLGenerator7.Emit(OpCodes.Ldarg_0);
					if (l == 0)
					{
						iLGenerator7.Emit(OpCodes.Ldarg_1);
					}
					else if (l == 1)
					{
						iLGenerator7.Emit(OpCodes.Ldarg_2);
					}
					else if (l == 2)
					{
						iLGenerator7.Emit(OpCodes.Ldarg_3);
					}
					else if (l < 255)
					{
						iLGenerator7.Emit(OpCodes.Ldarg_S, (byte)(l + 1));
					}
					else
					{
						iLGenerator7.Emit(OpCodes.Ldarg, (short)(l + 1));
					}
					iLGenerator7.Emit(OpCodes.Stfld, array[l]);
				}
				iLGenerator7.Emit(OpCodes.Ret);
			}
			if (properties.Count == 0)
			{
				iLGenerator4.Emit(OpCodes.Ldnull);
				iLGenerator4.Emit(OpCodes.Ceq);
				iLGenerator4.Emit(OpCodes.Ldc_I4_0);
				iLGenerator4.Emit(OpCodes.Ceq);
			}
			else
			{
				iLGenerator4.Emit(OpCodes.Ret);
				iLGenerator4.MarkLabel(label);
				iLGenerator4.Emit(OpCodes.Ldc_I4_0);
			}
			iLGenerator4.Emit(OpCodes.Ret);
			iLGenerator5.Emit(OpCodes.Stloc_0);
			iLGenerator5.Emit(OpCodes.Ldloc_0);
			iLGenerator5.Emit(OpCodes.Ret);
			iLGenerator3.Emit(OpCodes.Ldloc_0);
			iLGenerator3.Emit(OpCodes.Ldstr, (properties.Count == 0) ? "{ }" : " }");
			iLGenerator3.Emit(OpCodes.Callvirt, StringBuilderAppendString);
			iLGenerator3.Emit(OpCodes.Pop);
			iLGenerator3.Emit(OpCodes.Ldloc_0);
			iLGenerator3.Emit(OpCodes.Callvirt, PredefinedMethodsHelper.ObjectToString);
			iLGenerator3.Emit(OpCodes.Ret);
			EmitEqualityOperators(typeBuilder, methodBuilder4);
			return typeBuilder.CreateType();
		}

		private static void EmitEqualityOperators(TypeBuilder typeBuilder, MethodBuilder equals)
		{
			MethodBuilder methodBuilder = typeBuilder.DefineMethod("op_Equality", MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.SpecialName, typeof(bool), new Type[2]
			{
				typeBuilder.AsType(),
				typeBuilder.AsType()
			});
			ILGenerator iLGenerator = methodBuilder.GetILGenerator();
			Label label = iLGenerator.DefineLabel();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Brfalse_S, label);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Brfalse_S, label);
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Callvirt, equals);
			iLGenerator.Emit(OpCodes.Ret);
			iLGenerator.MarkLabel(label);
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Call, typeof(object).GetMethod("ReferenceEquals"));
			iLGenerator.Emit(OpCodes.Ret);
			ILGenerator iLGenerator2 = typeBuilder.DefineMethod("op_Inequality", MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.SpecialName, typeof(bool), new Type[2]
			{
				typeBuilder.AsType(),
				typeBuilder.AsType()
			}).GetILGenerator();
			iLGenerator2.Emit(OpCodes.Ldarg_0);
			iLGenerator2.Emit(OpCodes.Ldarg_1);
			iLGenerator2.Emit(OpCodes.Call, methodBuilder);
			iLGenerator2.Emit(OpCodes.Ldc_I4_0);
			iLGenerator2.Emit(OpCodes.Ceq);
			iLGenerator2.Emit(OpCodes.Ret);
		}

		private static string GenerateKey(IEnumerable<DynamicProperty> dynamicProperties, bool createParameterCtor)
		{
			return string.Join("|", dynamicProperties.Select((DynamicProperty p) => Escape(p.Name) + "~" + p.Type.FullName).ToArray()) + "_" + (createParameterCtor ? "c" : string.Empty);
		}

		private static string Escape(string str)
		{
			str = str.Replace("\\", "\\\\");
			str = str.Replace("|", "\\|");
			return str;
		}

		internal static void ClearGeneratedTypes()
		{
			lock (GeneratedTypes)
			{
				GeneratedTypes.Clear();
			}
		}
	}
	public static class DynamicEnumerableAsyncExtensions
	{
		private static readonly MethodInfo ToListAsyncGenericMethod;

		static DynamicEnumerableAsyncExtensions()
		{
			ToListAsyncGenericMethod = typeof(DynamicEnumerableAsyncExtensions).GetTypeInfo().GetDeclaredMethods("ToListAsync").First((MethodInfo x) => x.IsGenericMethod);
		}

		public static async Task<dynamic[]> ToDynamicArrayAsync(this IEnumerable source, Type type, CancellationToken cancellationToken = default(CancellationToken))
		{
			return (await Check.NotNull(source, "source").ToDynamicListAsync(Check.NotNull(type, "type"), cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToArray();
		}

		public static async Task<dynamic[]> ToDynamicArrayAsync(this IEnumerable source, CancellationToken cancellationToken = default(CancellationToken))
		{
			return (await ToListAsync<object>(Check.NotNull(source, "source"), cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToArray();
		}

		public static async Task<T[]> ToDynamicArrayAsync<T>(this IEnumerable source, CancellationToken cancellationToken = default(CancellationToken))
		{
			return (await ToListAsync<T>(Check.NotNull(source, "source"), cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToArray();
		}

		public static async Task<List<dynamic>> ToDynamicListAsync(this IEnumerable source, Type type, CancellationToken cancellationToken = default(CancellationToken))
		{
			Check.NotNull(source, "source");
			Check.NotNull(type, "type");
			Task task = (Task)ToListAsyncGenericMethod.MakeGenericMethod(type).Invoke(source, new object[2] { source, cancellationToken });
			await task.ConfigureAwait(continueOnCapturedContext: false);
			return ((IList)task.GetType().GetProperty("Result").GetValue(task)).Cast<object>().ToList();
		}

		public static Task<List<dynamic>> ToDynamicListAsync(this IEnumerable source, CancellationToken cancellationToken = default(CancellationToken))
		{
			return ToListAsync<object>(Check.NotNull(source, "source"), cancellationToken);
		}

		public static Task<List<T>> ToDynamicListAsync<T>(this IEnumerable source, CancellationToken cancellationToken = default(CancellationToken))
		{
			return ToListAsync<T>(Check.NotNull(source, "source"), cancellationToken);
		}

		private static async Task<List<T>> ToListAsync<T>(IEnumerable source, CancellationToken cancellationToken)
		{
			if (source is IEnumerable<T> source2)
			{
				return source2.ToList();
			}
			return source.Cast<T>().ToList();
		}
	}
	public static class DynamicEnumerableExtensions
	{
		private static readonly MethodInfo ToDynamicArrayGenericMethod;

		static DynamicEnumerableExtensions()
		{
			ToDynamicArrayGenericMethod = typeof(DynamicEnumerableExtensions).GetTypeInfo().GetDeclaredMethods("ToDynamicArray").First((MethodInfo x) => x.IsGenericMethod);
		}

		public static dynamic[] ToDynamicArray(this IEnumerable source)
		{
			return CastToArray<object>(Check.NotNull(source, "source"));
		}

		public static T[] ToDynamicArray<T>(this IEnumerable source)
		{
			return CastToArray<T>(Check.NotNull(source, "source"));
		}

		public static dynamic[] ToDynamicArray(this IEnumerable source, Type type)
		{
			Check.NotNull(source, "source");
			Check.NotNull(type, "type");
			return CastToArray<object>((IEnumerable)ToDynamicArrayGenericMethod.MakeGenericMethod(type).Invoke(source, new object[1] { source }));
		}

		public static List<dynamic> ToDynamicList(this IEnumerable source)
		{
			return CastToList<object>(Check.NotNull(source, "source"));
		}

		public static List<dynamic> ToDynamicList(this IEnumerable source, Type type)
		{
			return Check.NotNull(source, "source").ToDynamicArray(Check.NotNull(type, "type")).ToList();
		}

		public static List<T> ToDynamicList<T>(this IEnumerable source)
		{
			return CastToList<T>(Check.NotNull(source, "source"));
		}

		internal static T[] CastToArray<T>(IEnumerable source)
		{
			return source.Cast<T>().ToArray();
		}

		internal static List<T> CastToList<T>(IEnumerable source)
		{
			return source.Cast<T>().ToList();
		}
	}
	public static class DynamicExpressionParser
	{
		public static LambdaExpression ParseLambda(ParsingConfig? parsingConfig, bool createParameterCtor, Type? resultType, string expression, params object?[] values)
		{
			Check.NotEmpty(expression, "expression");
			return Expression.Lambda(new ExpressionParser(new ParameterExpression[0], expression, values, parsingConfig).Parse(resultType, createParameterCtor));
		}

		public static LambdaExpression ParseLambda(Type delegateType, ParsingConfig? parsingConfig, bool createParameterCtor, Type? resultType, string expression, params object?[] values)
		{
			Check.NotEmpty(expression, "expression");
			ExpressionParser expressionParser = new ExpressionParser(new ParameterExpression[0], expression, values, parsingConfig);
			return Expression.Lambda(delegateType, expressionParser.Parse(resultType, createParameterCtor));
		}

		public static Expression<Func<TResult>> ParseLambda<TResult>(ParsingConfig? parsingConfig, bool createParameterCtor, string expression, params object?[] values)
		{
			return (Expression<Func<TResult>>)ParseLambda(parsingConfig, createParameterCtor, typeof(TResult), expression, values);
		}

		public static Expression<Func<TResult>> ParseLambda<TResult>(Type delegateType, ParsingConfig? parsingConfig, bool createParameterCtor, string expression, params object?[] values)
		{
			Check.NotNull(delegateType, "delegateType");
			return (Expression<Func<TResult>>)ParseLambda(delegateType, parsingConfig, createParameterCtor, typeof(TResult), expression, values);
		}

		public static LambdaExpression ParseLambda(ParsingConfig? parsingConfig, bool createParameterCtor, ParameterExpression[] parameters, Type? resultType, string expression, params object?[]? values)
		{
			return ParseLambda(null, parsingConfig, createParameterCtor, parameters, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(Type? delegateType, ParsingConfig? parsingConfig, bool createParameterCtor, ParameterExpression[] parameters, Type? resultType, string expression, params object?[]? values)
		{
			Check.HasNoNulls(parameters, "parameters");
			Check.NotEmpty(expression, "expression");
			ExpressionParser expressionParser = new ExpressionParser(parameters, expression, values, parsingConfig);
			Expression expression2 = expressionParser.Parse(resultType, createParameterCtor);
			if (expression2 is LambdaExpression result)
			{
				return result;
			}
			if (parsingConfig != null && parsingConfig.RenameParameterExpression && parameters.Length == 1)
			{
				expression2 = new ParameterExpressionRenamer(expressionParser.LastLambdaItName).Rename(expression2, out ParameterExpression parameterExpression);
				if (!(delegateType == null))
				{
					return Expression.Lambda(delegateType, expression2, parameterExpression);
				}
				return Expression.Lambda(expression2, parameterExpression);
			}
			if (!(delegateType == null))
			{
				return Expression.Lambda(delegateType, expression2, parameters);
			}
			return Expression.Lambda(expression2, parameters);
		}

		public static Expression<Func<TResult>> ParseLambda<TResult>(ParsingConfig? parsingConfig, bool createParameterCtor, ParameterExpression[] parameters, string expression, params object?[] values)
		{
			return (Expression<Func<TResult>>)ParseLambda(parsingConfig, createParameterCtor, parameters, typeof(TResult), expression, values);
		}

		public static Expression<Func<TResult>> ParseLambda<TResult>(Type delegateType, ParsingConfig? parsingConfig, bool createParameterCtor, ParameterExpression[] parameters, string expression, params object?[] values)
		{
			Check.NotNull(delegateType, "delegateType");
			return (Expression<Func<TResult>>)ParseLambda(delegateType, parsingConfig, createParameterCtor, parameters, typeof(TResult), expression, values);
		}

		public static LambdaExpression ParseLambda(bool createParameterCtor, Type itType, Type? resultType, string expression, params object?[] values)
		{
			Check.NotNull(itType, "itType");
			Check.NotEmpty(expression, "expression");
			return ParseLambda(createParameterCtor, new ParameterExpression[1] { ParameterExpressionHelper.CreateParameterExpression(itType, string.Empty) }, resultType, expression, values);
		}

		public static Expression<Func<T, TResult>> ParseLambda<T, TResult>(ParsingConfig? parsingConfig, bool createParameterCtor, string expression, params object?[] values)
		{
			Check.NotEmpty(expression, "expression");
			return (Expression<Func<T, TResult>>)ParseLambda(parsingConfig, createParameterCtor, new ParameterExpression[1] { ParameterExpressionHelper.CreateParameterExpression(typeof(T), string.Empty, parsingConfig?.RenameEmptyParameterExpressionNames ?? false) }, typeof(TResult), expression, values);
		}

		public static Expression<Func<T, TResult>> ParseLambda<T, TResult>(Type delegateType, ParsingConfig? parsingConfig, bool createParameterCtor, string expression, params object?[] values)
		{
			Check.NotNull(delegateType, "delegateType");
			Check.NotEmpty(expression, "expression");
			return (Expression<Func<T, TResult>>)ParseLambda(delegateType, parsingConfig, createParameterCtor, new ParameterExpression[1] { ParameterExpressionHelper.CreateParameterExpression(typeof(T), string.Empty, parsingConfig?.RenameEmptyParameterExpressionNames ?? false) }, typeof(TResult), expression, values);
		}

		public static LambdaExpression ParseLambda(ParsingConfig? parsingConfig, Type? resultType, string expression, params object?[] values)
		{
			return ParseLambda(parsingConfig, createParameterCtor: true, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(Type delegateType, ParsingConfig? parsingConfig, Type? resultType, string expression, params object?[] values)
		{
			Check.NotNull(delegateType, "delegateType");
			return ParseLambda(delegateType, parsingConfig, createParameterCtor: true, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(Type? resultType, string expression, params object?[] values)
		{
			Check.NotEmpty(expression, "expression");
			return ParseLambda(null, createParameterCtor: true, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(Type itType, Type? resultType, string expression, params object?[] values)
		{
			Check.NotNull(itType, "itType");
			return ParseLambda(createParameterCtor: true, itType, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(ParsingConfig? parsingConfig, Type itType, Type? resultType, string expression, params object?[] values)
		{
			Check.NotNull(itType, "itType");
			return ParseLambda(parsingConfig, createParameterCtor: true, itType, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(Type delegateType, ParsingConfig? parsingConfig, Type itType, Type? resultType, string expression, params object?[] values)
		{
			Check.NotNull(delegateType, "delegateType");
			Check.NotNull(itType, "itType");
			return ParseLambda(delegateType, parsingConfig, createParameterCtor: true, itType, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(ParsingConfig? parsingConfig, bool createParameterCtor, Type itType, Type? resultType, string expression, params object?[]? values)
		{
			Check.NotNull(itType, "itType");
			Check.NotEmpty(expression, "expression");
			return ParseLambda(parsingConfig, createParameterCtor, new ParameterExpression[1] { ParameterExpressionHelper.CreateParameterExpression(itType, string.Empty, parsingConfig?.RenameEmptyParameterExpressionNames ?? false) }, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(Type delegateType, ParsingConfig? parsingConfig, bool createParameterCtor, Type itType, Type? resultType, string expression, params object?[] values)
		{
			Check.NotNull(delegateType, "delegateType");
			Check.NotNull(itType, "itType");
			Check.NotEmpty(expression, "expression");
			return ParseLambda(delegateType, parsingConfig, createParameterCtor, new ParameterExpression[1] { ParameterExpressionHelper.CreateParameterExpression(itType, string.Empty, parsingConfig?.RenameEmptyParameterExpressionNames ?? false) }, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(ParameterExpression[] parameters, Type? resultType, string expression, params object?[] values)
		{
			return ParseLambda(null, createParameterCtor: true, parameters, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(Type delegateType, ParameterExpression[] parameters, Type? resultType, string expression, params object?[] values)
		{
			Check.NotNull(delegateType, "delegateType");
			return ParseLambda(delegateType, null, createParameterCtor: true, parameters, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(ParsingConfig? parsingConfig, ParameterExpression[] parameters, Type? resultType, string expression, params object?[] values)
		{
			return ParseLambda(parsingConfig, createParameterCtor: true, parameters, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(Type delegateType, ParsingConfig? parsingConfig, ParameterExpression[] parameters, Type? resultType, string expression, params object?[] values)
		{
			Check.NotNull(delegateType, "delegateType");
			return ParseLambda(delegateType, parsingConfig, createParameterCtor: true, parameters, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(bool createParameterCtor, ParameterExpression[] parameters, Type? resultType, string expression, params object?[] values)
		{
			return ParseLambda(null, createParameterCtor, parameters, resultType, expression, values);
		}
	}
	internal class DynamicGetMemberBinder : GetMemberBinder
	{
		private static readonly MethodInfo DynamicGetMemberMethod = typeof(DynamicGetMemberBinder).GetMethod("GetDynamicMember");

		private readonly ConcurrentDictionary<Tuple<Type, string, bool>, DynamicMetaObject> _metaObjectCache = new ConcurrentDictionary<Tuple<Type, string, bool>, DynamicMetaObject>();

		internal DynamicGetMemberBinder(string name, ParsingConfig? config)
			: base(name, config == null || !config.IsCaseSensitive)
		{
		}

		public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject? errorSuggestion)
		{
			DynamicMetaObject target2 = target;
			MethodCallExpression methodCallExpression = Expression.Call(DynamicGetMemberMethod, target2.Expression, Expression.Constant(base.Name), Expression.Constant(base.IgnoreCase));
			if (target2.Value is IDynamicMetaObjectProvider)
			{
				Tuple<Type, string, bool> key = new Tuple<Type, string, bool>(target2.LimitType, base.Name, base.IgnoreCase);
				return _metaObjectCache.GetOrAdd(key, delegate
				{
					BindingRestrictions typeRestriction = BindingRestrictions.GetTypeRestriction(target2.Expression, target2.LimitType);
					return new DynamicMetaObject(methodCallExpression, typeRestriction, target2.Value);
				});
			}
			return DynamicMetaObject.Create(target2.Value, methodCallExpression);
		}

		public static object? GetDynamicMember(object value, string name, bool ignoreCase)
		{
			if (value == null)
			{
				throw new InvalidOperationException();
			}
			if (value is IDictionary<string, object> dictionary)
			{
				return dictionary[name];
			}
			if (value is IDictionary dictionary2)
			{
				return dictionary2[name];
			}
			BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
			if (ignoreCase)
			{
				bindingFlags |= BindingFlags.IgnoreCase;
			}
			Type type = value.GetType();
			PropertyInfo? property = type.GetProperty(name, bindingFlags);
			if (property == null)
			{
				throw new InvalidOperationException($"Unable to find property '{name}' on type '{type}'.");
			}
			return property.GetValue(value, null);
		}
	}
	internal struct DynamicOrdering
	{
		public Expression Selector { get; }

		public bool Ascending { get; }

		public string MethodName { get; }

		public DynamicOrdering(Expression selector, bool ascending, string methodName)
		{
			Selector = selector;
			Ascending = ascending;
			MethodName = methodName;
		}
	}
	public class DynamicProperty
	{
		public string Name { get; }

		public Type Type { get; }

		public DynamicProperty(string name, Type type)
		{
			Name = name;
			Type = type;
		}
	}
	public class DynamicPropertyWithValue : DynamicProperty
	{
		public object? Value { get; }

		public DynamicPropertyWithValue(string name, object? value)
			: base(name, value?.GetType() ?? typeof(object))
		{
			Value = value;
		}
	}
	public static class DynamicQueryableExtensions
	{
		[CompilerGenerated]
		private sealed class <AsDynamicEnumerable>d__16 : IEnumerable<object>, IEnumerable, IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			private int <>l__initialThreadId;

			private IQueryable source;

			public IQueryable <>3__source;

			private IEnumerator <>7__wrap1;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <AsDynamicEnumerable>d__16(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				int num = <>1__state;
				if (num == -3 || num == 1)
				{
					try
					{
					}
					finally
					{
						<>m__Finally1();
					}
				}
				<>7__wrap1 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				try
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						<>7__wrap1 = source.GetEnumerator();
						<>1__state = -3;
						break;
					case 1:
						<>1__state = -3;
						break;
					}
					if (<>7__wrap1.MoveNext())
					{
						object current = <>7__wrap1.Current;
						<>2__current = current;
						<>1__state = 1;
						return true;
					}
					<>m__Finally1();
					<>7__wrap1 = null;
					return false;
				}
				catch
				{
					//try-fault
					((IDisposable)this).Dispose();
					throw;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			private void <>m__Finally1()
			{
				<>1__state = -1;
				if (<>7__wrap1 is IDisposable disposable)
				{
					disposable.Dispose();
				}
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			IEnumerator<dynamic> IEnumerable<object>.GetEnumerator()
			{
				<AsDynamicEnumerable>d__16 <AsDynamicEnumerable>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					<AsDynamicEnumerable>d__ = this;
				}
				else
				{
					<AsDynamicEnumerable>d__ = new <AsDynamicEnumerable>d__16(0);
				}
				<AsDynamicEnumerable>d__.source = <>3__source;
				return <AsDynamicEnumerable>d__;
			}

			[DebuggerHidden]
			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<object>)this).GetEnumerator();
			}
		}

		private static readonly TraceSource TraceSource = new TraceSource("DynamicQueryableExtensions");

		private static readonly MethodInfo _AllPredicate = QueryableMethodFinder.GetMethod("All", 1);

		private static readonly MethodInfo _any = QueryableMethodFinder.GetMethod("Any");

		private static readonly MethodInfo _anyPredicate = QueryableMethodFinder.GetMethod("Any", 1);

		private static readonly MethodInfo _cast = QueryableMethodFinder.GetGenericMethod("Cast");

		private static readonly MethodInfo _count = QueryableMethodFinder.GetMethod("Count");

		private static readonly MethodInfo _countPredicate = QueryableMethodFinder.GetMethod("Count", 1);

		private static readonly MethodInfo _defaultIfEmpty = QueryableMethodFinder.GetMethod("DefaultIfEmpty");

		private static readonly MethodInfo _defaultIfEmptyWithParam = QueryableMethodFinder.GetMethod("DefaultIfEmpty", 1);

		private static readonly MethodInfo _distinct = QueryableMethodFinder.GetMethod("Distinct");

		private static readonly MethodInfo _first = QueryableMethodFinder.GetMethod("First");

		private static readonly MethodInfo _firstPredicate = QueryableMethodFinder.GetMethod("First", 1);

		private static readonly MethodInfo _firstOrDefault = QueryableMethodFinder.GetMethod("FirstOrDefault");

		private static readonly MethodInfo _firstOrDefaultPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("FirstOrDefault");

		private static readonly MethodInfo _last = QueryableMethodFinder.GetMethod("Last");

		private static readonly MethodInfo _lastPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("Last");

		private static readonly MethodInfo _lastDefault = QueryableMethodFinder.GetMethod("LastOrDefault");

		private static readonly MethodInfo _lastDefaultPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("LastOrDefault");

		private static readonly MethodInfo _longCount = QueryableMethodFinder.GetMethod("LongCount");

		private static readonly MethodInfo _longCountPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("LongCount");

		private static readonly MethodInfo _max = QueryableMethodFinder.GetMethod("Max");

		private static readonly MethodInfo _maxPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("Max");

		private static readonly MethodInfo _min = QueryableMethodFinder.GetMethod("Min");

		private static readonly MethodInfo _minPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("Min");

		private static readonly MethodInfo _ofType = QueryableMethodFinder.GetGenericMethod("OfType");

		private static readonly MethodInfo _singlePredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("Single");

		private static readonly MethodInfo _singleDefaultPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("SingleOrDefault");

		private static readonly MethodInfo _skip = QueryableMethodFinder.GetMethod("Skip", 1);

		private static readonly MethodInfo _skipWhilePredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("SkipWhile");

		private static readonly MethodInfo _take = QueryableMethodFinder.GetMethodWithIntParameter("Take");

		private static readonly MethodInfo _takeWhilePredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("TakeWhile");

		private static Expression OptimizeExpression(Expression expression)
		{
			if (ExtensibilityPoint.QueryOptimizer != null)
			{
				Expression expression2 = ExtensibilityPoint.QueryOptimizer(expression);
				if (expression2 != expression)
				{
					TraceSource.TraceEvent(TraceEventType.Verbose, 0, "Expression before : {0}", expression);
					TraceSource.TraceEvent(TraceEventType.Verbose, 0, "Expression after  : {0}", expression2);
				}
				return expression2;
			}
			return expression;
		}

		public static object Aggregate(this IQueryable source, string function, string member)
		{
			string function2 = function;
			Check.NotNull(source, "source");
			Check.NotEmpty(function2, "function");
			Check.NotEmpty(member, "member");
			PropertyInfo property = source.ElementType.GetProperty(member);
			ParameterExpression parameterExpression = ParameterExpressionHelper.CreateParameterExpression(source.ElementType, "s");
			Expression expression = Expression.Lambda(Expression.MakeMemberAccess(parameterExpression, property), parameterExpression);
			MethodInfo[] source2 = (from x in typeof(Queryable).GetMethods()
				where x.Name == function2 && x.IsGenericMethod
				select x).ToArray();
			MethodInfo methodInfo = source2.SingleOrDefault(delegate(MethodInfo m)
			{
				ParameterInfo parameterInfo = m.GetParameters().LastOrDefault();
				return parameterInfo != null && TypeHelper.GetUnderlyingType(parameterInfo.ParameterType) == property.PropertyType;
			});
			if (methodInfo != null)
			{
				return source.Provider.Execute(Expression.Call(null, methodInfo.MakeGenericMethod(source.ElementType), new Expression[2]
				{
					source.Expression,
					Expression.Quote(expression)
				}));
			}
			methodInfo = source2.SingleOrDefault((MethodInfo m) => m.Name == function2 && m.GetGenericArguments().Length == 2);
			return source.Provider.Execute(Expression.Call(null, methodInfo.MakeGenericMethod(source.ElementType, property.PropertyType), new Expression[2]
			{
				source.Expression,
				Expression.Quote(expression)
			}));
		}

		public static bool All(this IQueryable source, string predicate, params object?[] args)
		{
			return source.All(ParsingConfig.Default, predicate, args);
		}

		public static bool All(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute<bool>(_AllPredicate, source, Expression.Quote(expression));
		}

		public static bool Any(this IQueryable source)
		{
			return Execute<bool>(_any, Check.NotNull(source, "source"));
		}

		public static bool Any(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute<bool>(_anyPredicate, source, expression);
		}

		public static bool Any(this IQueryable source, string predicate, params object?[] args)
		{
			return source.Any(ParsingConfig.Default, predicate, args);
		}

		public static bool Any(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			Check.NotNull(lambda, "lambda");
			return Execute<bool>(_anyPredicate, source, lambda);
		}

		public static double Average(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute<double>(QueryableMethodFinder.GetMethod("Average", source.ElementType, typeof(double)), source);
		}

		public static double Average(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return source.Average(lambda);
		}

		public static double Average(this IQueryable source, string predicate, params object?[] args)
		{
			return source.Average(ParsingConfig.Default, predicate, args);
		}

		public static double Average(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			Check.NotNull(lambda, "lambda");
			return Execute<double>(QueryableMethodFinder.GetMethod("Average", lambda.GetReturnType(), typeof(double), 1), source, lambda);
		}

		[IteratorStateMachine(typeof(<AsDynamicEnumerable>d__16))]
		public static IEnumerable<dynamic> AsDynamicEnumerable(this IQueryable source)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <AsDynamicEnumerable>d__16(-2)
			{
				<>3__source = source
			};
		}

		public static IQueryable Cast(this IQueryable source, Type type)
		{
			Check.NotNull(source, "source");
			Check.NotNull(type, "type");
			Expression expression = OptimizeExpression(Expression.Call(null, _cast.MakeGenericMethod(type), source.Expression));
			return source.Provider.CreateQuery(expression);
		}

		public static IQueryable Cast(this IQueryable source, ParsingConfig config, string typeName)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(typeName, "typeName");
			if (!new TypeFinder(config, new KeywordsHelper(config)).TryFindTypeByName(typeName, null, forceUseCustomTypeProvider: true, out Type type))
			{
				throw new ParseException(string.Format(CultureInfo.CurrentCulture, "Type '{0}' not found", typeName));
			}
			return source.Cast(type);
		}

		public static IQueryable Cast(this IQueryable source, string typeName)
		{
			return source.Cast(ParsingConfig.Default, typeName);
		}

		public static int Count(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute<int>(_count, source);
		}

		public static int Count(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute<int>(_countPredicate, source, expression);
		}

		public static int Count(this IQueryable source, string predicate, params object?[] args)
		{
			return source.Count(ParsingConfig.Default, predicate, args);
		}

		public static int Count(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			Check.NotNull(lambda, "lambda");
			return Execute<int>(_countPredicate, source, lambda);
		}

		public static IQueryable DefaultIfEmpty(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return CreateQuery(_defaultIfEmpty, source);
		}

		public static IQueryable DefaultIfEmpty(this IQueryable source, object? defaultValue)
		{
			Check.NotNull(source, "source");
			return CreateQuery(_defaultIfEmptyWithParam, source, Expression.Constant(defaultValue));
		}

		public static IQueryable Distinct(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return CreateQuery(_distinct, source);
		}

		public static dynamic First(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute(_first, source);
		}

		public static dynamic First(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute(_firstPredicate, source, expression);
		}

		public static dynamic First(this IQueryable source, string predicate, params object?[] args)
		{
			return source.First(ParsingConfig.Default, predicate, args);
		}

		public static dynamic First(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			return Execute(_firstPredicate, source, lambda);
		}

		public static dynamic FirstOrDefault(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute(_firstOrDefault, source);
		}

		public static dynamic FirstOrDefault(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute(_firstOrDefaultPredicate, source, expression);
		}

		public static dynamic FirstOrDefault(this IQueryable source, string predicate, params object?[] args)
		{
			return source.FirstOrDefault(ParsingConfig.Default, predicate, args);
		}

		public static dynamic FirstOrDefault(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			return Execute(_firstOrDefaultPredicate, source, lambda);
		}

		public static IQueryable GroupBy(this IQueryable source, ParsingConfig config, string keySelector, string resultSelector, object[] args)
		{
			return InternalGroupBy(source, config, keySelector, resultSelector, null, args);
		}

		public static IQueryable GroupBy(this IQueryable source, ParsingConfig config, string keySelector, string resultSelector, IEqualityComparer? equalityComparer, object[]? args)
		{
			return InternalGroupBy(source, config, keySelector, resultSelector, equalityComparer, args);
		}

		internal static IQueryable InternalGroupBy(IQueryable source, ParsingConfig config, string keySelector, string resultSelector, IEqualityComparer? equalityComparer, object[]? args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(keySelector, "keySelector");
			Check.NotEmpty(resultSelector, "resultSelector");
			Check.Args(args, "args");
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source);
			LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, keySelector, args);
			LambdaExpression lambdaExpression2 = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, resultSelector, args);
			Expression expression;
			if (equalityComparer == null)
			{
				expression = OptimizeExpression(Expression.Call(typeof(Queryable), "GroupBy", new Type[3]
				{
					source.ElementType,
					lambdaExpression.Body.Type,
					lambdaExpression2.Body.Type
				}, source.Expression, Expression.Quote(lambdaExpression), Expression.Quote(lambdaExpression2)));
			}
			else
			{
				Type type = typeof(IEqualityComparer<>).MakeGenericType(lambdaExpression.Body.Type);
				expression = OptimizeExpression(Expression.Call(typeof(Queryable), "GroupBy", new Type[3]
				{
					source.ElementType,
					lambdaExpression.Body.Type,
					lambdaExpression2.Body.Type
				}, source.Expression, Expression.Quote(lambdaExpression), Expression.Quote(lambdaExpression2), Expression.Constant(equalityComparer, type)));
			}
			return source.Provider.CreateQuery(expression);
		}

		public static IQueryable GroupBy(this IQueryable source, string keySelector, string resultSelector, object[] args)
		{
			return source.GroupBy(ParsingConfig.Default, keySelector, resultSelector, args);
		}

		public static IQueryable GroupBy(this IQueryable source, string keySelector, string resultSelector, IEqualityComparer equalityComparer, object[] args)
		{
			return source.GroupBy(ParsingConfig.Default, keySelector, resultSelector, equalityComparer, args);
		}

		public static IQueryable GroupBy(this IQueryable source, ParsingConfig config, string keySelector, string resultSelector)
		{
			return source.GroupBy(config, keySelector, resultSelector, null, null);
		}

		public static IQueryable GroupBy(this IQueryable source, string keySelector, string resultSelector)
		{
			return source.GroupBy(ParsingConfig.Default, keySelector, resultSelector);
		}

		public static IQueryable GroupBy(this IQueryable source, ParsingConfig config, string keySelector, string resultSelector, IEqualityComparer equalityComparer)
		{
			return InternalGroupBy(source, config, keySelector, resultSelector, equalityComparer, null);
		}

		public static IQueryable GroupBy(this IQueryable source, string keySelector, string resultSelector, IEqualityComparer equalityComparer)
		{
			return source.GroupBy(ParsingConfig.Default, keySelector, resultSelector, equalityComparer);
		}

		public static IQueryable GroupBy(this IQueryable source, ParsingConfig config, string keySelector, params object[]? args)
		{
			return InternalGroupBy(source, config, keySelector, null, args);
		}

		public static IQueryable GroupBy(this IQueryable source, ParsingConfig config, string keySelector, IEqualityComparer equalityComparer, params object[]? args)
		{
			return InternalGroupBy(source, config, keySelector, equalityComparer, args);
		}

		internal static IQueryable InternalGroupBy(IQueryable source, ParsingConfig config, string keySelector, IEqualityComparer? equalityComparer, params object[]? args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(keySelector, "keySelector");
			Check.Args(args, "args");
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source);
			LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, keySelector, args);
			Expression expression;
			if (equalityComparer == null)
			{
				expression = OptimizeExpression(Expression.Call(typeof(Queryable), "GroupBy", new Type[2]
				{
					source.ElementType,
					lambdaExpression.Body.Type
				}, source.Expression, Expression.Quote(lambdaExpression)));
			}
			else
			{
				Type type = typeof(IEqualityComparer<>).MakeGenericType(lambdaExpression.Body.Type);
				expression = OptimizeExpression(Expression.Call(typeof(Queryable), "GroupBy", new Type[2]
				{
					source.ElementType,
					lambdaExpression.Body.Type
				}, source.Expression, Expression.Quote(lambdaExpression), Expression.Constant(equalityComparer, type)));
			}
			return source.Provider.CreateQuery(expression);
		}

		public static IQueryable GroupBy(this IQueryable source, string keySelector, params object[]? args)
		{
			return source.GroupBy(ParsingConfig.Default, keySelector, args);
		}

		public static IQueryable GroupBy(this IQueryable source, string keySelector, IEqualityComparer equalityComparer, params object[]? args)
		{
			return source.GroupBy(ParsingConfig.Default, keySelector, equalityComparer, args);
		}

		public static IEnumerable<GroupResult> GroupByMany<TElement>(this IEnumerable<TElement> source, ParsingConfig config, params string[] keySelectors)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.HasNoNulls(keySelectors, "keySelectors");
			List<Func<TElement, object>> list = new List<Func<TElement, object>>(keySelectors.Length);
			foreach (string expression in keySelectors)
			{
				LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, true, typeof(TElement), null, expression);
				list.Add((Func<TElement, object>)EnsureLambdaExpressionReturnsObject(lambdaExpression).Compile());
			}
			return GroupByManyInternal(source, list.ToArray(), 0);
		}

		public static IEnumerable<GroupResult> GroupByMany<TElement>(this IEnumerable<TElement> source, params string[] keySelectors)
		{
			return source.GroupByMany(ParsingConfig.Default, keySelectors);
		}

		public static IEnumerable<GroupResult> GroupByMany<TElement>(this IEnumerable<TElement> source, params Func<TElement, object>[] keySelectors)
		{
			Check.NotNull(source, "source");
			Check.HasNoNulls(keySelectors, "keySelectors");
			return GroupByManyInternal(source, keySelectors, 0);
		}

		private static IEnumerable<GroupResult> GroupByManyInternal<TElement>(IEnumerable<TElement> source, Func<TElement, object>[] keySelectors, int currentSelector)
		{
			Func<TElement, object>[] keySelectors2 = keySelectors;
			if (currentSelector >= keySelectors2.Length)
			{
				return null;
			}
			Func<TElement, object> keySelector = keySelectors2[currentSelector];
			return from g in source.GroupBy(keySelector)
				select new GroupResult
				{
					Key = g.Key,
					Count = g.Count(),
					Items = g,
					Subgroups = GroupByManyInternal(g, keySelectors2, currentSelector + 1)
				};
		}

		public static IQueryable GroupJoin(this IQueryable outer, ParsingConfig config, IEnumerable inner, string outerKeySelector, string innerKeySelector, string resultSelector, params object?[] args)
		{
			Check.NotNull(outer, "outer");
			Check.NotNull(config, "config");
			Check.NotNull(inner, "inner");
			Check.NotEmpty(outerKeySelector, "outerKeySelector");
			Check.NotEmpty(innerKeySelector, "innerKeySelector");
			Check.NotEmpty(resultSelector, "resultSelector");
			Check.Args(args, "args");
			Type elementType = outer.ElementType;
			Type elementType2 = inner.AsQueryable().ElementType;
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, outer);
			LambdaExpression outerSelectorLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, elementType, null, outerKeySelector, args);
			LambdaExpression innerSelectorLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, elementType2, null, innerKeySelector, args);
			CheckOuterAndInnerTypes(config, createParameterCtor, elementType, elementType2, outerKeySelector, innerKeySelector, ref outerSelectorLambda, ref innerSelectorLambda, args);
			ParameterExpression[] parameters = new ParameterExpression[2]
			{
				ParameterExpressionHelper.CreateParameterExpression(elementType, "outer"),
				ParameterExpressionHelper.CreateParameterExpression(typeof(IEnumerable<>).MakeGenericType(elementType2), "inner")
			};
			LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, parameters, null, resultSelector, args);
			return outer.Provider.CreateQuery(Expression.Call(typeof(Queryable), "GroupJoin", new Type[4]
			{
				outer.ElementType,
				elementType2,
				outerSelectorLambda.Body.Type,
				lambdaExpression.Body.Type
			}, outer.Expression, inner.AsQueryable().Expression, Expression.Quote(outerSelectorLambda), Expression.Quote(innerSelectorLambda), Expression.Quote(lambdaExpression)));
		}

		public static IQueryable GroupJoin(this IQueryable outer, IEnumerable inner, string outerKeySelector, string innerKeySelector, string resultSelector, params object?[] args)
		{
			return outer.GroupJoin(ParsingConfig.Default, inner, outerKeySelector, innerKeySelector, resultSelector, args);
		}

		public static IQueryable Join(this IQueryable outer, ParsingConfig config, IEnumerable inner, string outerKeySelector, string innerKeySelector, string resultSelector, params object?[] args)
		{
			Check.NotNull(outer, "outer");
			Check.NotNull(config, "config");
			Check.NotNull(inner, "inner");
			Check.NotEmpty(outerKeySelector, "outerKeySelector");
			Check.NotEmpty(innerKeySelector, "innerKeySelector");
			Check.NotEmpty(resultSelector, "resultSelector");
			Check.Args(args, "args");
			Type elementType = outer.ElementType;
			Type elementType2 = inner.AsQueryable().ElementType;
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, outer);
			LambdaExpression outerSelectorLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, elementType, null, outerKeySelector, args);
			LambdaExpression innerSelectorLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, elementType2, null, innerKeySelector, args);
			CheckOuterAndInnerTypes(config, createParameterCtor, elementType, elementType2, outerKeySelector, innerKeySelector, ref outerSelectorLambda, ref innerSelectorLambda, args);
			ParameterExpression[] parameters = new ParameterExpression[2]
			{
				ParameterExpressionHelper.CreateParameterExpression(elementType, "outer"),
				ParameterExpressionHelper.CreateParameterExpression(elementType2, "inner")
			};
			LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, parameters, null, resultSelector, args);
			Expression expression = OptimizeExpression(Expression.Call(typeof(Queryable), "Join", new Type[4]
			{
				elementType,
				elementType2,
				outerSelectorLambda.Body.Type,
				lambdaExpression.Body.Type
			}, outer.Expression, inner.AsQueryable().Expression, Expression.Quote(outerSelectorLambda), Expression.Quote(innerSelectorLambda), Expression.Quote(lambdaExpression)));
			return outer.Provider.CreateQuery(expression);
		}

		public static IQueryable Join(this IQueryable outer, IEnumerable inner, string outerKeySelector, string innerKeySelector, string resultSelector, params object?[] args)
		{
			return outer.Join(ParsingConfig.Default, inner, outerKeySelector, innerKeySelector, resultSelector, args);
		}

		public static IQueryable<TElement> Join<TElement>(this IQueryable<TElement> outer, ParsingConfig config, IEnumerable<TElement> inner, string outerKeySelector, string innerKeySelector, string resultSelector, params object?[] args)
		{
			return (IQueryable<TElement>)((IQueryable)outer).Join(config, (IEnumerable)inner, outerKeySelector, innerKeySelector, resultSelector, args);
		}

		public static IQueryable<TElement> Join<TElement>(this IQueryable<TElement> outer, IEnumerable<TElement> inner, string outerKeySelector, string innerKeySelector, string resultSelector, params object?[] args)
		{
			return outer.Join(ParsingConfig.Default, inner, outerKeySelector, innerKeySelector, resultSelector, args);
		}

		public static dynamic Last(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute(_last, source);
		}

		public static dynamic Last(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute(_lastPredicate, source, expression);
		}

		public static dynamic Last(this IQueryable source, string predicate, params object?[] args)
		{
			return source.Last(ParsingConfig.Default, predicate, args);
		}

		public static dynamic Last(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			return Execute(_lastPredicate, source, lambda);
		}

		public static dynamic LastOrDefault(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute(_lastDefault, source);
		}

		public static dynamic LastOrDefault(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute(_lastDefaultPredicate, source, expression);
		}

		public static dynamic LastOrDefault(this IQueryable source, string predicate, params object?[] args)
		{
			return source.LastOrDefault(ParsingConfig.Default, predicate, args);
		}

		public static dynamic LastOrDefault(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			return Execute(_lastDefaultPredicate, source, lambda);
		}

		public static long LongCount(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute<long>(_longCount, source);
		}

		public static long LongCount(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute<long>(_longCountPredicate, source, expression);
		}

		public static long LongCount(this IQueryable source, string predicate, params object?[] args)
		{
			return source.LongCount(ParsingConfig.Default, predicate, args);
		}

		public static long LongCount(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			Check.NotNull(lambda, "lambda");
			return Execute<long>(_longCountPredicate, source, lambda);
		}

		public static object Max(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute(_max, source);
		}

		public static object Max(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, typeof(object), predicate, args);
			return Execute(_maxPredicate, source, expression);
		}

		public static object Max(this IQueryable source, string predicate, params object?[] args)
		{
			return source.Max(ParsingConfig.Default, predicate, args);
		}

		public static object Max(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			return Execute(_maxPredicate, source, lambda);
		}

		public static object Min(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute(_min, source);
		}

		public static object Min(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, typeof(object), predicate, args);
			return Execute(_minPredicate, source, expression);
		}

		public static object Min(this IQueryable source, string predicate, params object?[] args)
		{
			return source.Min(ParsingConfig.Default, predicate, args);
		}

		public static object Min(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			return Execute(_minPredicate, source, lambda);
		}

		public static IQueryable OfType(this IQueryable source, Type type)
		{
			Check.NotNull(source, "source");
			Check.NotNull(type, "type");
			Expression expression = OptimizeExpression(Expression.Call(null, _ofType.MakeGenericMethod(type), source.Expression));
			return source.Provider.CreateQuery(expression);
		}

		public static IQueryable OfType(this IQueryable source, ParsingConfig config, string typeName)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(typeName, "typeName");
			if (!new TypeFinder(config, new KeywordsHelper(config)).TryFindTypeByName(typeName, null, forceUseCustomTypeProvider: true, out Type type))
			{
				throw new ParseException(string.Format(CultureInfo.CurrentCulture, "Type '{0}' not found", typeName));
			}
			return source.OfType(type);
		}

		public static IQueryable OfType(this IQueryable source, string typeName)
		{
			return source.OfType(ParsingConfig.Default, typeName);
		}

		public static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, ParsingConfig config, string ordering, params object?[] args)
		{
			return (IOrderedQueryable<TSource>)((IQueryable)source).OrderBy(config, ordering, args);
		}

		public static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string ordering, params object?[] args)
		{
			return source.OrderBy(ParsingConfig.Default, ordering, args);
		}

		public static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, ParsingConfig config, string ordering, IComparer comparer, params object?[] args)
		{
			return (IOrderedQueryable<TSource>)InternalOrderBy(source, config, ordering, comparer, args);
		}

		public static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string ordering, IComparer comparer, params object?[] args)
		{
			return source.OrderBy(ParsingConfig.Default, ordering, comparer, args);
		}

		public static IOrderedQueryable OrderBy(this IQueryable source, ParsingConfig config, string ordering, params object?[] args)
		{
			Check.Args(args, "args");
			if (args.Length != 0 && args[0] != null && args[0].GetType().GetInterfaces().Any((Type i) => i.Name.Contains("IComparer`1")))
			{
				return InternalOrderBy(source, config, ordering, args[0], args);
			}
			return InternalOrderBy(source, config, ordering, null, args);
		}

		public static IOrderedQueryable OrderBy(this IQueryable source, ParsingConfig config, string ordering, IComparer comparer, params object?[] args)
		{
			return InternalOrderBy(source, config, ordering, comparer, args);
		}

		public static IOrderedQueryable OrderBy(this IQueryable source, string ordering, params object?[] args)
		{
			return source.OrderBy(ParsingConfig.Default, ordering, args);
		}

		public static IOrderedQueryable OrderBy(this IQueryable source, string ordering, IComparer comparer, params object?[] args)
		{
			return source.OrderBy(ParsingConfig.Default, ordering, comparer, args);
		}

		internal static IOrderedQueryable InternalOrderBy(IQueryable source, ParsingConfig config, string ordering, object? comparer, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(ordering, "ordering");
			Check.Args(args, "args");
			ParameterExpression[] parameters = new ParameterExpression[1] { ParameterExpressionHelper.CreateParameterExpression(source.ElementType, string.Empty, config.RenameEmptyParameterExpressionNames) };
			IList<DynamicOrdering> list = new ExpressionParser(parameters, ordering, args, config, usedForOrderBy: true).ParseOrdering();
			Expression expression = source.Expression;
			foreach (DynamicOrdering item in list)
			{
				if (comparer == null)
				{
					expression = Expression.Call(typeof(Queryable), item.MethodName, new Type[2]
					{
						source.ElementType,
						item.Selector.Type
					}, expression, Expression.Quote(Expression.Lambda(item.Selector, parameters)));
				}
				else
				{
					Type type = typeof(IComparer<>).MakeGenericType(item.Selector.Type);
					ConstantExpression constantExpression = ((!type.IsInstanceOfType(comparer)) ? Expression.Constant(Activator.CreateInstance(DynamicClassFactory.CreateGenericComparerType(type, comparer.GetType())), type) : Expression.Constant(comparer, type));
					expression = Expression.Call(typeof(Queryable), item.MethodName, new Type[2]
					{
						source.ElementType,
						item.Selector.Type
					}, expression, Expression.Quote(Expression.Lambda(item.Selector, parameters)), constantExpression);
				}
			}
			Expression expression2 = OptimizeExpression(expression);
			return (IOrderedQueryable)source.Provider.CreateQuery(expression2);
		}

		public static IQueryable Page(this IQueryable source, int page, int pageSize)
		{
			Check.NotNull(source, "source");
			Check.Condition(page, (int p) => p > 0, "page");
			Check.Condition(pageSize, (int ps) => ps > 0, "pageSize");
			return source.Skip((page - 1) * pageSize).Take(pageSize);
		}

		public static IQueryable<TSource> Page<TSource>(this IQueryable<TSource> source, int page, int pageSize)
		{
			Check.NotNull(source, "source");
			Check.Condition(page, (int p) => p > 0, "page");
			Check.Condition(pageSize, (int ps) => ps > 0, "pageSize");
			return Queryable.Take(Queryable.Skip(source, (page - 1) * pageSize), pageSize);
		}

		public static PagedResult PageResult(this IQueryable source, int page, int pageSize, int? rowCount = null)
		{
			Check.NotNull(source, "source");
			Check.Condition(page, (int p) => p > 0, "page");
			Check.Condition(pageSize, (int ps) => ps > 0, "pageSize");
			Check.Condition(rowCount, (int? rc) => !rc.HasValue || rc >= 0, "rowCount");
			PagedResult obj = new PagedResult
			{
				CurrentPage = page,
				PageSize = pageSize,
				RowCount = (rowCount ?? source.Count())
			};
			obj.PageCount = (int)Math.Ceiling((double)obj.RowCount / (double)pageSize);
			obj.Queryable = source.Page(page, pageSize);
			return obj;
		}

		public static PagedResult<TSource> PageResult<TSource>(this IQueryable<TSource> source, int page, int pageSize, int? rowCount = null)
		{
			Check.NotNull(source, "source");
			Check.Condition(page, (int p) => p > 0, "page");
			Check.Condition(pageSize, (int ps) => ps > 0, "pageSize");
			Check.Condition(rowCount, (int? rc) => !rc.HasValue || rc >= 0, "rowCount");
			PagedResult<TSource> obj = new PagedResult<TSource>
			{
				CurrentPage = page,
				PageSize = pageSize,
				RowCount = (rowCount ?? Queryable.Count(source))
			};
			obj.PageCount = (int)Math.Ceiling((double)obj.RowCount / (double)pageSize);
			obj.Queryable = source.Page(page, pageSize);
			return obj;
		}

		public static IQueryable Reverse(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Queryable.Reverse((IQueryable<object>)source);
		}

		public static IQueryable Select(this IQueryable source, ParsingConfig config, string selector, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(selector, "selector");
			Check.Args(args, "args");
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source);
			LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, selector, args);
			Expression expression = OptimizeExpression(Expression.Call(typeof(Queryable), "Select", new Type[2]
			{
				source.ElementType,
				lambdaExpression.Body.Type
			}, source.Expression, Expression.Quote(lambdaExpression)));
			return source.Provider.CreateQuery(expression);
		}

		public static IQueryable Select(this IQueryable source, string selector, params object?[] args)
		{
			return source.Select(ParsingConfig.Default, selector, args);
		}

		public static IQueryable<TResult> Select<TResult>(this IQueryable source, ParsingConfig config, string selector, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(selector, "selector");
			Check.Args(args, "args");
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, typeof(TResult), selector, args);
			Expression expression2 = OptimizeExpression(Expression.Call(typeof(Queryable), "Select", new Type[2]
			{
				source.ElementType,
				typeof(TResult)
			}, source.Expression, Expression.Quote(expression)));
			return source.Provider.CreateQuery<TResult>(expression2);
		}

		public static IQueryable<TResult> Select<TResult>(this IQueryable source, string selector, params object?[] args)
		{
			return source.Select<TResult>(ParsingConfig.Default, selector, args);
		}

		public static IQueryable Select(this IQueryable source, ParsingConfig config, Type resultType, string selector, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotNull(resultType, "resultType");
			Check.NotEmpty(selector, "selector");
			Check.Args(args, "args");
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, resultType, selector, args);
			Expression expression2 = OptimizeExpression(Expression.Call(typeof(Queryable), "Select", new Type[2] { source.ElementType, resultType }, source.Expression, Expression.Quote(expression)));
			return source.Provider.CreateQuery(expression2);
		}

		public static IQueryable Select(this IQueryable source, Type resultType, string selector, params object?[] args)
		{
			return source.Select(ParsingConfig.Default, resultType, selector, args);
		}

		public static IQueryable SelectMany(this IQueryable source, ParsingConfig config, string selector, params object?[] args)
		{
			return SelectManyInternal(source, config, null, selector, args);
		}

		public static IQueryable SelectMany(this IQueryable source, string selector, params object?[] args)
		{
			return source.SelectMany(ParsingConfig.Default, selector, args);
		}

		public static IQueryable SelectMany(this IQueryable source, ParsingConfig config, Type resultType, string selector, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotNull(resultType, "resultType");
			Check.NotEmpty(selector, "selector");
			Check.Args(args, "args");
			return SelectManyInternal(source, config, resultType, selector, args);
		}

		public static IQueryable SelectMany(this IQueryable source, Type resultType, string selector, params object?[] args)
		{
			return source.SelectMany(ParsingConfig.Default, resultType, selector, args);
		}

		private static IQueryable SelectManyInternal(IQueryable source, ParsingConfig config, Type? resultType, string selector, params object?[] args)
		{
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source);
			LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, selector, args);
			if (resultType == null)
			{
				if (lambdaExpression.Body.Type.IsArray)
				{
					resultType = lambdaExpression.Body.Type.GetElementType();
				}
				else
				{
					Type[] genericArguments = lambdaExpression.Body.Type.GetGenericArguments();
					resultType = (genericArguments.Any() ? genericArguments[0] : typeof(object));
				}
			}
			Type type = typeof(IEnumerable<>).MakeGenericType(resultType);
			Type type2 = source.Expression.Type.GetTypeInfo().GetGenericTypeArguments()[0];
			lambdaExpression = Expression.Lambda(typeof(Func<, >).MakeGenericType(type2, type), lambdaExpression.Body, lambdaExpression.Parameters);
			Expression expression = OptimizeExpression(Expression.Call(typeof(Queryable), "SelectMany", new Type[2] { source.ElementType, resultType }, source.Expression, Expression.Quote(lambdaExpression)));
			return source.Provider.CreateQuery(expression);
		}

		public static IQueryable<TResult> SelectMany<TResult>(this IQueryable source, ParsingConfig config, string selector, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(selector, "selector");
			Check.Args(args, "args");
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source);
			LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, selector, args);
			Type type = source.Expression.Type.GetTypeInfo().GetGenericTypeArguments()[0];
			Type type2 = typeof(IEnumerable<>).MakeGenericType(typeof(TResult));
			lambdaExpression = Expression.Lambda(typeof(Func<, >).MakeGenericType(type, type2), lambdaExpression.Body, lambdaExpression.Parameters);
			Expression expression = OptimizeExpression(Expression.Call(typeof(Queryable), "SelectMany", new Type[2]
			{
				source.ElementType,
				typeof(TResult)
			}, source.Expression, Expression.Quote(lambdaExpression)));
			return source.Provider.CreateQuery<TResult>(expression);
		}

		public static IQueryable<TResult> SelectMany<TResult>(this IQueryable source, string selector, params object?[] args)
		{
			return source.SelectMany<TResult>(ParsingConfig.Default, selector, args);
		}

		public static IQueryable SelectMany(this IQueryable source, ParsingConfig config, string collectionSelector, string resultSelector, object?[]? collectionSelectorArgs = null, params object?[]? resultSelectorArgs)
		{
			return source.SelectMany(collectionSelector, resultSelector, "x", "y", collectionSelectorArgs, resultSelectorArgs);
		}

		public static IQueryable SelectMany(this IQueryable source, string collectionSelector, string resultSelector, object[]? collectionSelectorArgs = null, params object[]? resultSelectorArgs)
		{
			return source.SelectMany(ParsingConfig.Default, collectionSelector, resultSelector, "x", "y", collectionSelectorArgs, resultSelectorArgs);
		}

		public static IQueryable SelectMany(this IQueryable source, ParsingConfig config, string collectionSelector, string resultSelector, string collectionParameterName, string resultParameterName, object?[]? collectionSelectorArgs = null, params object[]? resultSelectorArgs)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(collectionSelector, "collectionSelector");
			Check.NotEmpty(collectionParameterName, "collectionParameterName");
			Check.NotEmpty(resultSelector, "resultSelector");
			Check.NotEmpty(resultParameterName, "resultParameterName");
			Check.Args(collectionSelectorArgs, "collectionSelectorArgs");
			Check.Args(resultSelectorArgs, "resultSelectorArgs");
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source);
			LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, collectionSelector, collectionSelectorArgs);
			Type type = source.Expression.Type.GetGenericArguments()[0];
			Type type2 = lambdaExpression.Body.Type.GetGenericArguments()[0];
			Type type3 = typeof(IEnumerable<>).MakeGenericType(type2);
			lambdaExpression = Expression.Lambda(typeof(Func<, >).MakeGenericType(type, type3), lambdaExpression.Body, lambdaExpression.Parameters);
			ParameterExpression parameterExpression = ParameterExpressionHelper.CreateParameterExpression(source.ElementType, collectionParameterName, config.RenameEmptyParameterExpressionNames);
			ParameterExpression parameterExpression2 = ParameterExpressionHelper.CreateParameterExpression(type2, resultParameterName, config.RenameEmptyParameterExpressionNames);
			LambdaExpression lambdaExpression2 = DynamicExpressionParser.ParseLambda(config, createParameterCtor, new ParameterExpression[2] { parameterExpression, parameterExpression2 }, null, resultSelector, resultSelectorArgs);
			Type type4 = lambdaExpression2.Body.Type;
			Expression expression = OptimizeExpression(Expression.Call(typeof(Queryable), "SelectMany", new Type[3] { source.ElementType, type2, type4 }, source.Expression, Expression.Quote(lambdaExpression), Expression.Quote(lambdaExpression2)));
			return source.Provider.CreateQuery(expression);
		}

		public static IQueryable SelectMany(this IQueryable source, string collectionSelector, string resultSelector, string collectionParameterName, string resultParameterName, object?[]? collectionSelectorArgs = null, params object?[]? resultSelectorArgs)
		{
			return source.SelectMany(ParsingConfig.Default, collectionSelector, resultSelector, collectionParameterName, resultParameterName, collectionSelectorArgs, resultSelectorArgs);
		}

		public static dynamic Single(this IQueryable source)
		{
			Check.NotNull(source, "source");
			Expression expression = OptimizeExpression(Expression.Call(typeof(Queryable), "Single", new Type[1] { source.ElementType }, source.Expression));
			return source.Provider.Execute(expression);
		}

		public static dynamic Single(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute(_singlePredicate, source, expression);
		}

		public static dynamic Single(this IQueryable source, string predicate, params object?[] args)
		{
			return source.Single(ParsingConfig.Default, predicate, args);
		}

		public static dynamic Single(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			return Execute(_singlePredicate, source, lambda);
		}

		public static dynamic SingleOrDefault(this IQueryable source)
		{
			Check.NotNull(source, "source");
			Expression expression = OptimizeExpression(Expression.Call(typeof(Queryable), "SingleOrDefault", new Type[1] { source.ElementType }, source.Expression));
			return source.Provider.Execute(expression);
		}

		public static dynamic SingleOrDefault(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute(_singleDefaultPredicate, source, expression);
		}

		public static dynamic SingleOrDefault(this IQueryable source, string predicate, params object?[] args)
		{
			return source.SingleOrDefault(ParsingConfig.Default, predicate, args);
		}

		public static dynamic SingleOrDefault(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			Check.NotNull(lambda, "lambda");
			return Execute(_singleDefaultPredicate, source, lambda);
		}

		public static IQueryable Skip(this IQueryable source, int count)
		{
			Check.NotNull(source, "source");
			Check.Condition(count, (int x) => x >= 0, "count");
			if (count == 0)
			{
				return source;
			}
			return CreateQuery(_skip, source, Expression.Constant(count));
		}

		public static IQueryable SkipWhile(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotNull(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return CreateQuery(_skipWhilePredicate, source, expression);
		}

		public static IQueryable SkipWhile(this IQueryable source, string predicate, params object?[] args)
		{
			return source.SkipWhile(ParsingConfig.Default, predicate, args);
		}

		public static object Sum(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute<object>(QueryableMethodFinder.GetMethod("Sum", source.ElementType), source);
		}

		public static object Sum(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute<object>(QueryableMethodFinder.GetMethod("Sum", lambdaExpression.GetReturnType(), 1), source, lambdaExpression);
		}

		public static object Sum(this IQueryable source